REST API
@protobase/server turns resource definitions into a Hono app that follows Google’s API design conventions (AIP-131 to 136, 158, 160). It uses Web APIs only and runs on Node, Bun and Workers; protobase dev and serve serve it on Node or Bun.
protobase dev and serve build it from the project: the resources of config/, the functions of functions/, sign-in from auth, and the API’s settings from the top-level keys of protobase.config.ts, such as statementTimeoutMs and scanGuard. In code of its own, an app builds it with createAdmin, whose options take the same settings:
import { configExports, createAdmin, jwtAuthenticator } from '@protobase/server'import * as config from './config'
const { resources, views } = configExports(config) // splits a config's index.ts exportsconst admin = createAdmin({ resources, views, // optional, served by /meta db, // Kysely<any> on Postgres authenticate: jwtAuthenticator({ jwksUrl, issuer }), // required: no development mode; anonymous only with that role functions, // optional: your own endpoints at /api/functions/<name>, see /guides/api-functions/ options: { statementTimeoutMs: 1_000, scanGuard: { mode: 'reject' } },})Run the ERP example with bun run --cwd tests/apps/erp serve (port 8787, Better Auth login, the user’s active organization as tenant; REQUEST_LOG=true logs requests). Interactive reference: /api/docs; like /api/openapi.json it needs a bearer token, because the document lists what the caller may see and do. Every route answers 401 without a valid token; get one with protobase token [email protected]. A project whose roles define anonymous serves the resources API to requests without a token as that role.
Routes
Section titled “Routes”/api/v1/* is resources only, so a table may be called meta or docs. The system endpoints (/api/meta, /api/openapi.json, /api/docs), the app’s own API functions (/api/functions/<name>), file downloads (/api/files/<provider>/<path>), public forms (/api/forms/<name>) and login (/api/auth/*) live beside it; the parent of apiPath (default /api/v1) is where the system endpoints go.
Under /api/v1:
| Route | |
|---|---|
GET /{resource} |
list: filter, order_by, page_size (50, max 500), page_token, fields, labels, photos, photos_order_by, count=exact, limit_per, etag=false |
POST /{resource}:search |
same parameters as a JSON body (fields and labels arrays), for long filters |
GET /{parent}/{key}/{resource} |
the list of resource that belongs to one record, see Lists under a record |
GET /{resource}/{key} |
one record, with ETag; composite keys are part,part, each part percent-encoded |
POST /{resource} |
create, 201 with Location and ETag |
PATCH /{resource}/{key} |
partial update, If-Match required |
DELETE /{resource}/{key} |
soft delete when the resource has one (AIP-135); If-Match optional |
POST /{resource}:upload?field=&name= |
one file for a file field, as the raw body or one multipart file part; 201 { value, file, derived, corrected? }, where value is the ticket a write sends as the field’s value; 413 over the field’s maxSize, 415 for a type it does not take |
POST /{resource}/{key}:reveal |
{ "field": "iban" } gives { field, value } of one sensitive field, with Cache-Control: no-store, and publishes an audit event |
GET /{resource}/{key}:history |
the record’s changes, newest first, for a resource with history: page_size (20, max 100), page_token; see Record history |
GET, POST /{resource}/{key}:comments, GET /{resource}/{key}:mentionable?q= |
the record’s comments, newest first, adding one, and whom it may mention, for a resource with comments; see Record comments |
POST /{resource}/{key}:generate |
{ "action": "<name>" } runs an AI action of the caller’s view: the model writes its field, with the ETag the record was read with, and it answers the record as an update does |
POST /{resource}/{key}:undelete |
restores a soft-deleted record (AIP-164); If-Match optional; 409 when not deleted, 400 on hard-delete resources |
POST /api/v1:batchWrite |
many writes in one transaction, see Batch writes |
GET /{resource}:facets?field=&filter=&limit=&label= |
{ field, facets: [{ value, count }] }, the limit most frequent values (100 by default, at most 1,000), never all of them; with label, a relation’s facets carry the related record’s name as label, as in Related names |
GET /{resource}:aggregate?group_by=&sum=&average=&maximum=&filter= |
{ group_by, groups: [{ value, count, sum }] }: the records the whole filter finds, per value of group_by, each with its count and, with sum, average or maximum (one of them), that of a numeric field, null when no record of the group has one. Values come largest first, the first limit (100 by default, at most 1,000), with label as in :facets. A date or timestamp group_by is bucketed like :series instead (granularity minute, 5_minutes, 15_minutes or hour to year, range or from and to, time_zone), empty buckets included, and each value is the bucket’s start; the response adds granularity and time_zone. With split_by (a filterable field of values), a date group_by also splits each bucket: the response adds split_by and splits (the split_limit largest values over the range, 8 by default and at most 100, ranked by the sum, else by count; split_label names a relation’s values), and each group lists its splits with their count and sum, average or maximum. Unlike :facets, the filter’s terms on group_by apply too, so the groups add up to what the filter finds. A values group_by takes limit_per=<field>:<n>: the first n groups per value of field, each with that value as per, by per, with limit capping all groups together; a date group_by refuses it |
GET /{resource}:series?field=&range=&granularity=&time_zone=&filter= |
range is 1h, 24h, 7d, 30d, 90d, 1y, all, or from and to (ISO); granularity minute, 5_minutes, 15_minutes, hour, day (the default), week or month. Buckets of minutes start on the clock’s multiples of them |
GET /{resource}:histogram?field=&buckets=&filter= |
equal-width buckets of a numeric field |
POST /{resource}:batchAggregates |
{ facets: [...], histograms: [...], series: [...] }, each a list of reads with the parameters of :facets, :histogram and :series (at most 100 of each), answered with lists of what those methods answer, in the same order. Reads that filter the same rows, a facet’s own terms left out, share their scans of the table: one for the bounds of every histogram, and one per four facets, histograms of several buckets and series. Each keeps its method’s access, scan guard and labels, and a read that fails fails the request. A list page sends its filters’ counts and its chart this way |
GET /{resource}:map?latitude=&longitude=&zoom=&filter=&order_by=&fields=&labels=&photos=&photos_order_by= |
the records in a map’s view, the bounding box being in filter (lat >= 51.9 AND lat <= 52.1 AND lng >= 4.2 AND lng <= 4.5), as { items, buckets, total_size }; see Maps |
GET /{resource}:seek?position=&order_by=&filter=&page_size=&fields=&labels=&photos=&photos_order_by= |
the page at a row position (scrollbar jumps), with next_page_token and prev_page_token; same items as a list |
GET /api/meta |
resource, view and page models (fields carry default: { value } or { db: true }) and the caller’s permissions; the ETag hashes both, so it differs per user; If-None-Match gives 304 |
GET /api/live?after= |
a text/event-stream of which records of the live resources the caller may read change, keys only; see The stream |
POST /api/files:cleanup |
runs the scheduled file deletes that are due, for an admin; { deleted, kept } |
GET /api/openapi.json, GET /api/docs |
OpenAPI 3.1 for the caller (only the resources, fields and operations their roles allow), and the Scalar reference |
Every response carries X-Meta-Version, the hash of the models, the Protobase version and the caller’s roles; a client that sees it change (a model edit, an upgrade, a role change) refetches /meta.
show_deleted=true on list, :search (body) and get also returns soft-deleted records (soft-delete resources only, 400 otherwise).
A list returns { items, next_page_token, total_size_estimate }, the estimate being the planner’s, which reads no rows. count=exact adds total_size, counted through the indexes but no further than 10,000 matches: above that total_size is left out and the estimate stands. next_page_token is "" on the last page, and a token only continues the filter and order_by it came from: with others the request fails with 400 invalid-cursor. Items use field names, dates as ISO 8601 text, 64-bit integers and decimals as strings.
First rows per value
Section titled “First rows per value”limit_per=<field>:<n> keeps, for each value of field among the records the filter finds, the first n records in the list’s order_by, such as the latest three comments of each task on a page in one read:
GET /api/v1/comments?filter=related(task_id, tasks.id, (state = "open"), "created_at desc", 20)&order_by=created_at desc&limit_per=task_id:3fieldis a filterable field that is not JSON,na whole number from 1 to 500. The items come per value offield, in its order, and inorder_bywithin each value; records whosefieldis null are left out.page_sizecaps the items over all values together.- The records are read as any list reads them, under the caller’s tenant, access and filter, a
related()term included, so only the values that filter keeps appear.total_size_estimateandtotal_sizecount what the filter finds, not whatlimit_perkeeps. next_page_tokenis always"".limit_perwith apage_tokenor on:seekis a400invalid-parameterthat names the conflict.- The scan guard needs a btree index on
fieldwith the first field oforder_byunder it, such ascreate index on comments (task_id, created_at). - On
:aggregate,limit_pergroups byfieldas well asgroup_byand keeps, for each value offield, the firstngroups in the aggregate’s order; each group carries that value asper.
Record history
Section titled “Record history”GET /{resource}/{key}:history answers { items, next_page_token } for a resource with .history(), and 404 for one without. It needs what a get needs, a soft-deleted record included. Each item is { id, at, operation, changed, before?, after?, actor, database_role }: before and after hold only the fields the caller may read, never a sensitive or file field, changed names the changed fields the caller may read, and an update of only other fields is left out. actor is { id, name? } for a write through the API, the name when the project’s Better Auth knows the user, and null otherwise; database_role is the role that wrote. See Record history.
Record comments
Section titled “Record comments”For a resource with .comments(), and 404 for one without; each needs what a get needs. GET /{resource}/{key}:comments answers { items, next_page_token }, newest first, a soft-deleted record included, with page_size (20, max 100) and page_token. Each item is { id, created_at, body, author, mentions }, where author and each of mentions is { id, name? }, the name when the project’s Better Auth knows the user. POST with { "body": "...", "mentions": ["<user id>"] } adds the caller’s comment to a record that is not deleted and answers 201 with it: body is trimmed, mentions names at most 20 users, the caller dropped, and each is emailed. GET /{resource}/{key}:mentionable?q= answers { items: [{ id, name }] }: at most 8 users whose name contains q, by name, who may read the record, without the caller. Its problems: 403 comment-needs-user to a caller who is not signed in, on the POST and on :mentionable; 400 invalid-comment for an empty body or one over 10,000 characters; 400 invalid-mention for a mention of someone who may not read the record, which keeps nothing. See Record comments.
Related names
Section titled “Related names”A list holds a relation as the key of the record it points at. labels names those records in the same answer: labels=place_id.name,agency_id.name on a list, :search, :seek or :map adds labels: { "place_id": { "12": "Amsterdam" }, "agency_id": { ... } }, the name of each place and agency the page’s items point at, by key as text. Each entry is a relation among the returned fields, to a resource with a single-field key, and the field of that resource that names its records, neither a file nor JSON; anything else is a 400. The related records are read as the caller lists that resource, in one query per relation: its tenant, row filter, soft delete and readable fields apply. A record they cannot list, or whose field they cannot read, is not in labels, and neither is an empty name, so it goes by its key; a field they cannot read or that does not exist answers the same, so labels never tells it exists.
Card photos
Section titled “Card photos”A list can bring each record’s first photos in the same answer, as a cards display’s photos shows them: photos=listing_photos.listing_id.photo&photos_order_by=position on a list, :search, :seek or :map adds photos: { "12": [{ "uri": "public:…", "url": "…", "placeholder": "…" }, …] }, the photo files of the first ten records of listing_photos whose relation listing_id points at each item, by its key as text, in photos_order_by order (their primary key breaking ties). An item without photos is not in photos. The entry names a resource, its relation to the listed one and its file field; a malformed entry, or photos_order_by without it, is a 400.
The photos are read as the caller lists that resource, in one query for the whole page: its tenant, row filter, soft delete and readable fields apply, each file comes as that resource’s list returns it, with its placeholder when the caller may read that field, and the scan guard checks the lookup like a list. A caller who cannot list the resource, or read and use the relation, the file field or the sorted fields, gets photos: {}, as they would for a resource or field that does not exist, so photos never tells it exists; so does a list of a resource with a composite key.
:map answers a map of a resource’s records at their position, two filterable number fields in decimal degrees (latitude and longitude name them) and MapLibre’s zoom, a whole number from 0 to 22. The map’s bounding box is part of the AIP-160 filter, with the list’s own filter: (rooms >= 3) AND lat >= 51.9 AND lat <= 52.1 AND lng >= 4.2 AND lng <= 4.5, or (lng >= 170 OR lng <= -170) across the antimeridian. When up to 200 records match, or from zoom 16 on, items holds them (at most 200, in order_by order) as a list returns them, and buckets is empty. Otherwise buckets counts them per cell of a grid about 64 pixels across at the zoom, square on a Web Mercator map and fixed as it pans, the fullest 1,000 cells, each as { count, latitude, longitude, bounds: { south, west, north, east } }: the records’ mean position and the bounds around them, which a map zooms to when the bucket is chosen. items is then empty, and records without a position are in no bucket. total_size counts the matches either way, up to 10,000 when items holds them, as count=exact does, the planner’s estimate above that. Postgres counts and groups the records, so an index on the position serves the bounding box.
Access
Section titled “Access”Access is resolved once per request and resource (resolveAccess, see Login with Better Auth for roles and capabilities), and everything downstream uses the result:
- Operations: a denied operation is
403; a resource the caller can do nothing with does not exist for them (404everywhere, absent from/metaand the OpenAPI document). - Readable fields: the caller works with a restricted model that has only the fields they may read.
filter,order_by,fields,search(...),:facets,:aggregate,:histogram,:series,:batchAggregates,:map,:seekand:searchbodies are checked against it, so a hidden field is refused exactly like an unknown one (same status, same message and hint, nothing that says it exists). List, get, create, update and delete responses contain readable fields only, and queries select only those columns. - Sensitive fields are readable fields that no response carries and no request may name, except
:reveal; they can be written. See Sensitive fields and audit. - Writable fields: only fields the caller may write and read are accepted, and write-only ones; any other is
400, worded as unknown (hidden) or read-only. - Row filters: a rule that returns a filter (
.own,.team) narrows every read (list, get, aggregates) and the rows a write may target; the database applies it, so it may use columns the caller cannot see. A row outside it is a404. - Parents: a resource declared with
.parent(fk, 'read')narrows every read to the rows whose parent the caller reads under the parent’s own access, a row outside being a404(see Records that belong to another). - Record-level rules (a rule that needs the record, such as
status != 'locked') run in the write transaction with the stored record; a filter they return is checked in the database against the row as written, and a miss rolls the write back with403. .ownon create: when the create rule is limited to rows, the owner field is set to the caller unless given, and a row owned by someone else is refused with403.- Seeking:
:seekresolves a row position to a page on the server, inside the caller’s tenant, row filter and filter. No anchor value, column statistic or boundary token is ever returned (table-wide statistics include rows the caller may not see), only the page and the tokens of its own rows. - ETags: with a read-only
versionorupdated_atcolumn the ETag is a hash of that column’s exact text, so it never shows a hidden value yet moves on every change;.etagFrom((r) => r.updated_at)on a resource names the column, for aversionthat counts something else. Without one it is a hash of the fields the caller may read, sensitive ones excluded: a change to a field they cannot read, or to a sensitive field, does not change their ETag. - Errors never contain values of fields the caller cannot read; database errors leave out constraint and column names.
The roles (the roles export of config/roles.ts, from defineRoles) make an operation without an explicit rule need the matching capability (orders.update), and limits each role to the fields and rows its capabilities list; defaultAccess: 'allow' | 'deny' in the config overrides the capability check. Without either, operations without a rule are allowed (single-admin projects).
Record permissions
Section titled “Record permissions”Get responses carry permissions: { update, delete, fields }, where fields maps each readable field to edit or read for this record (hidden fields are not listed). List items carry permissions: { update, delete } too, decided in the database in one extra query per page; turn it off for a resource with rowPermissions: { except: ['resource'] } in the config (or false for all). They only inform the UI: every write is checked again. A resource cannot have a field named permissions or etag.
/meta and OpenAPI per caller
Section titled “/meta and OpenAPI per caller”/meta returns, per caller: the resources they can do anything with as restricted models (hidden fields absent, readOnly unless writable, write-only fields marked writeOnly), the view for their roles (pickView) with every reference to a hidden field removed (columns, sort, search, filters, layout, chart, title, search result) and the related sections they cannot use, permissions[resource] as { read, create, update, delete, conditional }, the user menu as userMenu and the bottom bar of their active role as bottomBar, each without the resources and pages they cannot see, and the composed pages as pages, each without the elements that name what they cannot see or do, and, for a caller with the admin or ai role, the assistant backend as assistant: { url } when the app has one, and, for a caller with the admin role, the runtime updates endpoint as runtime: { url } when the app has one, and, for everyone, the style of the record page’s maps as maps: { style } when the app has one, the language of its screens as locale when it sets one, and the Protobase version the server runs as protobaseVersion. When that version changes under an open page, the admin app keeps what the page shows, stops reading /meta, and offers to reload the page, asking first while a form holds unsaved changes or a save is under way. conditional lists the operations allowed only for some records (a row filter or a record-level rule decides). A view’s sidebar group (nav.recent) is dropped when it uses a field they cannot read. The ETag hashes all of it, so it differs per user and per roles. The OpenAPI document is generated the same way: record and body schemas have only the readable and writable fields, and methods the caller may not use are left out. Its servers are relative to the document (v1 for the resources, . for the system endpoints), and /api/docs loads openapi.json beside it, so both are right on any host and under any prefix the API is reached at.
Sensitive fields and audit
Section titled “Sensitive fields and audit”A field declared .sensitive() is in /meta (marked sensitive: true), in record permissions.fields and in create and update bodies, but in no list, get, :search, :seek, write or batch response, and filter, order_by, fields and the aggregates refuse it like an unknown field. POST /{resource}/{key}:reveal with { "field": "<name>" } returns one record’s value. It needs read access to the record and the field: another tenant’s record, a row outside the caller’s row filter or a key that does not exist is a 404, a field the caller cannot read or that is not sensitive a 400. An encrypted field’s reveal decrypts its value, and an empty one reveals null; a value that does not decrypt is a 500 reported to the operator, without an audit event. An update that changes the key of a record with encrypted fields is a 400 key-change-unsupported.
A field with .strongSignIn() is a 403 strong-sign-in-required, whose problem carries minutes, until the caller’s sign-in proved a passkey or a second step that recently, or, for an account with neither, an emailed confirmation code. The same request reveals a resource’s computed reveals by name, whose value the server makes when asked.
Before answering, the server publishes an audit event to the app’s audit queue, and when publishing fails the reveal fails (500), so no value leaves without its event. The event never holds the value:
type AuditEvent = { type: 'field.revealed' at: string // ISO 8601 actor?: { id: string | number; roles: string[] } // absent when a job read the value reader?: { job: string } | { function: string } // who read it with decryptField; absent for a reveal tenant?: string | number // the caller's organization (the record's for decryptField), for tenant-scoped resources resource: string recordKey: string // as in the record's URL field: string origin: { userAgent?: string; forwardedFor?: string } // from the request headers}A job or API function that reads an encrypted field with decryptField publishes the same event, with reader set and, for a job, no actor or origin headers.
With organizations, someone with a global role switching into an organization they are not a member of publishes { type: 'organization.entered', at, actor, organization, origin } first, where actor.roles are their global roles; a failed publish refuses the switch. AuditEvent is the union of the two.
Audit events
Section titled “Audit events”The queue is an AuditQueue, { publish(event): Promise<void> }, the default export of the project’s audit/queue.ts. The default, consoleAuditQueue(), prints each event to the console as one [audit] {...} JSON line and keeps nothing; a queue that stores or forwards events replaces it there.
Filters
Section titled “Filters”filter and order_by are AIP-160 and AIP-132 text, checked against the model (filterable and sortable fields only). Functions: in(field, v, ...), search("text") and bare words (every word, ignoring case, anywhere inside one of the resource’s search fields, so port finds “Portfolio”; %, _ and \ are literal; a digitsEnd field matches only the end of its digits), similar(field, "text"), regex(field, "pattern"), isNull(field), now() with offsets such as now() - 7d, and related(field, resource.key, (filter), "order_by", limit, "page_token"). A filter is capped at 10,000 characters in a query string and 200,000 in a :search body. A proxy in front of the API can refuse a long URL sooner with a 431, counting the headers too: Protobase Cloud refused about 8,000 characters. So send a long filter to :search, as client.list does when its query string passes 4,000 characters.
Filtering through related records
Section titled “Filtering through related records”related(field, resource.key, (subfilter)) keeps the records whose field holds the key of a record of resource that meets the subfilter, in one read, so a client never reads the keys first and sends them back:
task_claims related(task_id, objective_tasks.task_id, (objective_id = 40)) AND claimed_at >= now() - 7dtasks related(id, objective_tasks.task_id, (objective_id = 40)) AND state != "done"preconditions related(task_id, tasks.id, (state != "done" AND related(id, objective_tasks.task_id, (objective_id = 40))))It works in the filter of a list, :search, :seek, :facets, :aggregate, :series, :histogram and :map, in /api/v1 and in MCP’s list_records and count_records, and where.related('task_id', 'objective_tasks', 'task_id', where.eq('objective_id', 40)) builds it in code.
fieldis a filterable field of the resource read, andkeyone ofresource. Both point at one resource: each is a relation to it, or its own single key, orkeyis a JSON list of its keys. A nullfielddoes not match.- It is a term ANDed at the top of the filter or of a subfilter.
NOTandORrefuse it, as does anything else that takes a filter: access rules, role filters, a view’s opening filter, events, subscriptions, workflow conditions and page conditions. - A filter holds at most 3 terms, those in subfilters included, and nests at most 2 levels.
- It may do only what the caller could do in two steps, listing
resourcewith the subfilter and then filtering within(field, ...): the access rules apply to both sides, and a resource the caller cannot list answers as one that does not exist. - The scan guard judges both tables. Besides
fieldand the subfilter’s columns,keyneeds a btree index under what the subfilter pins, and the first field oforder_byneeds one as in a list ofresource. A JSON list of keys needs no index of its own: it is only read from the records the indexed subfilter and order already chose, and is never filtered or sorted on. - A list across organizations with a term reads the session’s own organization alone, and so does the term.
After the subfilter it can take the order_by, limit and page_token of a list of resource, each needing the one before it, so a child read keeps to the children of exactly the records one page of that list shows:
task_claims related(task_id, tasks.id, (state != "done"), "created_at desc", 20)task_claims related(task_id, tasks.id, (state != "done"), "created_at desc", 20, "<next_page_token>")tasks related(id, tasks.waits, (state != "done"), "created_at desc", 20)order_byis the list’s AIP-132 text,""for its default order;limitis itspage_size, a whole number from 1, capped at 500 as a page is;page_tokenis anext_page_tokenof the list ofresourcewith the same subfilter and order, and with any other it is a400invalid-cursor. The subfilter is optional here too:related(task_id, tasks.id, "created_at desc", 20).where.related(..., filter, { orderBy: 'created_at desc', limit: 20, pageToken })builds it in code.- A JSON
key, such as a task’swaits, lists keys of the resourcefieldpoints at: a record matches when itsfieldis in the list of any record the term reads. A null, empty or non-list value adds no keys, and neither does an item that is no valid key, such as"x"among integer keys. It needs Postgres 16 or later, which tells a valid key from one that is not (pg_input_is_valid).
Lists under a record
Section titled “Lists under a record”GET /{parent}/{key}/{resource} is the list of resource that belongs to one record, with the same parameters as its own list: /objectives/40/tasks?filter=state != "done". The other list methods work too: /objectives/40/tasks:facets, POST /objectives/40/tasks:search and the rest. It is a filter the path spells out, and a record keeps its one address, /tasks/7.
- A relation of
resourcetoparentleads there without a declaration:/tasks/7/task_claimskeeps totask_id = 7, also in a:facetsontask_id. - A link resource that declares its two relations with
.links()joins them:/objectives/40/tasksreads asrelated(id, objective_tasks.task_id, (objective_id = 40)), the other side/tasks/7/objectives, and a resource a further step away,/objectives/40/task_claims, asrelated(task_id, objective_tasks.task_id, (objective_id = 40)). - The caller’s own
filterstands beside it, with its own limits; a:facetson the relation stays inside the record. - Where nothing leads there the answer is a
404. Where several ways do, such astask_dependencieswith its two relations totasks, it is a400ambiguous-parentthat names them, and arelated()filter says which. Links count only when the caller can list them. - The parent is read as the caller would read it first: one in another tenant, soft-deleted, outside their row filter or refused by a rule that reads the record answers the same
404as one that does not exist. A resource they do nothing with answers as one that does not exist. A list of a resource they may not list answers as that list does. - A composite key has no list under it.
MCP’s list_records and count_records take the same as belongs_to: { "resource": "objectives", "key": 40 }, beside filter.
Writes
Section titled “Writes”Create, update and delete share one pipeline (write-pipeline.ts):
- the caller is authenticated and, for tenant-scoped resources, has a tenant (
403otherwise); - unknown fields, read-only fields and the tenant column in the body are refused, each value is validated by its field’s zod schema (an empty string for a text field without
.optional()counts as missing:required, or its default on a create), then the resource’s.validate()rules run (400witherrors: [{ field, code, message }]); what needs the network is checked before the transaction opens, such as the address of a webhook subscription’s URL; - one transaction with
SET LOCAL statement_timeout; the row is locked withFOR UPDATE; another tenant’s key, or a soft-deleted row, is a404; - on PATCH and DELETE,
If-Matchis compared with the ETag as soon as the row is locked (428when missing on PATCH,412when stale), so a PATCH answers it before the body’s checks of step 2; then the resource’s.prepare()hooks fill in or rewrite a create’s or update’s values (422with the field named when one refuses), then the access rule runs; - the write, then
writeHooksinside the same transaction (a hook that throws rolls the write back). Audit logging and the admin store plug in here. A hook does database work only, through the transaction it is given: while it waits on anything else, such as an HTTP call, the transaction stays open with the row locked, and on Protobase Cloud the database ends a transaction left idle for a second. Work that waits belongs in a job the hook enqueues; - once it commits, the files it took out of its rows are scheduled for deletion (see Deleting files), so the transaction never waits on the storage.
ETag: the version or updated_at column when the resource has a read-only one (bumped on every update, so no trigger is needed; the ETag keeps the column’s full microsecond text), otherwise a hash of the exposed fields. It is computed from the row itself, so lists need no extra query.
etag property: every record in a get, list, :search, create or update response carries its current version as etag (the value of the ETag header, AIP-154), so a grid row can be updated or deleted without a get. It survives fields selection. etag=false on a list, :search or :seek (true, the default, keeps it; any other value is a 400) leaves it out of every item, so a list that only shows records reads only its fields from the database, where a resource without a version column otherwise reads every field it may read to hash its ETags. A resource cannot have a field named etag (startup error); a body containing etag is a 400 that points at If-Match.
If-Match is required on PATCH (428 without it). On DELETE it is optional: without it the current version is deleted. When sent it must match, otherwise 412; * matches whatever the current version is (RFC 9110).
Prefer: create and update return the record by default; Prefer: return=minimal returns no body (201/204). Delete returns 204, or the record with Prefer: return=representation.
The rules behind these steps are described under Access.
Batch writes
Section titled “Batch writes”POST /api/v1:batchWrite takes { ops: [...] } ({ operations: [...] } is accepted too), at most 500, run in order inside ONE transaction, so check constraints and triggers see one consistent state. Each operation goes through the same write pipeline as a single write (validation, access with row filters and record-level rules, tenant, ETags, hooks), access is checked per operation, and the operations may span resources.
op |
fields |
|---|---|
create |
resource, data, ref? |
update |
resource, key, etag (required, * allowed), data |
delete |
resource, key, etag? |
reorder |
resource, field, keys (in final order), start (optional, 1 by default), etags (per key text) |
move |
resource, field, key, after (a key or null), before? (a key or null), filter? |
- Keys are the URL text (
a,bwhen composite), a number, a list of parts, or a reference. $ref:ref: 'invoice'on a create names the record; later operations use{ "$ref": "invoice" }as a key, a key part, or a value indata(it stands for that record’s key, or with{ "$ref": "invoice", "field": "number" }a readable field’s value). A ref must come after its create.reordersetsfieldtostart,start+ 1, … in the order ofkeys, so a long list sends only the stretch that moved, and writes only the records whose value changes, each as an ordinary update (so each needs itsetagsentry, and hooks see each). To work with a non-deferrable unique index such as(invoice_id, position), the changing records are first moved out of the range in use, in the same transaction and without touching their ETags: above the highest value of the column, or, when a check constraint refuses that (checked with a savepoint), below the lowest one. Then they get their final values, which collide with nothing. The field must be an integer the caller may write; the keys must all exist and be visible to the caller. When it is the resource’s position withafter, a reorder that puts a record at or above a record it depends on, or one of those at or below it, fails with409and the typeranks-above-dependency, naming both keys inrecordanddependsOn; pairs out of order before it do not count.moveputs the recordkeyjust afterafter, or first when it isnull, in the listfilterreads (as a list’sfilterdoes) ordered byfield. It is anchored to that place rather than to ETags: it saves while the record afterafterthere, leaving out the moved one, is stillbefore(null: none), whatever else changed in the list or in the records, and fails with412otherwise, so the caller reads the list again. Leavebeforeout when the caller did not load the record afterafter; then onlyafteris checked. The server reads the list in its current order and renumbers the shortest stretch that saves the move, written as areorderwrites it, so the same field rules, unique index handling andranks-above-dependencycheck apply. Moves and reorders of the same resource’sfieldrun one at a time, together with the creates and updates through this API that set the resource’s.position()field (data config), and a record of the stretch renumbered by another write between the move’s read and its write refuses it with412too.A write of the position through the PostgREST-compatible API cannot make a move wait because that API taking the order lock is not implemented. A filter needs indexes as a list’s does.- Result:
{ results: [...] }, one entry per operation in order:createandupdategiverecordandetag,deletegivesdeleted: true,reordergivesrecords(every key in order, with its etag), andmovethe records it numbered, in order, with their etags. Each of those records comes withprevious, its value offieldbefore the operation, which an undo puts back. - Failure: nothing is written. The problem is the failing operation’s own (
400,403,404,409,412,428, …) withoperation(its index),opandresourceadded. A stale ETag anywhere is a412for the whole batch.
Authentication
Section titled “Authentication”Real login is the app’s sign-in. Lower level:
authenticate(request) returns { user: { id, roles }, tenant? } or throws unauthorized(...) (a 401 problem), or new MissingCredentials(...) (also a 401) when the request carries no credential at all. Shipped: jwtAuthenticator({ jwksUrl | keys, issuer?, audience?, rolesClaim?, tenantClaim?, tenant? }), which verifies a bearer token with jose (sub is the user id; tenant fixes the tenant instead of reading a claim) and refuses a token bound to a key (cnf), which only a proof of that key may use, and the authenticator of the app’s sign-in on top of it, which authenticate in the config sets (Tokens and roles) and which also takes OAuth access tokens for the API; an authenticator of the project’s own is the default export of auth/authenticate.ts. No code path treats a request as a user without verifying a credential; the one exception is the anonymous role, which the resources API gives a request that has none, when the project defines it.
The API sends no CORS headers until it has something to allow: other websites in cors in the config (a list of origins, or '*' for any), which defaults to PROTOBASE_CORS_ORIGINS (* or comma separated http and https origins), other origins of the app, which are always allowed, or a mobile section, which allows the app’s Capacitor origins, capacitor://localhost and https://localhost. PROTOBASE_CORS_ORIGINS refuses other schemes at startup.
- It covers
/api/*but Better Auth’s/api/auth/*, which checks origins itself (the mobile app signs in through native HTTP, outside CORS), and API functions with acorsof their own; supabase-js’s/api/sbis under it too. - An allowed origin gets
Access-Control-Allow-Originwith its name andVary: Origin, or*with'*'. No credentials: browser code calls the API with a bearer token. - Preflights are answered before authentication, for
authorization,content-type,if-match,if-none-matchand supabase-js’sapikey,x-client-infoandx-supabase-api-version, and kept for 10 minutes.Location,ETag,X-Meta-VersionandX-Protobase-Warningare exposed. - An API whose resources another app draws as remote resources lists that app’s origin here.
Safety
Section titled “Safety”-
Every request runs in a transaction with
SET LOCAL statement_timeout(statementTimeoutMs, default 1 s), so a slow query fails where it runs instead of holding a connection that other requests wait for. List, search, get, histogram, series, map and seek transactions are read-only. A query that runs longer is stopped: a504statement-timeoutthat names the request, its limit and the ways out, such asGET /api/v1/orders ran a query longer than 1 s, so the database stopped it. It may also have waited on a lock another transaction held, such as a migration while a deploy runs. Make the query faster, such as with an index or a narrower filter, or move the work into a function or job with longQueries: true, whose queries may run up to 30 s.It goes to the app’s error hook (hooks/error.ts,createAdmin’soptions.onUnhandledError) and the error tracker like a500. A read that needs longer has no way to opt out: give it an index, or move it into a function or job withlongQueries. -
Under
protobase devandserve, a request waits at most 2 seconds for a free database connection. When every connection stays busy that long, it is a503connections-busywithRetry-After: 1that names the request, reported the same way, rather than a request that hangs behind slow ones. A request that finds room for a new connection waits up to 30 seconds for it to open, such as while a database that scaled to zero wakes. -
Scan guard: a list,
:search,:seek,:mappage, card photos,:facets(in:batchAggregatestoo) and:aggregateread only columns an index serves, so they stay cheap however many rows match. The server reads each table’s valid indexes from the catalog once, then checks every column the caller’s filter, the role’s row filter, the sort’s first field, a facet’s or an aggregate’s grouped field, the field oflimit_per, areadparent’s relation read and arelated()term’sfield, the columns of the parent’s own row filter against the parent’s table, and the subfilter’s columns andkeyof a term against its resource’s table:- Comparisons,
in, null checks, sorts and facets need a btree index with the column as a key, every key before it pinned by the query: by=orinin the filter (outsideORandNOT), by the tenant or by soft delete.(for_sale, status, published_at desc)servesfor_sale = true AND status = "available"sorted bypublished_at desc, but notstatusalone.=on text may use a pg_trgm index instead. limit_perreads each value’s records in the sort’s order, so it needs one btree index with its field as a key and the sort’s first field under it,(task_id, created_at)forlimit_per=task_id:3&order_by=created_at desc; without anorder_by, an index on its field alone.- Patterns (
name = "*port*"),regex(),similar()andsearch()need a pg_trgm (GIN or GiST) index on each column they read, adigitsEndsearch field one on its digits; JSONfield:valueneeds a GIN index. - A partial index counts for nothing, and a resource on a plain view or a foreign table, which has no indexes of its own, is not checked.
A column without one is a
400expensive-queryproblem that names it, withcolumns(each{ field, column, use, need, suggestion }) and acreate indexsuggestion;scanGuard: { mode: 'warn' }answers with anX-Protobase-Warningheader instead,'off'disables it. The indexes are read when a table is first queried and kept for the process lifetime, so restart the server after adding one.protobase doctorjudges every read the config makes by the same rule against the database’s indexes, so a missing index fails it before a deploy instead of a page after. - Comparisons,
Errors
Section titled “Errors”Every error is application/problem+json (RFC 9457) with type (urn:protobase:problem:<slug>), title, status, detail, instance. Filter and order_by errors add parameter and errors: [{ code, message, hint, span: { start, end } }]; invalid parameters add errors: [{ parameter, message }]. A create or update whose body fails the checks is invalid-record with errors: [{ field, code, message, params }], code one of required, invalid-value, read-only, unknown-field and invalid-record (a .validate() rule); params is the limit an invalid value broke, such as { min }, { max } or a decimal’s { precision, scale }. Database constraint failures map to 409 or 400 without the raw message. A check violation naming a check the resource declares with .checks() is a 400 invalid-record with errors: [{ field: '_record', code, message }], code the check’s name and message its label from the config, never the database’s text; any other check violation is the generic 400, and the server logs a warning with the constraint’s name. A create or update that writes the position of a resource with after so a record ranks at or above one it depends on is a 409 ranks-above-dependency, as in a reorder. A create that repeats the values of a resource’s .openExisting() unique key is a 409 conflict with existing: { key }, the key of the record holding them as its address writes it, only when the caller may read that record; otherwise it is the plain 409, as any unique conflict is. A delete that other records still point at is a 409 conflict with blockedBy: { resource, field? }: their resource, when the caller may list it, and its relation field pointing at the record, when they may filter by it, so a client can open those records; the admin app’s toast names them, such as “Orders still point at this company.”, with a link to that list. Postgres names one table of them only, so blockedBy holds one resource. A write that Postgres rolls back because it locked the same records as another write in the opposite order (a deadlock) is a 409 conflict too: nothing was written, so send it again. Anything unexpected is a 500 with a fixed detail, reported to the app’s error hook (hooks/error.ts, createAdmin’s options.onUnhandledError) and, when it is set, the error tracker.
| Status | Slugs |
|---|---|
| 400 | invalid-filter, invalid-order-by, invalid-parameter, invalid-key, invalid-record, malformed-json, expensive-query, query-layer codes |
| 401 | unauthenticated |
| 403 | access-denied, tenant-required |
| 404 | not-found |
| 409 | conflict: a unique key, a record other records point at, or a deadlock with another write, which may be sent again |
| 412 / 428 | precondition-failed / precondition-required |
| 503 | read-only: the database refuses writes, as during a deploy’s write freeze; send the write again after Retry-After. database-restarting: the database or its connection pooler is shutting down, starting up or recovering from a crash; send the request again after Retry-After. connections-busy: every database connection stayed busy for 2 seconds (see Safety) |
| 504 | statement-timeout: a query ran past its limit (see Safety) |
Error reporting
Section titled “Error reporting”An app can send its errors to an error tracker of its own: Sentry or one that speaks its protocol, such as Bugsink or GlitchTip. It is off until a DSN, the address the tracker gives a project, is set in errorReporting or PROTOBASE_SENTRY_DSN; without one nothing is loaded or sent.
export default defineConfig({ errorReporting: { dsn: 'https://<key>@errors.example.com/42', environment: 'staging' },})- Server: every
500with the request it failed, and every504 statement-timeoutand503 connections-busywith the request it names, underdev,serveand the runtime, besides the default export ofhooks/error.tsor the console. Underserve, the runtime andworker, an uncaught exception or unhandled rejection too, which then still ends the process with exit code 1.The assistant and MCP tool calls cannot leave a database restart’s 503unreported because their reporting check knows only the write freeze’sread-only. - Admin app: uncaught errors and the errors of components that fail to draw.
/api/metanames the DSN to every signed-in caller, as a browser app always shows its own. Only the app’s own errors are sent:build,build-shellandbuild-pluginmark every script they write as the app’s, and an error none of whose stack frames is in a marked script, such as one raised by a browser extension or a script the browser injects, is dropped. Underdev, whose scripts are not built, every error is sent. - Errors only, with no performance tracing. Before an event leaves, the values of authorization headers, cookies, passwords, tokens and other credentials, in fields and in URLs, are replaced by
[Filtered]. environmentnames the deployment in the tracker; without it the tracker’s default,production.errorReporting: falseturns reporting off whatever the environment says. A DSN that is nohttp(s)URL with a key and a project id stops startup.