API documentation

Every opendb project has an HTTP API for its data and for its users' authentication. It works from any language or framework: all you need is HTTP requests.

Before you start

Every route hangs off your project's URL, which you'll find in the dashboard under Resumen (Overview):

ServicePathWhat for
Data/rest/v1Read and write your tables, and call database functions
Authentication/auth/v1Sign-up, login, Google, sessions and password recovery
Migrations/migrations/v1Apply migrations (Prisma or SQL) with a project token

The examples use these variables; replace them with your project's:

URL="https://api.yourdomain.com/p/myapp"   # Resumen → project URL
ANON="eyJhbGciOiJIUzI1NiIs..."             # Resumen → anon key

The dashboard also has generated docs for each table in your project, under API, with your column names already filled in.

Keys and headers

Each project has two keys. They only work on their own project: with another project's key, the API answers 403.

KeyWhere it goesWhat it can do
anonIn your frontend or mobile app. It's public.Whatever your RLS policies allow the anon role (no session), or the user whose token you send.
service_roleOnly on your server. Never in the browser.Everything: it bypasses RLS. Use it for admin tasks and backends.

Every request carries two headers:

curl "$URL/rest/v1/todos" \
  -H "apikey: $ANON" \
  -H "Authorization: Bearer $TOKEN"

Authentication

Your app's users sign up and log in at /auth/v1. Each login returns an access_token, valid for one hour, and a refresh_token to get a new one without typing the password again.

Sign-up

POST /auth/v1/signup

curl "$URL/auth/v1/signup" \
  -H "apikey: $ANON" \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"Sup3r-secret!","data":{"name":"Ana"}}'

data is optional: it's stored in the user's user_metadata. The response depends on how the project is set up:

Other errors: 422 weak_password if the password is shorter than 6 characters, and 422 user_already_exists if the email is already registered.

Log in

POST /auth/v1/token?grant_type=password

curl "$URL/auth/v1/token?grant_type=password" \
  -H "apikey: $ANON" \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"Sup3r-secret!"}'
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "bearer",
  "expires_in": 3600,
  "expires_at": 1795373401,
  "refresh_token": "v2kq7fx3...",
  "user": { "id": "f7a14adc-...", "email": "[email protected]", "app_metadata": { ... }, "user_metadata": { "name": "Ana" } }
}

Keep both tokens. With a wrong email or password it answers 400 invalid_credentials.

With Google

First, turn it on in the dashboard: Ajustes → Iniciar sesión con Google (Settings → Sign in with Google), with your Google OAuth client's Client ID and Client secret. Also add the address your app returns to under URLs de redirección permitidas (allowed redirect URLs); if it isn't on the list, the user is sent to the site URL instead.

To log in, send the user (with a link or location.href, not with fetch) to:

GET /auth/v1/authorize?provider=google&redirect_to=https://myapp.com/auth

It takes no apikey: it's a browser navigation. After picking their account at Google, the user comes back to redirect_to in one of two ways:

Simple flow: the tokens arrive in the URL fragment (the part after #, which is never sent to any server):

https://myapp.com/auth#access_token=eyJ...&expires_in=3600&refresh_token=v2kq...&token_type=bearer
const params = new URLSearchParams(location.hash.slice(1))
const session = {
  access_token: params.get('access_token'),
  refresh_token: params.get('refresh_token'),
}
history.replaceState(null, '', location.pathname) // removes the tokens from the address bar

PKCE flow (recommended): the tokens never go through the URL (PROJECT_URL is your project's URL). Before redirecting, generate a random code_verifier, keep it, and send its SHA-256 in base64url as code_challenge:

const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)))
sessionStorage.setItem('pkce', verifier)
const challenge = base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))))
location.href = `${PROJECT_URL}/auth/v1/authorize?provider=google&redirect_to=${encodeURIComponent('https://myapp.com/auth')}`
  + `&code_challenge=${challenge}&code_challenge_method=s256`

function base64url(bytes) {
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}

Google sends the user back to https://myapp.com/auth?code=.... Exchange that code for the session:

POST /auth/v1/token?grant_type=pkce

curl "$URL/auth/v1/token?grant_type=pkce" \
  -H "apikey: $ANON" \
  -H "Content-Type: application/json" \
  -d '{"auth_code":"THE_CODE_FROM_THE_URL","code_verifier":"THE_SAVED_VERIFIER"}'

The response is the same as for Log in. If the user cancels or something fails, they come back with error and error_description in the URL.

To see which login methods a project has turned on: GET /auth/v1/settings (with apikey) returns, among others, external.email and external.google.

Current user

GET /auth/v1/user

curl "$URL/auth/v1/user" -H "apikey: $ANON" -H "Authorization: Bearer $TOKEN"

Without the user's token it answers 403 bad_jwt. To change their email, password or data:

PUT /auth/v1/user

curl -X PUT "$URL/auth/v1/user" \
  -H "apikey: $ANON" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"data":{"name":"Ana María"}}'     # or {"password":"..."} or {"email":"..."}

Refresh the session

The access_token expires after one hour (expires_at, in Unix seconds). Before it does, ask for a new one:

POST /auth/v1/token?grant_type=refresh_token

curl "$URL/auth/v1/token?grant_type=refresh_token" \
  -H "apikey: $ANON" \
  -H "Content-Type: application/json" \
  -d '{"refresh_token":"v2kq7fx3..."}'

The response carries a new access_token and a new refresh_token: keep both. Each refresh_token is used once; the previous one is accepted for only a few more seconds, to cover two tabs refreshing at the same time.

Log out

POST /auth/v1/logout

curl -X POST "$URL/auth/v1/logout" -H "apikey: $ANON" -H "Authorization: Bearer $TOKEN"

It answers 204 and revokes the user's refresh_tokens. Their access_token stays valid until it expires (one hour at most), so delete it from your app too.

Password recovery

POST /auth/v1/recover

curl "$URL/auth/v1/recover" \
  -H "apikey: $ANON" \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]"}'

It sends an email with a link to log in and change the password (with PUT /auth/v1/user). It needs SMTP set up on the server; it answers 200 whether or not the email exists, so it doesn't reveal who is registered.

The token

The access_token is a JWT. These are the fields you'll use in your app and your policies:

FieldWhat it is
subThe user's id (UUID). In SQL, auth.uid().
roleauthenticated for logged-in users.
emailTheir email.
app_metadata.rolesYour app's roles, assigned from the dashboard (admin, editor…). The user can't change them.
user_metadataThe data they sent at sign-up or with PUT /auth/v1/user. The user can change it: don't use it to grant permissions.
expWhen it expires (Unix seconds).

A role change takes effect when the user refreshes their token.

Data (REST API)

Each table in your database is a route: the todos table is at /rest/v1/todos. A new table shows up as soon as you create it, with RLS on: without policies, nobody sees its rows (see Security with RLS).

Read

GET /rest/v1/todos?select=id,title,done&order=created_at.desc&limit=20

curl "$URL/rest/v1/todos?select=id,title,done&order=created_at.desc&limit=20" \
  -H "apikey: $ANON" -H "Authorization: Bearer $TOKEN"
[{"id":1,"title":"Buy bread","done":false}]
ParameterExampleWhat it does
selectselect=id,titleColumns to return. Without it, all of them.
orderorder=created_at.desc,id.ascOrder; add .nullsfirst or .nullslast if needed.
limit, offsetlimit=20&offset=40Pagination.

Counting rows: add Prefer: count=exact and read the response's Content-Range header, for example 0-19/137 (137 in total).

One row as an object instead of a list: add Accept: application/vnd.pgrst.object+json. If there isn't exactly one row, it answers 406 with PGRST116.

Filters

A filter is column=operator.value. Several filters combine with "and".

OperatorExampleMeans
eq, neqdone=eq.falseEqual, not equal
gt, gte, lt, lteprice=gte.10Greater, greater or equal, less, less or equal
like, iliketitle=ilike.*bread*Contains (* is the wildcard); ilike ignores case
inid=in.(1,2,3)Is in the list
isdeleted_at=is.nullIs null, true or false
not.list_id=not.is.nullNegates any operator
oror=(done.eq.true,title.ilike.*luis*)Matches at least one condition

Values go in the URL: encode with encodeURIComponent any that have spaces, commas or special characters.

Relations

If a table has a foreign key to another one, you can fetch both in a single request by putting the related table in select:

curl "$URL/rest/v1/todos?select=title,lists(name)" -H "apikey: $ANON" -H "Authorization: Bearer $TOKEN"
[{"title":"Call Luis","lists":{"name":"Home"}}]

It works both ways: lists?select=name,todos(title) returns each list with its tasks.

Insert

POST /rest/v1/todos

curl "$URL/rest/v1/todos" \
  -H "apikey: $ANON" -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Prefer: return=representation" \
  -d '{"title":"Buy bread"}'

It answers 201. With Prefer: return=representation it returns the created rows (with their id and default values); without it, the response is empty.

To insert several rows, send a list. Every object must have the same keys; otherwise it answers 400 PGRST102:

-d '[{"title":"Call Luis","done":false},{"title":"Pay the power bill","done":true}]'

Update

PATCH /rest/v1/todos?id=eq.1

curl -X PATCH "$URL/rest/v1/todos?id=eq.1" \
  -H "apikey: $ANON" -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Prefer: return=representation" \
  -d '{"done":true}'

Always add a filter. A PATCH or DELETE without a filter affects every row the user can see under your policies. With the service_role key, the whole table.

Insert or update (upsert)

Inserts the row or, if one with the same key already exists, updates it:

curl "$URL/rest/v1/profiles?on_conflict=user_id" \
  -H "apikey: $ANON" -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Prefer: resolution=merge-duplicates,return=representation" \
  -d '{"name":"Ana María"}'

on_conflict is the unique column that decides whether the row exists (without it, the primary key). A generated always as identity column can't be sent: for an upsert by id, define it as generated by default as identity.

Delete

DELETE /rest/v1/todos?id=eq.1

curl -X DELETE "$URL/rest/v1/todos?id=eq.1" -H "apikey: $ANON" -H "Authorization: Bearer $TOKEN"

It answers 204, or the deleted rows with Prefer: return=representation. As with updates: always add a filter.

Functions (RPC)

A function in your database is called at /rest/v1/rpc/name, with its arguments in the body:

curl "$URL/rest/v1/rpc/add" \
  -H "apikey: $ANON" -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"a":2,"b":3}'

If the function only reads data, you can also call it with GET /rest/v1/rpc/add?a=2&b=3. A function that returns rows takes the same select, filters and order as a table.

Security with RLS

Row Level Security decides which rows each request can read and write. In opendb every new table is born with RLS on and no policies: nobody sees anything until you write them. Requests reach the database with one of these roles:

Your policies can use these functions:

FunctionReturns
auth.uid()The id of the request's user, or null without a session.
opendb.has_role('admin')true if the user has that app role (app_metadata.roles).
opendb.jwt()All the token's data, as jsonb.
-- Each user reads and writes only their own tasks
alter table todos add column user_id uuid not null default auth.uid();
create policy "own rows" on todos for all to authenticated
  using (user_id = auth.uid()) with check (user_id = auth.uid());

-- Your app's admins see all of them
create policy "admins see all" on todos for select to authenticated
  using (opendb.has_role('admin'));

-- A public, read-only catalog, also without a session
create policy "public read" on products for select to anon, authenticated using (true);

With default auth.uid() you don't need to send user_id when inserting: the database fills in the request's user. Write the policies in the dashboard's SQL editor; API → Acceso y RLS (Access and RLS) shows which tables have policies and which don't.

If a policy blocks a write, the API answers 42501 ("new row violates row-level security policy"): 401 without a session and 403 with one. If it blocks a read, there's no error: the response is just empty.

Errors

Errors are JSON. Data errors carry code, message, details and hint; authentication errors carry code, error_code and msg.

StatusResponseCause
401No API key found in requestThe apikey header is missing (or the key is in the URL).
401UnauthorizedThe key isn't valid.
403You cannot consume this serviceThe key belongs to another project.
401PGRST301The user's token is invalid or expired: refresh it.
401 / 40342501RLS or permissions don't allow the operation.
40042703A column that doesn't exist (the hint suggests the right one).
40023502A required value is missing (a not null column with no default).
40923505, 23503Duplicate value in a unique column; foreign key that doesn't exist.
404PGRST205The table doesn't exist or isn't published in the API.
406PGRST116You asked for a single row and there are zero or several.
400invalid_credentialsWrong email or password.
422signup_disabled, weak_password, user_already_existsSee Sign-up.
413The body is over 10 MB.
429API rate limit exceededToo many requests: see Limits.

Limits

Migrations

To change the database schema from your code, opendb applies migrations over HTTPS, without opening the Postgres port. Create a token in the dashboard (Migraciones) and download the CLI, a single file with no dependencies (Node 18 or later):

curl -fsSLo opendb-migrate.mjs "$URL/migrations/v1/cli.mjs"

# In your .env: OPENDB_URL, OPENDB_TOKEN and OPENDB_DATABASE_URL
node opendb-migrate.mjs tunnel -- npx prisma migrate deploy   # with Prisma
node opendb-migrate.mjs deploy --dir migrations                # a folder of .sql files

The dashboard shows the commands with your project's details already filled in, and the scripts for your package.json.

Node.js SDK

Coming soon to npm. The @opendb/sdk package isn't published yet. Meanwhile, the single-file CLI in Migrations does the same with a connection string.

A package for Node.js 18 or later, with no dependencies, with a Postgres tunnel over HTTPS, migrations and temporary credentials: all it needs is the project URL and its migrations token, with no database passwords in your .env or your CI.

npm install --save-dev @opendb/sdk

Configuration

# .env at the root of your project
OPENDB_URL=https://api.yourdomain.com/p/myapp   # dashboard → Resumen
OPENDB_TOKEN=odb_...                            # dashboard → Migraciones → new token

They're read in this order: options first (--url, --token or those of openTunnel()), then the .env in the current folder, then environment variables. The project's .env wins over a variable left exported in your terminal; in a CI with no .env, the environment variables are used.

DATABASE_URL is never read, because it usually points at your local development database. If you set OPENDB_DATABASE_URL, the tunnel uses that connection instead of temporary credentials.

Command line

npx opendb tunnel -- npx prisma migrate deploy   # Prisma as is, through the tunnel
npx opendb tunnel -- npx prisma migrate status
npx opendb tunnel --port 54320                   # open until Ctrl+C (psql, DBeaver…)
npx opendb status --dir db/migrations            # without Prisma: applied and pending
npx opendb deploy --dir db/migrations            # without Prisma: applies the pending ones
npx opendb baseline --dir db/migrations          # the database already has them: mark them, don't run them
npx opendb credentials --minutes 30              # credentials for a direct connection

With a command after --, the tunnel runs it with DATABASE_URL and DIRECT_URL pointing at 127.0.0.1 and closes when the command ends, with its exit code. Tested with Prisma 6 and 7.

From code

import { openTunnel, status, deploy } from '@opendb/sdk'

const tunnel = await openTunnel({ minutes: 30 })   // reads OPENDB_URL and OPENDB_TOKEN
console.log(tunnel.databaseUrl)                    // postgresql://myapp_tmp_…@127.0.0.1:53817/p_myapp
// …use it with Prisma, pg, Drizzle, Knex…
await tunnel.close()

const plan = await status({ dir: 'db/migrations' }) // { applied, pending, modified, failed, missing }
await deploy({ dir: 'db/migrations', onApply: (r) => console.log(r.name, r.status) })

Temporary credentials

When it opens the tunnel, the SDK asks the project, with the token, for a database user that acts as the project owner and that Postgres stops accepting after a few minutes (15 by default, up to 60):

They only exist on projects hosted on opendb. On a project that connects an external database, use OPENDB_DATABASE_URL.

JavaScript example

A minimal client with fetch and no dependencies: login, a saved session, automatic token refresh, and reading and writing data.

const PROJECT_URL = 'https://api.yourdomain.com/p/myapp'
const ANON = 'eyJhbGciOiJIUzI1NiIs...'

let session = JSON.parse(localStorage.getItem('session') ?? 'null')

async function request(path, { method = 'GET', body, headers = {} } = {}) {
  // Refreshes the token if it expires in less than a minute
  if (session && session.expires_at * 1000 - Date.now() < 60_000) await refresh()
  const res = await fetch(PROJECT_URL + path, {
    method,
    headers: {
      apikey: ANON,
      ...(session && { Authorization: `Bearer ${session.access_token}` }),
      ...(body && { 'Content-Type': 'application/json' }),
      ...headers,
    },
    body: body && JSON.stringify(body),
  })
  const data = res.status === 204 ? null : await res.json().catch(() => null)
  if (!res.ok) throw new Error(data?.message ?? data?.msg ?? `HTTP ${res.status}`)
  return data
}

function save(data) {
  session = data
  localStorage.setItem('session', JSON.stringify(data))
}

async function login(email, password) {
  save(await request('/auth/v1/token?grant_type=password', { method: 'POST', body: { email, password } }))
}

async function refresh() {
  const res = await fetch(`${PROJECT_URL}/auth/v1/token?grant_type=refresh_token`, {
    method: 'POST',
    headers: { apikey: ANON, 'Content-Type': 'application/json' },
    body: JSON.stringify({ refresh_token: session.refresh_token }),
  })
  if (res.ok) save(await res.json())
  else { session = null; localStorage.removeItem('session') }   // the user has to log in again
}

async function logout() {
  await request('/auth/v1/logout', { method: 'POST' }).catch(() => {})
  session = null
  localStorage.removeItem('session')
}

// Usage
await login('[email protected]', 'Sup3r-secret!')
const pending = await request('/rest/v1/todos?select=id,title&done=eq.false&order=created_at.desc')
const [created] = await request('/rest/v1/todos', {
  method: 'POST',
  body: { title: 'Buy bread' },
  headers: { Prefer: 'return=representation' },
})
await request(`/rest/v1/todos?id=eq.${created.id}`, { method: 'PATCH', body: { done: true } })

Keeping the session in localStorage is the simplest option. If your app has a backend, you can keep it in an HttpOnly cookie and make the requests from the server.