pdbr introspects pg_catalog and serves a PostgREST-style REST API. Every
request — however many embeds, filters or nested writes it carries — compiles
to one parameterized SQL statement whose single json column is the
response body; Go only maps status codes and headers.
This document is the URL and header reference. Filters live in filtering.md; paging, ordering and cursors in pagination.md.
Everything except the health endpoints is mounted under server.base_path
(default "": the root, as in PostgREST; /api prefixes every route with
/api). {base} below is that prefix.
| Method / route | Meaning | Status |
|---|---|---|
GET {base}/{table} |
list rows → JSON array | 200 |
HEAD {base}/{table} |
list headers only (incl. X-Total-Count with count=true), no body |
200 |
GET {base}/{table}/{pk} |
one row by primary key → object; composite PK values comma-separated in PK column order, each percent-encoded (, in a value → %2C) |
200 / 404 |
GET {base}/{table}/by/{cols}/{vals} |
one row by unique constraint; cols = comma list equal (order-insensitive) to a unique constraint's column set, vals positional to cols |
200 / 404 |
POST {base}/{table} |
insert object → row; insert array → bulk (single INSERT … VALUES (…),(…), columns = union, missing → DEFAULT); {} → DEFAULT VALUES |
201 |
PUT {base}/{table} |
upsert on the PK, or on ?on_conflict=col1,col2 (a unique constraint); conflict columns must be in the body |
201 inserted (xmax = 0) / 200 updated; arrays always 200 |
PUT {base}/{table}/{pk}, …/by/{cols}/{vals} |
upsert of the row the path names (key from the path; body key columns optional, must match); only where every key column is writable | 201 inserted / 200 updated |
PATCH {base}/{table}/{pk}, …/by/{cols}/{vals} |
partial update → row | 200 / 404 / 412 |
DELETE {base}/{table}/{pk}, …/by/{cols}/{vals} |
delete → deleted row | 200 (204 with Prefer: return=minimal) / 404 / 412 |
PATCH, DELETE {base}/{table}?<filters> |
bulk write of every row the filters select → array of written rows; no filter → 400 unfiltered_mutation unless mutations.allow_unfiltered (mutations.md) |
200 (204 with Prefer: return=minimal) |
GET {base}/{schema}/{table}… |
schema-qualified form of every route above; {base}/{schema}/rpc/{x} always names a function of the schema (404 when there is none), so a table named rpc has no /{pk} path (its list and /by/ paths stay; build warning) |
|
GET {base}/rpc/{fn}?arg=v |
stable/immutable function | see RPC |
POST {base}/rpc/{fn} (JSON body {arg: v}) |
any function; volatile via GET → 405 (Allow: POST) |
|
GET {base}/openapi.json |
OpenAPI 3.1 document (openapi.enabled, default true) |
200 |
OPTIONS * |
CORS preflight when server.cors_origins is set |
|
GET /healthz, GET /readyz |
{"status":"ok"} — not under {base}; /readyz pings the database (server.readyz_timeout) |
200, /readyz 503 unavailable when the database is unreachable |
HEAD is accepted wherever GET is and returns the same headers without a
body.
Views, materialized views and tables the connection role cannot write have no
write methods; calling one returns 405 with Allow listing what exists.
server.read_only: true turns every write into 405 (code: read_only) and
can be toggled at runtime through App.SetReadOnly.
For each table/view in schema.schemas the connection role can SELECT:
| Postgres | pdbr |
|---|---|
table users |
resource /users (/public/users canonical; bare alias for schema.schemas[0]) |
| rows | GET /users (select, filters, order, limit/offset, after/before, count, distinct; aggregates select=mood,count() with aggregates.enabled, aggregates.md) |
| primary key | GET /users/{id}, PATCH/DELETE /users/{id}, keyset cursors, ETag |
| unique constraints | GET /users/by/email/{email} (+ PATCH/DELETE), PUT /users?on_conflict=email |
| foreign keys | embeds posts?select=*,users(*) (forward) and users?select=*,posts(*) (backward), relation filters and order |
PostgreSQL 18 temporal keys (WITHOUT OVERLAPS), PERIOD and NOT ENFORCED foreign keys |
see Temporal keys: no single-row routes or conflict targets for temporal keys, PERIOD embeds are arrays |
partitioned table orders |
one resource like any table (reads, writes and embeds span every partition; inserts are routed by PostgreSQL); its partitions are not resources unless schema.expose_partitions: true, and then only with the keys and FKs declared on the partition itself (inherited ones are recorded on the parent) |
INSERT/UPDATE/DELETE privileges |
POST /users, PATCH /users/{id}, DELETE /users/{id}, PUT /users |
| enums | verbatim labels in bodies, responses and filters (mood=eq.happy) |
| composite types | nested JSON objects ("address": {"street": …}) on read and write; arrays too |
| stable/immutable functions | GET/POST /rpc/{fn} (RETURNS TABLE / OUT params → objects keyed by the result columns) |
| volatile functions | POST /rpc/{fn} (mutation semantics) |
fn(<table>) stable functions |
computed columns (users_post_count → select=post_count) |
| PostGIS columns | GeoJSON in/out, ~<col>_area, ~<col>_centroid, … pseudo-columns, spatial filters, .st_distance ordering |
| everything | GET /openapi.json |
Identifiers are raw PostgreSQL names — nothing is camel-cased, singularized or prefixed:
- Path segment = table/view name verbatim (percent-encoded if needed). JSON keys = column names verbatim. Enum values = labels verbatim. RPC path = function name.
- Multi-schema. Every resource has a canonical
/{schema}/{table}and/{schema}/rpc/{fn}. Resources inschema.schemas[0]also get the bare alias/{table}and/rpc/{fn}. A bare alias is suppressed with a startup warning when it collides with a reserved segment:rpc,openapi.json,healthz,readyz,by. - Relation keys (embeds, filter paths, order paths, nested-mutation
bodies): forward FK → the referenced table name; backward FK → the
referencing table name. Two FKs to the same table, or a self-reference,
yield the same key and require a hint:
rel!fk_constraint_name(...)orrel!column(...); unhinted →400 ambiguous_relationlisting the candidates.@fieldName/@foreignFieldNameon the FK comment set explicit keys and remove the need for a hint. - Computed columns: function name with the
<table>_prefix stripped (users_post_count→post_count);@nameoverrides. A real column with the same name wins and the computed column is skipped with a warning. - PostGIS pseudo-columns:
~<col>_area,_length,_perimeter,_centroid,_envelope,_srid,_geometry_type,_is_valid,_x,_y,_z,_m,_num_points,_num_geometries,_start_point,_end_point,_point_on_surface,_wkt,_ewkt,_is_empty,_is_simple,_xmin,_ymin,_xmax,_ymax(the type-specific ones only where the column's typmod allows them — postgis.md; a real column of that name wins). - Score pseudo-columns:
~<col>_st_distance(spatial, from~near=),~<col>_trgm_similarity,_word_similarity,_strict_word_similarity(pg_trgm, against~trgm=) and~<col>_l2_distance,_negative_inner_product,_cosine_distance,_l1_distance,_hamming_distance,_jaccard_distance(pgvector, from~vec=),~<col>_chebyshev_distanceand the L2 / L1 ones on cube columns (from~vec=),~<col>_earth_distanceand~<col>_earth_miles_distance(earthdistance, from~latlon=) and the raster~<col>_value(band=)(from~near=): the pdbcore expression names in snake_case, the same names pdbq gives its<field>Distance/<field>Similarity/<field>CosineDistancefields (postgis.md, contrib.md). - Overloaded functions and duplicate route names: keep-first + warning (of several overloads, the one with the fewest input parameters, see rpc.md).
Route precedence between /{schema}/{table} and /{table}/{pk} (decided
in M1, as built in api.Built.Match): a first segment equal to a configured
schema name is always the schema-qualified form; a schema.schemas[0] table
whose name equals another configured schema loses its bare alias (startup
warning), like the reserved segments. /{schema}/rpc/{fn} wins over a table
named rpc in that schema, falling back to the table when no such function
exists.
Reserved: select, order, limit, offset, after, before, count,
distinct, on_conflict (and columns on writes), plus everything that
starts with ~ (see The ~ namespace). Every other
parameter is a filter (col=op.value, rel.col=op.value,
and=/or=/not.and=/not.or=) — see filtering.md. A
column literally named like a reserved parameter cannot be filtered in the
bare form; use it inside and=(…).
Names pdbr generates next to the catalog's own start with ~, so no column,
computed column, relation or function argument can ever take their place:
adding a column named near or location_area to a table, or a function
argument named vec, does not change what any request means.
- Reference parameters:
~near=(spatial distance, raster pixel value),~trgm=(trigram distance and similarity),~vec=(pgvector and cube distances),~latlon=(earthdistance),~levenshtein=(edit distance) and~geometry=(the Feature geometry ofAccept: application/geo+json). Each is request-wide: one value serves the root and every embed. - Pseudo-columns: every value pdbr derives from a column is
~<col>_<name>: PostGIS accessors (~location_area,~location_srid), raster accessors (~rast_width,~rast_value), distance and similarity scores (~location_st_distance,~emb_cosine_distance,~title_trgm_similarity), headlines (~body_headline) and the ltree/intarray accessors (~path_nlevel,~tags_icount). The response key is that name,~included, unless the item is aliased (select=area:~location_area).
A query parameter, select= item, filter key or order= term that starts
with ~ always resolves in this namespace: ~nope is 400 unknown_column
(or invalid_parameter for a misused reference parameter), never a column.
A column whose name starts with ~ is therefore returned by select=* but
cannot be named by any query parameter: not as a select= item (cast, JSON
path and aggregate forms included), filter key, order= term (JSON path,
distance and related forms included), distinct=, on_conflict= or
columns= entry (400 unknown_column; invalid_body for columns=). A
JSON body still writes it under its own key. pdbr logs a warning at build
time. Real columns named near or location_area are ordinary
columns, filterable as near=eq.x next to ~near=.
Absent select means all columns (*). Grammar:
select := item ("," item)*
item := field | alias ":" field | embed | "..." embed | "*" | [ alias ":" ] aggregate
field := name [ "(" k "=" v ("," k "=" v)* ")" ] -- args only for spatial projection (transform=<srid>, simplify=<tol>, buffer=<distance>, precision=<digits>), geometry distance (spheroid=true), contrib derived values and headlines (document=<col>, max_words=…)
| column [ jsonpath ] [ "::" type ] -- JSON path and/or cast
embed := relkey [ "!" hint ]* "(" select ")" -- hint := fk_name | column | "inner"
name := column | computed column | postgis, contrib, headline or score pseudo-column
aggregate := "count()" | column [ jsonpath ] [ "::" type ] "." fn "()" [ "::" type ] -- aggregates.enabled
fn := count | sum | avg | max | min | extent | union | collect | centroid
jsonpath := ( "->" step )* [ "->>" step ] -- at least one arrow
step := key | '"' any-but-quote '"' | [ "-" ] digits -- object key or array index
type := allowlisted built-in scalar type | enum of the API
Aggregate functions (off by default, aggregates.enabled) group the result
by the other items of the same select= (columns and computed fields, not
embeds): select=author_id,count(), select=total:amount::numeric.sum()::text,
select=id,posts(count()). See aggregates.md for grouping,
embeds, the cast allowlist, ordering, paging, the
spatial extent/union/collect/centroid extensions and the differences
from PostgREST.
GET /users?select=id,email
GET /users?select=id,n:email -- alias: {"id": 1, "n": "a@b.c"}
GET /users?select=*,post_count -- all columns + a computed columnUnknown names → 400 unknown_column. Two items answering under the same
response key are 400 invalid_select (alias one of them), unless they are
the same column selected again (select=*,email or select=id,id answer
once): select=id,email,email:full_name, select=*,mood::text and
select=excerpt(max_chars=5),excerpt:title are rejected. PostgREST would
return both keys. Aliases (and JSON-path keys) are bind parameters in the
compiled SQL, never SQL text, so any character the grammar admits is safe.
* expands to real columns only (PostgREST behaviour, as built in
compile.rowJSON); computed columns and pseudo-columns (PostGIS and contrib accessors, scores) must be named
explicitly (select=*,post_count). The OpenAPI resource schema still lists
them (readOnly, "Select explicitly: select=").
-> and ->> reach into json/jsonb columns, and into array and
composite columns through to_jsonb(col) (PostgREST's form, so an
expression index on to_jsonb(col)->'k' serves it): -> yields JSON,
->> text, an integer step indexes an array (negative from the end). A
column that holds table rows or rasters (a row type, an array of rows, a
composite with such an attribute) is read through its rendered JSON
instead, so paths and casts only reach the nested rows' readable columns;
such a column cannot be filtered, ordered, grouped or given to max() /
min().
GET /users?select=id,settings->theme,mode:settings->>theme,tags->0,address->>city[{"id": 1, "theme": "dark", "mode": "dark", "tags": "admin", "city": "London"}]- The response key is the alias, else the last key of the path
(
settings->a->>b→b), else the column (tags->0→tags). - Bare keys are letters, digits,
_,$and-; anything else (.,,,:, parentheses,!, spaces, an empty key) is double-quoted:settings->"a.b".->>may only be the last step. - Keys and indexes travel as bind parameters (
t."settings" -> $1::text); the SQL text depends only on the number of steps and their kinds. - Missing keys and out-of-range indexes are
null. On an hstore column a path is exactly one key (attrs->color,attrs->>color), the text value of that key (contrib.md). A path on any other column type is400 invalid_select. - Filters (
settings->>theme=eq.dark, filtering.md) andorder=(order=settings->>theme.desc) take the same paths.
column::type and column->path::type cast the selected value; the
response key stays the column's (or the path's last key):
GET /users?select=id::text,balance::int8,n:settings->n::int[{"id": "1", "balance": 0, "n": 20}]The target is a built-in scalar type (smallint/int2, int/integer/
int4, bigint/int8, numeric/decimal, real/float4, float/
float8, text, varchar, char/bpchar, boolean/bool, date,
time, timetz, timestamp, timestamptz, interval, uuid, json,
jsonb, money) or an enum of an exposed schema; the reg* types,
pseudo-types and composites are 400 invalid_select. The cast is rendered
schema-qualified (::"pg_catalog"."text") and the result through
to_json, so cast numbers (bigint included) are JSON numbers. A failing
conversion is a database error (400 pg:22P02, …). Casts apply to columns
and JSON paths only (not computed columns or embeds), and not to filters
(as in PostgREST: a cast would defeat the column's indexes).
An embed compiles to a LEFT JOIN LATERAL inside the same statement:
| Direction | Key | Result |
|---|---|---|
| forward (the FK is on this table) | referenced table name | object, or null when the FK is null, the referenced row is missing (NOT ENFORCED FK) or an embed filter excludes it; an array for a PERIOD FK |
| backward (the FK points at this table) | referencing table name | array (possibly empty) |
GET /posts?select=id,title,users(id,email) -- forward: post → author
GET /posts?select=id,title,author:users(email) -- aliased
GET /users?select=id,posts(id,title,comments(id)) -- backward, nested[{"id": 1, "posts": [{"id": 7, "title": "Hello", "comments": [{"id": 3}]}]}]Nesting depth is bounded by limits.max_depth (default 5); deeper →
400 depth_exceeded. Cost is bounded by limits.max_cost — see
pagination.md.
...rel(cols) hoists the embed's items into the parent object instead of
nesting them under a key (PostgREST 12):
GET /posts?select=id,...users(author:email,mood)
GET /users?select=id,...posts(titles:title,ids:id)&posts.order=id.desc[{"id": 1, "author": "ada@example.com", "mood": "happy"}]
[{"id": 1, "titles": ["Unpublished draft", "Notes on the Analytical Engine"], "ids": [2, 1]}]- A to-one spread contributes its values; without a related row (or
when an embed filter excludes it) they are
null.!innerdrops such parents, as for any embed. - A to-many spread contributes one array per item, aggregated in one
pass over the related rows so the arrays are correlated (same order: the
embed's
order=, then its primary key;[]without related rows). Per- embed parameters address the spread by its relation key (posts.order=,posts.limit=,posts.title=…). - Spreads nest (
...posts(title,...users(email))) and may contain plain embeds (an embed inside a to-many spread becomes an array of objects); a to-many spread inside another becomes an array of arrays. - The spread itself takes no alias (
x:...rel(…)is400 invalid_select); alias its items. An item answering under a key the parent already has is400 invalid_select, like any duplicate key (select=id,...users(id)): alias it (...users(author_id:id)). - In an aggregate select, a to-one spread's items are the parent's own:
its columns group, its aggregates aggregate over the joined rows
(aggregates.md). Aggregates inside a
to-many spread are
400 invalid_select. - CSV accepts spreads (their items are columns of the row) unless they nest a plain embed.
- Cost: a spread costs what the same embed costs (pagination.md).
comments.parent_id references comments, so both the forward and the
backward key are comments; posts and places both point at users, but
that is one FK per table and needs no hint.
GET /comments?select=id,parent:comments!parent_id(id,body) -- forward by column
GET /comments?select=id,replies:comments!comments_parent_id_fkey(id) -- backward by FK name
GET /posts?select=title,users!inner(email)&users.email=eq.a@b.c -- inner!fk_constraint_name/!columndisambiguate.!columnnames a column of the FK on the referencing side. A hint that selects none of the key's FKs (comments!nope(id), or PostgREST's!left) is400 unknown_relation, with the valid hints in the detail.!innerturns the lateral join into an inner one: a filter on the embed restricts the parent rows (compiled asEXISTS), and parents with no match are dropped instead of carryingnull/[].
Hints can be combined: comments!parent_id!inner(id).
Array embeds (backward, and forward over a PERIOD FK) accept their own
paging, ordering and filters, addressed by the relation key (or its alias
when one is given):
GET /users?select=id,posts(id,title)&posts.order=title.desc&posts.limit=5&posts.offset=5
GET /users?select=id,posts(id,title)&posts.published=is.trueWithout !inner a filter on a backward embed only narrows the embedded list;
a filter on a forward embed nulls out the object. With !inner both also
restrict the parent. Embedded filters and orders follow the embedded table's
own indexed-only policy.
As built: <embed>.limit/.order/.offset and <embed>.<col>=<op>.<value>
address a selected embed by its response key — the alias when one is
given (recent:posts(id)&recent.limit=3, PostgREST style), the relation
key otherwise — and nest (posts.comments.limit=2). Per-embed
after/before/count/select/distinct are rejected (400 invalid_parameter): embedded lists are offset-paged.
PostgreSQL 18 adds temporal keys, PRIMARY KEY / UNIQUE (…, valid_at WITHOUT OVERLAPS): the last column is a range (or multirange), the leading
columns repeat once per non-overlapping period. It also adds temporal
foreign keys, FOREIGN KEY (…, PERIOD valid_at) REFERENCES t (…, PERIOD valid_at), and NOT ENFORCED foreign keys. pdbr handles them like this:
| Object | Behaviour |
|---|---|
| temporal primary key | no /{pk} row route (404), no ETag, not the default PUT conflict target; it still orders the default listing and backs keyset cursors (the range value travels in the cursor) |
| temporal unique constraint | no /by/{cols}/{vals} route |
?on_conflict= naming a temporal key |
400 temporal_conflict_target on PUT and Prefer: resolution=merge-duplicates: PostgreSQL enforces the key as an exclusion constraint, which ON CONFLICT (cols) cannot infer and DO UPDATE does not support; resolution=ignore-duplicates accepts it (ON CONFLICT ON CONSTRAINT … DO NOTHING) |
PUT |
offered only when the table has a plain primary key or unique constraint; a table whose only key is temporal has no PUT (405) and, without a row route, is updated and deleted only by filter on the collection (PATCH/DELETE /bookings?room_id=eq.1&…) |
| duplicate (overlapping) period on insert/update | 409 pg:23P01 (exclusion violation) |
PERIOD FK, forward embed |
an array of every referenced row whose period overlaps the row's own (the child's period may be covered by several parent rows), ordered by the referenced primary key; per-embed parameters apply |
PERIOD FK, backward embed |
an array of every referencing row whose period overlaps |
PERIOD FK, joins |
child.k = parent.k AND child.valid_at && parent.valid_at for embeds, !inner, relation filters (!none/!every accepted in both directions) and related order terms (aggregated with MIN/MAX in both directions) |
PERIOD FK violation |
409 pg:23503 |
NOT ENFORCED FK |
an ordinary relation; the forward embed is null when no referenced row exists, even for NOT NULL FK columns (the OpenAPI property is nullable and says so) |
GET /booking_notes?select=id,note,room_bookings(guest,valid_at)[{"id": 1, "note": "late checkout", "room_bookings": [
{"guest": "ada", "valid_at": "[2026-01-01,2026-01-05)"},
{"guest": "bo", "valid_at": "[2026-01-05,2026-01-10)"}]}]Nested writes over a PERIOD FK copy only the equality columns: see
mutations.md.
GET /users?select=id,post_count -- users_post_count(users) → "post_count"
GET /places?select=name,location,~location_srid,~area_area
GET /places?select=name,web:location(transform=3857),coarse:area(simplify=0.01)Computed columns come from stable/immutable functions whose first argument is
the table's row type; set-returning ones become arrays. Extra arguments are
passed as field(k=v,…): select=id,excerpt(max_chars=80), aliased
short:excerpt(max_chars=40). Values are bare text or double-quoted
(name="a,b"), coerced by the argument's type and bound as parameters; an
omitted argument takes its DEFAULT, an omitted argument without one → 400 missing_argument, an unknown name → 400 unknown_argument, a bad value →
400 invalid_argument. A SETOF <table> column takes its nested select after
the arguments: recent_posts(n=2,id,title). Parenthesised arguments on
spatial columns and their pseudo-columns are buffer=<distance> →
ST_Buffer, simplify=<tolerance> → ST_SimplifyPreserveTopology,
transform=<srid> → ST_Transform and precision=<digits> → the
ST_AsGeoJSON decimal digits (postgis plugin,
postgis.md). Spatial values are GeoJSON
on output; GeoJSON or WKT/EWKT on input.
GET /rpc/search_posts?q=hello
POST /rpc/search_posts {"q": "hello"}GETfor stable/immutable functions,POSTfor any volatility. Volatile functions run with mutation semantics (transaction,405when read-only).- Arguments by name, coerced by pg type; missing → SQL
NULL; unknown →400. Enum labels verbatim; spatial arguments GeoJSON or WKT. - Returns: scalar → JSON value
200;void→204; single row (table or composite) → object200(nullwhen the function returns NULL); `SETOF ` → array with full `select=` (embeds included), filters, `order=`, `limit`/`offset`, `count=true` and CSV — offset paging only, no cursors; `SETOF ` → array of values. A function returning the `auth.mint_type` composite returns a minted HS256 JWT string. - Not exposed: functions without EXECUTE privilege, extension-owned, unnamed
args,
OUT/INOUT/VARIADIC, trigger/internal returns. Overloads → keep-first + warning.schema.functions: falseremoves RPC and computed columns entirely. - Responses are
application/json; charset=utf-8. Request bodies must beapplication/json→ otherwise415 unsupported_media_type. int8,numericandmoneyare serialized as JSON strings (no precision loss); on input a JSON number or string is accepted.byteais base64. Timestamps are ISO 8601. Composite-typed columns are nested objects (arrays of composites too). Enum labels verbatim.- Objects are built with
json_build_object/json_agg(as PostgREST does), so keys follow theselect=order (embeds after the columns, composite attributes in declaration order),jsoncolumns come back as stored,float8uses PostgreSQL's float output (1e+20), and the text has PostgreSQL's spacing ({"id" : 1}): compare bodies as JSON, never byte for byte. - Body validation: unknown key →
400 invalid_body; generated and identityALWAYScolumns →400 column_readonly(identityBY DEFAULTcolumns are writable); on create,NOT NULLcolumns without a default, identity or generation are required; onPATCHeverything is optional. select=applies to mutation responses (compiled against the__mutCTE, embeds work;RETURNINGlists only referenced columns).- Nested writes on
POSTand single-rowPATCH(pluginnested_mutations): forward key →{"create": {…}}or{"connect": {<key cols>}}(exactly one onPOST; the key is the referenced columns, the primary key or one unique constraint —{"email": "…"}connects a user), onPATCHalso{"disconnect": true},{"update": {…}},{"delete": true}; backward key → lists undercreateandconnect, onPATCHalsoupdate([{"where": {…}, "data": {…}}]),delete,disconnect; depth ≤ 3 (plugins.settings.nested_mutations.max_depth); FK columns become optional when nested input is provided; a nested lookup that matches nothing is404and rolls the request back (mutations.md). - One header row, then one record per row,
CRLFrecord ends; fields are quoted by the encoder when they contain,,", a carriage return or a line feed, or start with white space ("doubled). Everything else inside a quoted field is copied byte for byte: a value's own\r,\nor\r\ncomes out exactly as it is stored. - Column order =
select=order:*expands to the resource's columns in catalog order, explicit items follow (an unaliased duplicate of a*column is dropped), aliases rename the header — exactly the compiled projection. Set-returning composite functions use the type's attributes; scalar sets (SETOF text,SETOF mood) have a singlevaluecolumn. - Values: strings verbatim, numbers/booleans as their JSON literals,
arrays / json / composites / GeoJSON as compact JSON text, NULL and
missing keys as an empty field (no
\Nsentinel). - Formula escaping (CSV injection): a header or string cell that starts with
=,+,-,@, a tab or a carriage return gets a leading', so Excel, LibreOffice and Google Sheets show it as text instead of evaluating it (=HYPERLINK(…)→'=HYPERLINK(…), a text-5→'-5). JSON numbers are never escaped (-5in an integer column stays-5).server.csv_escape_formulas: falsewrites every cell verbatim. - The SQL is identical to the JSON request (goldens unaffected); the server
re-encodes the jsonb array on the way out.
X-Total-Count, cursors andLinkare unchanged, andHEADreturns the same headers with no body. - Errors are always
application/problem+json, even when onlytext/csvwas acceptable. <row>hashes the row asselect=*renders it: every column the resource exposes, in catalog order, composite and domain values through their visible attributes. Columns hidden with@omit/@omit read(smart-comments.md) or by a contract, hidden attributes of composite values and raster columns never reach it, so the ETag neither reveals their values nor changes when only they change.<repr>hashes the response body itself, so it coversselect=, embeds, spreads, computed columns and the media type (Accept: application/geo+jsonhashes the Feature, with the media type mixed in).
| Request | Response |
|---|---|
no Accept, */*, application/*, application/json |
JSON |
Accept: text/csv (or text/*) on a list GET/HEAD or set-returning RPC GET/HEAD |
CSV, Content-Type: text/csv; charset=utf-8 |
Accept: text/csv with an embed in select=, on a single-row path, on a mutation, on a non-set RPC, or with server.csv: false |
406 not_acceptable (the detail says which) |
Accept: application/geo+json on a GET/HEAD of a resource with a spatial column (list, key lookup, SETOF <table> or single-row RPC) |
GeoJSON FeatureCollection / Feature, Content-Type: application/geo+json; ~geometry=<key> picks the geometry item — see PostGIS |
Accept: application/geo+json without a spatial column in select=, with aggregates, on a mutation or a non-row RPC |
406 not_acceptable |
any other Accept |
406 not_acceptable |
Media ranges are ranked by q then specificity, so text/csv;q=0.5, application/json is JSON and text/csv, */*;q=0.1 falls back to JSON when
CSV is unavailable.
CSV rules (RFC 4180, internal/server/csv.go):
CSV is toggled by server.csv (default true); when off the OpenAPI document
drops the text/csv content and the Accept header parameter.
| Header | Effect |
|---|---|
Prefer: return=representation (default) |
body = affected row(s) |
Prefer: return=minimal / return=headers-only |
204 and no body; a single-object POST (or a PUT that inserted) returns 201 + Location and no body |
Prefer: handling=strict |
unknown or malformed tokens → 400 invalid_preference (default handling=lenient ignores them) |
Prefer: handling=strict, max-affected=N |
PATCH/DELETE writing more than N rows → 400 max_affected_exceeded, rolled back |
Prefer: resolution=merge-duplicates|ignore-duplicates |
POST upserts / skips conflicting rows on ?on_conflict= or the PK (mutations.md) |
Prefer: partial=items |
bulk POST/PUT: each element in its own savepoint, answered as a per-element report (207 when one failed); needs transactions.partial.enabled, else ignored (400 under handling=strict) |
Prefer: tx=commit|rollback |
writes: commit or roll back (the result is still returned); needs transactions.end commit-allow-override / rollback-allow-override, else ignored (400 under handling=strict) |
Prefer: timezone=<IANA name> |
the transaction runs with that timezone (validated against pg_timezone_names); unknown → ignored (400 under handling=strict) |
?columns=a,b on POST/PUT/PATCH |
only those body keys are used; others ignored, omitted ones take DEFAULT (mutations.md) |
Prefer: missing=default |
accepted on POST/PUT; omitted keys always take their default in pdbr |
Range: <first>-<last> / <first>- (+ Range-Unit: items) |
list GET/HEAD: offset/limit as a header, intersected with offset/limit; 206 when a counted page is a strict subset of the total, 416 past it (pagination.md); ignored on writes |
Prefer: count=exact|planned|estimated |
list GET/HEAD: total in Content-Range and X-Total-Count (pagination.md); bulk PATCH/DELETE: exact written-row total in Content-Range |
Honoured tokens are echoed in Preference-Applied. Details and the
transaction semantics: mutations.md.
Single-row GETs and HEADs carry a weak ETag: W/"<row>.<repr>", two
md5 hex digests computed in SQL in the same statement:
Responses on API routes carry Vary: Accept, since the body depends on it.
If-None-Match compares the whole tag: 304 only when the representation
the request asks for is unchanged (an embedded post that changed gives
?select=id,posts(*) a new ETag).
PATCH/DELETE on single-row paths honour If-Match against the <row>
part (a tag with or without the .<repr> part), so a tag read through any
select=, embed or Accept guards the same row state. The check is part of
the one statement:
WITH cur AS (SELECT md5((json_build_object('id', __cur."id", …))::text) AS h FROM users __cur WHERE id = $1),
__mut AS (UPDATE users SET … WHERE id = $1 AND (SELECT h FROM cur) = $2 RETURNING …)
SELECT …No cur row → 404; hash mismatch → 412 etag_mismatch. Atomic without a
second round-trip. server.etags (default true) toggles the whole feature;
with it off, If-None-Match is ignored and If-Match is
400 if_match_unsupported on every route, so a conditional write never runs
unconditionally. The hash is of the rendered JSON, so it follows the
request's time zone (Prefer: timezone=) like the body.
Caveat — column-level grants. The hash needs SELECT on every exposed
column. If a role lacks it on an exposed column, single-row GETs on that
table fail with 403; hide the column (@omit read), grant it, or disable
server.etags. A write to a hidden column (or a hidden composite attribute)
alone does not change the ETag, so If-Match does not guard it.
List responses carry no ETag.
| Header | When | Meaning |
|---|---|---|
Content-Range |
offset-addressed list pages and bulk PATCH/DELETE |
<first>-<last>/<total> (* when empty or without a count); */<total> on 416 |
X-Total-Count |
count=true or Prefer: count= on lists / SETOF RPC |
total rows after filters (distinct-aware); computed by a count(*) subquery in the same statement |
X-Next-Cursor |
keyset-capable list, next page exists | opaque cursor for after= |
X-Prev-Cursor |
keyset-capable list, previous page exists | opaque cursor for before= |
Link |
lists | <url?after=…>; rel="next", <url?before=…>; rel="prev" built from the request URL (relative: {base}{path}?{query}, other params kept verbatim and in place); offset-only resources get offset= links and no cursors |
ETag |
single-row GET |
weak row hash |
Location |
201 from a single-object POST (or inserting PUT) on a resource with a single-column PK |
{base}/{table}/{pk} |
Preference-Applied |
a request whose Prefer tokens were honoured |
the honoured tokens, comma-separated (return=minimal, handling=strict) |
Allow |
every 405 (API routes, /openapi.json, /healthz, /readyz) |
methods that exist on the path; empty when none does (a volatile function's route under server.read_only) |
Content-Type |
always | application/json; charset=utf-8, text/csv; charset=utf-8, application/geo+json, or application/problem+json |
Cursor and Link details: pagination.md.
| Limit | Config | Over |
|---|---|---|
| page size | limits.max_page_size (100) |
400 page_size_exceeded (limit=); a Range header is clamped instead |
| embed depth | limits.max_depth (5) |
400 depth_exceeded |
| request cost | limits.max_cost (100000) |
400 cost_exceeded |
| body size | limits.max_body_bytes (1 MiB) |
413 |
| request time | server.request_timeout (30s) |
504 |
| statement time | database.statement_timeout (25s) |
504 |
Errors are RFC 9457 problem documents (application/problem+json) with a
stable code extension:
{"type":"about:blank","title":"Conflict","status":409,
"detail":"duplicate key value violates unique constraint \"users_email_key\"",
"instance":"/users","code":"pg:23505"}errors.detail: dev adds a pg object (sqlstate, message, detail,
hint, table, constraint); prod (default) passes through 22*/23*
messages and makes the rest generic; strict makes every database message
generic (code stays).
Fixture: users(id, email, mood, tags, settings, address),
posts(id, author_id, title, published),
comments(id, post_id, parent_id, body), places(id, name, location, area),
functions search_posts(q) and users_post_count(users).
List with sparse fields, a filter and an embed:
$ curl -s 'localhost:8080/users?select=id,email,posts(id,title)&mood=eq.happy&limit=2'[{"id":1,"email":"a@b.c","posts":[{"id":7,"title":"Hello"}]},
{"id":4,"email":"d@e.f","posts":[]}]Total count and cursors:
$ curl -si 'localhost:8080/posts?order=title.asc&limit=2&count=true'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Total-Count: 41
X-Next-Cursor: WyJwdWJsaWMucG9zdHMiLDJd
Link: </posts?order=title.asc&limit=2&count=true&after=WyJwdWJsaWMucG9zdHMiLDJd>; rel="next"
[{"id":7,"title":"Hello","author_id":1,"published":true},
{"id":2,"title":"Intro","author_id":1,"published":false}]Single row by PK with ETag, then a conditional re-fetch:
$ curl -si 'localhost:8080/users/1?select=id,email,address'
HTTP/1.1 200 OK
ETag: W/"9e107d9d372bb6826bd81d3542a419d6"
{"id":1,"email":"a@b.c","address":{"street":"1 Main St","city":"Leeds","mood":"ok"}}
$ curl -si -H 'If-None-Match: W/"9e107d9d372bb6826bd81d3542a419d6"' 'localhost:8080/users/1'
HTTP/1.1 304 Not ModifiedLookup by unique constraint, with a computed column:
$ curl -s 'localhost:8080/users/by/email/a%40b.c?select=id,post_count'
{"id":1,"post_count":"3"}Insert with a nested forward connect, minimal response:
$ curl -si -X POST -H 'Content-Type: application/json' -H 'Prefer: return=minimal' \
-d '{"title":"New","published":false,"users":{"connect":{"id":1}}}' \
'localhost:8080/posts'
HTTP/1.1 201 Created
Location: /posts/42Conditional update:
$ curl -si -X PATCH -H 'Content-Type: application/json' -H 'If-Match: W/"stale"' \
-d '{"published":true}' 'localhost:8080/posts/42'
HTTP/1.1 412 Precondition Failed
Content-Type: application/problem+json
{"type":"about:blank","title":"Precondition Failed","status":412,
"detail":"row has changed since it was read","instance":"/posts/42","code":"etag_mismatch"}Set-returning RPC as CSV, filtered and ordered:
$ curl -s -H 'Accept: text/csv' 'localhost:8080/rpc/search_posts?q=hello&published=is.true&order=id.desc&limit=2'
id,author_id,title,published
9,2,Hello again,true
7,1,Hello,trueNearest places to a point, with a pseudo-column:
$ curl -s 'localhost:8080/places?select=name,~location_srid&order=location.st_distance.asc&~near=SRID%3D4326%3BPOINT(-0.1281%2051.508)&limit=1'
[{"name":"Trafalgar Square","~location_srid":4326}]Next: filtering.md, pagination.md.