# Galon Backend

> PostgreSQL for your app: a database hosted by Galon or your own, with versioned migrations and backups.

## Before you start

- A Galon account, a project and a key with `database:read` (read) or `database:create`. A database belongs to the environment of the key (test or live).

## Quickstart

Every example reads `GALON_API_BASE` (`https://api.galon.ai/v1`) and `GALON_API_KEY` from the environment and prints the HTTP status and the JSON body.

**1. Set your key.** Export the base URL and your key.

**curl**

```bash
export GALON_API_BASE="https://api.galon.ai/v1"
export GALON_API_KEY="gln_..."
```

**2. Create a hosted database.** `name`: 3 to 40 characters, lowercase letters, digits and `-`. The `Idempotency-Key` must have 16 to 128 characters. The answer carries `url`, your `DATABASE_URL` (TLS `verify-full`): store it as a secret.

**curl**

```bash
curl -sS -X POST "$GALON_API_BASE/backend/hosted/databases" \
  -H "Authorization: Bearer $GALON_API_KEY" \
  -H "Idempotency-Key: quickstart-db-00000001" \
  -H "Content-Type: application/json" \
  -d '{"name": "quickstart-db"}' \
  -w '\n%{http_code}\n'
```

**Python 3 (standard library)**

```python
import json, os, urllib.error, urllib.request

req = urllib.request.Request(
    os.environ["GALON_API_BASE"] + "/backend/hosted/databases",
    data=json.dumps({"name": "quickstart-db"}).encode(),
    headers={"Authorization": "Bearer " + os.environ["GALON_API_KEY"],
             "Idempotency-Key": "quickstart-db-00000001",
             "Content-Type": "application/json"},
    method="POST",
)
try:
    with urllib.request.urlopen(req) as res:
        print(res.status, json.load(res))
except urllib.error.HTTPError as err:  # the error body carries detail.code and detail.next_action
    print(err.code, json.load(err))
```

**Node.js 18+ (fetch)**

```js
const res = await fetch(`${process.env.GALON_API_BASE}/backend/hosted/databases`, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.GALON_API_KEY}`, "Idempotency-Key": "quickstart-db-00000001", "Content-Type": "application/json" },
  body: JSON.stringify({name: "quickstart-db"}),
});
console.log(res.status, JSON.stringify(await res.json()));
```

**3. Run a migration.** Migrations are versioned and applied in order, once. No `BEGIN`/`COMMIT` inside: each migration runs in its own transaction. The answer is `202` with an operation to read with `GET /v1/backend/operations/{operation_id}`.

**curl**

```bash
curl -sS -X POST "$GALON_API_BASE/backend/databases/${GALON_DATABASE_ID}/migrations" \
  -H "Authorization: Bearer $GALON_API_KEY" \
  -H "Idempotency-Key: quickstart-migration-0001" \
  -H "Content-Type: application/json" \
  -d '{"migrations": [{"version": "1", "name": "init", "sql": "create table notes (id bigserial primary key, body text);"}]}' \
  -w '\n%{http_code}\n'
```

**Python 3 (standard library)**

```python
import json, os, urllib.error, urllib.request

req = urllib.request.Request(
    os.environ["GALON_API_BASE"] + "/backend/databases/" + os.environ["GALON_DATABASE_ID"] + "/migrations",
    data=json.dumps({"migrations": [{"version": "1", "name": "init", "sql": "create table notes (id bigserial primary key, body text);"}]}).encode(),
    headers={"Authorization": "Bearer " + os.environ["GALON_API_KEY"],
             "Idempotency-Key": "quickstart-migration-0001",
             "Content-Type": "application/json"},
    method="POST",
)
try:
    with urllib.request.urlopen(req) as res:
        print(res.status, json.load(res))
except urllib.error.HTTPError as err:  # the error body carries detail.code and detail.next_action
    print(err.code, json.load(err))
```

**Node.js 18+ (fetch)**

```js
const res = await fetch(`${process.env.GALON_API_BASE}/backend/databases/${process.env.GALON_DATABASE_ID}/migrations`, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.GALON_API_KEY}`, "Idempotency-Key": "quickstart-migration-0001", "Content-Type": "application/json" },
  body: JSON.stringify({migrations: [{version: "1", name: "init", sql: "create table notes (id bigserial primary key, body text);"}]}),
});
console.log(res.status, JSON.stringify(await res.json()));
```

**4. Check the connection.** Galon connects with TLS and reports what it found.

**curl**

```bash
curl -sS -X POST "$GALON_API_BASE/backend/databases/${GALON_DATABASE_ID}/check" \
  -H "Authorization: Bearer $GALON_API_KEY" \
  -w '\n%{http_code}\n'
```

**Python 3 (standard library)**

```python
import json, os, urllib.error, urllib.request

req = urllib.request.Request(
    os.environ["GALON_API_BASE"] + "/backend/databases/" + os.environ["GALON_DATABASE_ID"] + "/check",
    headers={"Authorization": "Bearer " + os.environ["GALON_API_KEY"]},
    method="POST",
)
try:
    with urllib.request.urlopen(req) as res:
        print(res.status, json.load(res))
except urllib.error.HTTPError as err:  # the error body carries detail.code and detail.next_action
    print(err.code, json.load(err))
```

**Node.js 18+ (fetch)**

```js
const res = await fetch(`${process.env.GALON_API_BASE}/backend/databases/${process.env.GALON_DATABASE_ID}/check`, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.GALON_API_KEY}` },
});
console.log(res.status, JSON.stringify(await res.json()));
```

## Concepts

**Hosted or your own.** `POST /v1/backend/hosted/databases` creates a PostgreSQL database hosted by Galon. `POST /v1/backend/databases` with `{name, dsn}` declares your own (TLS `sslmode=verify-full` only; the connection string is encrypted and never returned).

**Connection string.** Returned at creation and by `POST /v1/backend/databases/{id}/connection/reveal`, and nowhere else.

**Migrations.** `{migrations: [{version, name, sql}]}`: `version` is a number, applied in increasing order; a migration already applied with a different content is refused (`backend_migration_checksum_mismatch`).

**Backups.** `POST /v1/backend/databases/{id}/backups` with a Galon Storage `bucket_id` writes a backup to that bucket (`202`, then read the operation).

## API reference

These routes are served by the code but are not in the OpenAPI contract yet:

| Method | Path | Auth | What it does |
|---|---|---|---|
| POST | `/v1/backend/hosted/databases` | key `database:create` | Create a hosted database |
| POST | `/v1/backend/databases` | key `database:create` | Declare your own database |
| GET | `/v1/backend/databases` | key `database:read` (read) or `database:create` | List databases |
| POST | `/v1/backend/databases/{database_id}/migrations` | key `database:create` | Apply migrations |
| POST | `/v1/backend/databases/{database_id}/backups` | key `database:create` | Back up to a bucket |
| POST | `/v1/backend/databases/{database_id}/connection/reveal` | key `database:create` | Return the connection string |
| GET | `/v1/backend/operations/{operation_id}` | key `database:read` (read) or `database:create` | Read an operation |

## Errors

Every error is JSON: `{"detail": {"code", "message", "next_action"}}`. `next_action.code` is stable, `next_action.hint` says what to do next, and `console_url` is added when a person must act. The codes below are those this service returns.

| Status | Code | When | next_action |
|---|---|---|---|
| 401 | `api_key_missing` | No `Authorization: Bearer` header. | `use_valid_api_key` |
| 403 | `scope_missing` | The key lacks `database:create`. | `add_missing_scope` |
| 403 | `backend_byo_tenant_not_allowed` | Backend is not open to this account. | `check_project_access` |
| 400 | `idempotency_key_required` | No `Idempotency-Key` header. | `fix_request` |
| 400 | `idempotency_key_invalid` | Not 16 to 128 characters of `[A-Za-z0-9_.:-]`. | `fix_request` |
| 400 | `body_fields_invalid` | A missing or unknown field. | `fix_request` |
| 409 | `idempotency_conflict` | Same key, different body. | `resolve_conflict` |
| 409 | `backend_database_name_taken` | This name is already used in the project. | `resolve_conflict` |
| 409 | `backend_hosted_limit_reached` | The project has its maximum of hosted databases. | `raise_limit_or_plan` |
| 409 | `backend_confirmation_required` | A live database needs `confirm: true`. | `resolve_conflict` |
| 400 | `backend_dsn_invalid` | The connection string cannot be read. | `fix_request` |
| 400 | `backend_dsn_tls_required` | The connection string disables TLS. | `fix_request` |
| 400 | `backend_migration_sql_invalid` | An empty or unreadable migration. | `fix_request` |
| 400 | `backend_migration_transaction_control_forbidden` | `BEGIN`, `COMMIT` or `ROLLBACK` in a migration. | `fix_request` |
| 409 | `backend_migration_checksum_mismatch` | An applied version with a different content. | `resolve_conflict` |
| 404 | `backend_database_not_found` | No database with this id for this key. | `check_resource_id` |
| 503 | `backend_backup_unavailable` | No Storage bucket is connected for backups. | `retry_later` |
| 503 | `backend_temporarily_unavailable` | Temporary: retry with the same Idempotency-Key. | `retry_later` |

| next_action | What to do |
|---|---|
| `use_valid_api_key` | Send a valid Galon API key as 'Authorization: Bearer <key>'. If the key was revoked or has expired, create a new one in the console and retry with it. |
| `add_missing_scope` | This key does not have the scope this call needs. Create a key with that scope in the console, then retry the same call with the new key. |
| `check_project_access` | This project or key is not allowed to do this. Its owner must review the project, its key and its account in the console. |
| `fix_request` | The request is invalid. Fix it as 'message' and 'field' say, using the OpenAPI contract, then send it again. Do not retry it unchanged. |
| `resolve_conflict` | The request conflicts with the resource state or with an earlier request under the same Idempotency-Key. Read the resource first; for a new intent, use a new Idempotency-Key. |
| `raise_limit_or_plan` | A plan quota or a spending limit is reached. Raise the limit or change the plan in the console, or wait for the next period, then retry. |
| `check_resource_id` | Nothing with this id is visible to this key. List the resources to get a valid id, and check that the key belongs to the right project and environment (test or live). |
| `retry_later` | Temporary error on Galon's side. Retry with exponential backoff and the same Idempotency-Key; if it lasts, contact support with the X-Request-Id header. |

## Limits, free tier and pricing

Read from the platform code each time this page is served.

| Limit | Value |
|---|---|
| Hosted databases per project (default) | **3** |
| Hosted database storage, in MB (default) | **500** |
| Connections per hosted database (default) | **20** |

Billed per started hour from the prepaid balance, in US dollars, read from the platform each time this page is served. Creating a database needs 24 hours of balance.

| Plan | Database | Per hour | About per month |
|---|---|---|---|
| `micro` | hosted by Galon | 0.01302 USD | 9.5046 USD |
| `byo` | your own database | 0.002742 USD | 2.00166 USD |

Beyond what a plan includes: disk 0.11 USD per GB-month, up to 8 GB per database.

When the balance no longer covers one hour, the database becomes read-only; after 72 hours it is paused (no connection, data kept). A database hosted by Galon is deleted 30 days after the pause, never earlier, and only after notices to the administrators at the pause, 7 days and 1 day before; a top-up that covers what is due reopens it before then.

## FAQ

**Which PostgreSQL version?**

Hosted databases run PostgreSQL 16, with TLS `verify-full`.

**Can I bring my own database?**

Yes: declare its connection string; Galon runs your migrations and backups on it.

**Is there a connection pooler?**

No pooler is offered today: connect directly with the `url`.

## More

- [Authentication](/cloud/docs/platform/authentication)
- [Projects: live and test](/cloud/docs/platform/environments)
- [Prepaid balance](/cloud/docs/platform/balance)
- [Quotas and rate limits](/cloud/docs/platform/quotas)
- [Terms of Service](/legal/terms-of-service)
- [Acceptable Use Policy](/legal/acceptable-use-policy)
- [Privacy Policy](/legal/privacy-policy)
- [Refunds and prepaid balance](/legal/prepaid-balance-and-refund-policy)
- [Legal Notice](/legal/legal-notice)
- [All legal documents](/legal)
