# Databases from the API and CI

Everything the console does with a managed database is on the API, so you need no extra tooling. The samples use the helper from [Using the Zaroz API](/guides/api/overview) (`$ZAROZ_API` and `$AUTH`) and `jq`. `$DB` is the database's service instance id: the id in the console address of the database, or the `service_instance_id` your purchase returned.

Use an [API token](/api-tokens/getting-started) scoped to **one project**, holding only the permissions the script needs. Revealing or rotating the password counts as operating the database, so a token that only reads cannot do it.

## Operations

Changes that take time (a backup, a restore, an export, a rotation, an upgrade) answer `202` with an **operation**. Poll it until its `state` is `succeeded`, `failed` or `cancelled`:

```bash
wait_for() {  # wait_for <operation id>
  while :; do
    op=$(curl -sS "$ZAROZ_API/service-instances/$DB/database/operations/$1" -H "$AUTH")
    state=$(jq -r .state <<<"$op")
    case "$state" in
      succeeded) return 0 ;;
      failed|cancelled) jq -r '.error // "operation \(.state)"' <<<"$op" >&2; return 1 ;;
    esac
    sleep 5
  done
}
```

`progress` (0 to 100) and `phase` say how far it got. A failed operation says whether it was rolled back (`rolled_back`) and whether retrying is safe (`retryable`).

## Create a database

A managed database is bought like any other product ([Subscriptions and billing](/concepts/billing)). Send an `Idempotency-Key` header on the purchase so a retried request never buys twice. When the service is ready, `GET /service-instances/$DB/database` describes it: engine, version, copies, health and what it supports.

## Connection details and the password

```bash
# Addresses, ports, the database name and the user (never the password)
curl -sS "$ZAROZ_API/service-instances/$DB/database/connection" -H "$AUTH"

# The password of the default user
curl -sS -X POST "$ZAROZ_API/service-instances/$DB/database/credentials/reveal" -H "$AUTH" | jq -r .password

# The Zaroz certificate, for a client outside Zaroz
curl -sS "$ZAROZ_API/service-instances/$DB/database/connection/ca" -H "$AUTH" -o zaroz-ca.pem
```

Every reveal is recorded on the database's timeline and in your organization's audit log. Prefer **linked variables** for apps on Zaroz ([Connect an app to a managed database](/guides/databases/connect-tls)): the app gets the password without anyone reading it.

## Rotate the password

```bash
op=$(curl -sS -X POST "$ZAROZ_API/service-instances/$DB/database/credentials/rotate" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d '{"grace": "one_hour"}' | jq -r .id)
wait_for "$op"
```

`grace` is how long the old password keeps working: `none` (it stops at once), `one_hour` or `twenty_four_hours`. Restart the apps that use the database within that time; linked variables pick up the new password on restart.

## Back up and wait

```bash
op=$(curl -sS -X POST "$ZAROZ_API/service-instances/$DB/database/backups" -H "$AUTH" | jq -r .id)
wait_for "$op"
# The backups, and the span you can restore to
curl -sS "$ZAROZ_API/service-instances/$DB/database/backups" -H "$AUTH" | jq '{restorable_from, restorable_to, backups: [.backups[] | .id]}'
```

## Export and download

```bash
op=$(curl -sS -X POST "$ZAROZ_API/service-instances/$DB/database/exports" \
  -H "$AUTH" -H "Content-Type: application/json" -d '{"format": "pg_custom"}' | jq -r .id)
wait_for "$op"
url=$(curl -sS "$ZAROZ_API/service-instances/$DB/database/exports/$op/link" -H "$AUTH" | jq -r .url)
curl -sS "$url" -o backup.dump
```

PostgreSQL exports as `sql`, `sql_gz` or `pg_custom` (the format `pg_restore` reads). The file is kept for seven days; each call to `/link` gives a fresh download address valid for 24 hours.

## Allow a source address

From outside Zaroz, a database with public access can be limited to the addresses you list:

```bash
curl -sS -X POST "$ZAROZ_API/service-instances/$DB/database/network/rules" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d '{"cidr": "203.0.113.7/32", "label": "office"}'
```

`GET .../network` shows public access, the rules and how many you may add (`max_rules`). Apps in the same project never need a rule.

## Read the timeline

```bash
curl -sS "$ZAROZ_API/service-instances/$DB/database/events?limit=50" -H "$AUTH" \
  | jq -r '.events[] | "\(.created_at) \(.kind)"'
```

The timeline holds lifecycle changes, operations, health changes, maintenance, backups and access (password viewed or rotated, users, network changes). Filter with `kinds=` (comma-separated) and page with the `next` cursor (`after_created_at` and `after_id`). An event never carries a password.

## Databases in CI

### Tests: use a throwaway database

Run your tests against a database container that lives as long as the CI job, not against a managed database. It is faster, free, and a test can never touch real data. GitHub Actions:

```yaml
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:18
        env:
          POSTGRES_PASSWORD: test
        ports: ["5432:5432"]
        options: >-
          --health-cmd "pg_isready -U postgres"
          --health-interval 5s --health-retries 10
    env:
      DATABASE_URL: postgres://postgres:test@localhost:5432/postgres
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npm test
```

Forgejo Actions and GitLab CI accept the same `services:` idea; see [CI overview](/guides/ci/overview).

### Migrations on deploy

Run migrations against the managed database as a step of your deploy, with a backup just before it:

```bash
set -euo pipefail
# 1. A backup to go back to
op=$(curl -sS -X POST "$ZAROZ_API/service-instances/$DB/database/backups" -H "$AUTH" | jq -r .id)
wait_for "$op"
started=$(date -u +%Y-%m-%dT%H:%M:%SZ)

# 2. The connection details and the password, never stored in the repository
conn=$(curl -sS "$ZAROZ_API/service-instances/$DB/database/connection" -H "$AUTH")
export PGPASSWORD=$(curl -sS -X POST "$ZAROZ_API/service-instances/$DB/database/credentials/reveal" -H "$AUTH" | jq -r .password)
curl -sS "$ZAROZ_API/service-instances/$DB/database/connection/ca" -H "$AUTH" -o zaroz-ca.pem

# 3. Migrate (use your tool; PG* variables from $conn as on the Connect tab)
if ! npx prisma migrate deploy; then
  echo "Migration failed. To go back to the state before it:" >&2
  echo "  curl -X POST $ZAROZ_API/service-instances/$DB/database/restore -H \"\$AUTH\" -H 'Content-Type: application/json' -d '{\"target\": {\"kind\": \"point_in_time\", \"at\": \"$started\"}}'" >&2
  exit 1
fi
```

A restore can itself be undone for a while (`POST .../restore/undo`), so trying one is safe.

### Reaching the database from a CI runner

A CI runner is outside Zaroz. Either turn on public access and add the runner's outgoing address range as an allowed source, or run the migration from inside your project (for example as a step of the app's start command, or a job on Zaroz), where no rule is needed.
