PostgREST
Auto-generated REST API from a curated PostgreSQL schema.
| Category | Integration |
| Deploy | ./uis deploy postgrest --app <name> (per-instance) |
| Undeploy | ./uis undeploy postgrest --app <name> |
| Depends on | postgresql |
| Required by | None |
| Image | postgrest/postgrest:v14.10 |
| Default namespace | postgrest |
What It Does
PostgREST is a single Haskell binary that introspects a PostgreSQL schema and exposes its tables and views as REST endpoints, with foreign keys becoming embedded-resource relations and OpenAPI metadata served at GET /. PostgREST 14.x (the version UIS currently pins, v14.10) emits Swagger 2.0; v15+ may upgrade to OpenAPI 3.x. UIS deploys one PostgREST instance per consuming application, all sharing a single namespace and the platform's PostgreSQL service. Each instance is configured separately via ./uis configure postgrest --app <name>.
Configuration
PostgREST is a multi-instance service: one Deployment per consuming application, configured independently. Before deploying you must answer four questions: which app, which database, which schema, and what URL prefix.
The api_v1 contract (application-side, required)
PostgREST must point at a curated api_v1 schema of views — never at raw application tables. The application owns this schema; UIS does not write it for you. Minimum setup, run once against your application's database:
CREATE SCHEMA api_v1;
-- Curated views over your internal model. Hide debug columns,
-- expose only what you want as a public API.
CREATE VIEW api_v1.kommune AS
SELECT kommune_nr, name, fylke_nr, population_latest
FROM marts.dim_kommune;
Why this rule:
- Decouples the API contract from internal models — refactor your tables without breaking clients.
- Column-level control — internal-only columns (raw scrape timestamps, debug fields) stay in
marts.*and never reach the API. - Versioning — when v2 lands, create
api_v2alongside; deprecateapi_v1on a schedule, no client breakage. - Per-endpoint Row-Level Security later — RLS policies attach to views, not raw tables.
Connection model and role naming
PostgREST does not connect as your application's owner user (e.g. my_app). It uses a separate role pair, created by ./uis configure postgrest:
<app>_authenticator—LOGIN,NOINHERIT, with a generated password. The role PostgREST connects as.NOINHERITis load-bearing: it has no implicit privileges; only whatSET LOCAL ROLEexplicitly switches to is granted.<app>_web_anon—NOLOGIN. The role for unauthenticated requests. HasSELECTonapi_v1.
Per request, PostgREST connects as <app>_authenticator, runs SET LOCAL ROLE <app>_web_anon, executes the query in that role's permissions, then resets at end of request. Your application's existing user and password are untouched.
The <app>_ prefix is required because Postgres roles are cluster-wide. Two apps with unprefixed web_anon would collide on the platform's shared PostgreSQL.
Lifecycle commands
# 0. Bootstrap the application's database (one-time, per app)
# Creates <app>_db + the <app> Postgres role with credentials, and
# auto-exposes the cluster's postgresql service at localhost:35432.
# Run before the application's data pipeline so that api_v1.* views
# exist on the database by the time configure-postgrest runs in step 1.
./uis configure postgresql --app atlas --database atlas_db --json
# → Copy the credentials from the JSON output into the application's
# env (DATABASE_URL, PGUSER, PGPASSWORD, PGDATABASE), then run the
# application's data pipeline (migrations and any data loading) so
# that the api_v1.* views are populated before step 1 runs.
# 1. Configure PostgREST (Postgres-side role pair + Secret in postgrest namespace)
./uis configure postgrest --app atlas \
--database atlas_db \
--schemas api_v1,marts,raw \
--url-prefix api-atlas
# `--schemas` is a comma-separated list — pass one or many. The list is
# stored on the per-app secret (key PGRST_DB_SCHEMAS) and consumed by
# deploy automatically; deploy itself takes no schema flags.
# 2. Deploy (Kubernetes objects: Deployment, Service, IngressRoute)
./uis deploy postgrest --app atlas
# 3. Verify (see [Smoke checks](#smoke-checks) below for the full template)
curl http://api-atlas.localhost/ # Swagger 2.0 metadata
curl http://api-atlas.localhost/kommune # Sample view
api_v1,marts,raw above is Atlas's decided posture, not a stylistic example. The multi-schema
flag exists because Atlas asked for it — PLAN-postgrest-multi-schema-reconciliation, PR #140,
merged 2026-05-06 — and Atlas's published API documentation and customer frontend are built on all
three being anonymously readable.
Narrowing it to api_v1 on least-privilege reasoning reverses a decision that was made, coordinated
across two repositories, shipped, and built on. That has been attempted once — by the maintainer of
this repository, who had shipped the feature at Atlas's request and did not check before recommending
against it.
Equally, do not copy this list into a different tenant. Three schemas is Atlas's answer, not a
default. For a new instance the rule is: name exactly what that application intends to serve
publicly, and nothing else. The anon role receives SELECT on every schema listed.
⚠️ And on every table added to that schema afterwards. Alongside GRANT SELECT ON ALL TABLES,
configure emits ALTER DEFAULT PRIVILEGES … GRANT SELECT ON TABLES per schema — which is what makes
a later-created view readable without a re-configure, and is deliberate. The consequence is that
naming a schema exposes its future contents too, with no per-table review at the point they
appear.
So --schemas is a posture, not a value: it says "everything that will ever be in these
schemas is public", not "these tables are public". A schema a pipeline writes into is a standing
commitment, and the person choosing the list needs that in front of them.
The asymmetry that follows, and it is the useful part when deciding: widening later is cheap and un-publishing is not. A re-run with a different list is a wipe-and-rewrite in one transaction (see Reconfigure semantics) — minutes, no drift to manage. Withdrawing a schema that consumers have already built against is a different kind of problem. When unsure, name fewer.
If a tenant's list looks wrong, that is a conversation with the tenant — and, where it changes what a public API serves, with whoever owns the exposure decision. It is not a flag to tighten in passing.
Step 0 is required before step 1. ./uis configure postgrest runs a precheck that the named database exists in the cluster's PostgreSQL — if it doesn't, configure aborts with a clear error and creates no side effects (no roles, no Secret). Running step 0 first is what guarantees the precheck passes; it also gives the application a role + credentials to write marts.* and api_v1.* into. Step 0 is per-app and idempotent.
What changes at each step:
configure postgresql(step 0) creates<app>_db, the<app>Postgres role with a generated password, grants the role on the database, and auto-exposes the cluster service atlocalhost:35432. Returns connection JSON (no credentials are printed elsewhere — the JSON is the only output that carries the password). Use--rotateto refresh the password.configure postgrest(step 1) creates the role pair (atlas_web_anon,atlas_authenticator) and writes theatlas-postgrestSecret with bothPGRST_DB_URIandPGRST_DB_SCHEMASkeys. The handler dispatches on the cluster's current state — see Reconfigure semantics for the full contract. Re-running with the same--schemasis a no-op; with a different list it wipes-and-rewrites grants to match. If the secret was deleted manually, configure recovers by rotating the password (Reconfigure-fresh-password). If exactly one of the two roles exists, the handler refuses to act and tells you to--purge(the cluster is in an inconsistent state that UIS won't auto-recover from). Use--rotateto force a new password and update the Secret without changing schemas.deploy(step 2) renders per-instance manifests and applies the Deployment, Service, and IngressRoute. Errors out if the instance has not been configured.undeployremoves only the Kubernetes objects. Postgres roles and the Secret remain, so a follow-updeployworks without re-configure.configure postgrest --purgedrops the Postgres roles and removes the Secret. Pass--database <app>_dbexplicitly — without it, purge falls back to<app>as the default database name and aborts with "FATAL: database does not exist" (see Troubleshooting). Use afterundeployfor a full teardown.
Smoke checks
Five canonical checks verify a per-app PostgREST instance is healthy after deploy. Run these from the host machine after step 2:
# 1. Spec served, version pinned (default schema = first in --schemas)
curl -sS http://api-<app>.localhost/ | jq '{swagger, version: .info.version}'
# expect: {"swagger":"2.0","version":"14.10"}
# 2. Real data flowing through a curated view (default schema)
curl -sS http://api-<app>.localhost/<view-name> | jq 'length'
# expect: > 0
# 3. Each schema in --schemas is reachable via Accept-Profile
# PostgREST exposes one schema per request; the first schema in
# PGRST_DB_SCHEMAS is the default (no header needed). Switch to a
# non-default schema by setting Accept-Profile per request.
for profile in api_v1 marts raw; do
paths=$(curl -sS -H "Accept-Profile: $profile" http://api-<app>.localhost/ | jq '.paths | length')
echo " $profile -> $paths paths"
done
# expect: each schema reports a non-zero path count matching the table
# count for that schema (one row per /table-or-view + 1 for the root /).
# 4. Hidden objects stay hidden (e.g. private_marts not in --schemas)
curl -sS -o /dev/null -w '%{http_code}\n' \
-H 'Accept-Profile: private_marts' http://api-<app>.localhost/
# expect: 404 (the schema isn't in PGRST_DB_SCHEMAS, so PostgREST refuses
# to switch to it).
# 5. CORS preflight works for browser callers
curl -sS -X OPTIONS \
-H 'Origin: https://<your-frontend-host>' \
-H 'Access-Control-Request-Method: GET' \
http://api-<app>.localhost/<view-name> -i | grep -i access-control
# expect: Access-Control-Allow-Origin: ...
Proving the write-refusal check can actually fail
./uis verify postgrest --app <name> asserts that a write through the API is
refused. That is a security property, so it is worth knowing it can fail —
and the obvious way to try it silently does nothing:
-- ✗ does NOT falsify anything
GRANT INSERT ON ALL TABLES IN SCHEMA api_v1 TO web_anon;
Two reasons: the role is per-app (<app>_web_anon, never a bare web_anon —
see Connection model and role naming above), and ON ALL TABLES covers only tables that exist
at grant time, while the verify creates its probe table during the run.
-- ✓ actually loosens the instance
ALTER DEFAULT PRIVILEGES IN SCHEMA api_v1
GRANT INSERT ON TABLES TO atlas_web_anon;
The verify then fails, reporting that an unauthenticated write endpoint is live.
Revert with the matching REVOKE, or re-run uis configure postgrest --app <name>, which rebuilds the grants from scratch.
Check 1 confirms PostgREST is alive and the pinned image is what's actually running. Check 2 confirms the default schema (the first one in --schemas) is reachable and populated. Check 3 is the multi-schema verification: it walks the full --schemas list, fetching the OpenAPI spec under each Accept-Profile and asserting each schema has a non-zero path count. Don't skip this check on a multi-schema instance — without Accept-Profile, root-path probes only verify the default schema, which masks broken GRANTs on the other schemas. Check 4 confirms private_* schemas (or anything else not in --schemas) return 404 even when explicitly requested. Check 5 confirms CORS is open enough for browser apps.
Schema reload
When you add a new view to api_v1, PostgREST does not see it until its schema cache is invalidated:
-- Hot reload, no downtime: signal from any psql session against the database
NOTIFY pgrst, 'reload schema';
Or restart the pods for a clean cycle:
kubectl rollout restart deployment/<app>-postgrest -n postgrest
./uis configure postgrest automatically issues the NOTIFY at the end of any non-no-op run, so a freshly-configured instance picks up new tables without manual intervention. The kubectl rollout is only needed if you change the order of --schemas (PostgREST re-parses the env var only at startup; the first schema in the list is the default served when Accept-Profile is omitted).
Reconfigure semantics
./uis configure postgrest --app <app> --schemas <list> is the only way to change the schema set served by an instance. The handler is wipe-and-rewrite:
- The list passed via
--schemasis the complete, ordered set of schemas the instance will expose. - Each non-no-op call drops every grant the
<app>_web_anonrole currently holds in the database (DROP OWNED BY), then re-appliesGRANT USAGE/GRANT SELECT ON ALL TABLES/ALTER DEFAULT PRIVILEGESfor each schema in--schemas. All inside a single transaction. - A re-run with the identical list (string-equal to the value stored on the secret, order included) is a no-op short-circuit — no SQL fires, no secret is rewritten.
- A re-run with a different list (added schemas, removed schemas, or just reordered) is a regular reconfigure: the wipe-and-rewrite produces an end state that matches
--schemasexactly. There's no diff state to manage; the new state is fully determined by the flag value.
This keeps the operator-visible contract simple: the role's grants are exactly --schemas, no more, no less. No accumulated drift across reconfigures, no stealth pg_default_acl entries from removed schemas, no need to track what was previously granted.
The trade-off: any out-of-band GRANT … TO <app>_web_anon (e.g., a manual GRANT done from psql for debugging) will be wiped on the next configure. See UIS-managed role contract below.
Inspecting the current schema list
The schema list lives on the per-app secret as the PGRST_DB_SCHEMAS key. Read it with one kubectl line:
kubectl get secret <app>-postgrest -n postgrest \
-o jsonpath='{.data.PGRST_DB_SCHEMAS}' | base64 -d
The deploy template reads from this same key via valueFrom.secretKeyRef, so what kubectl prints is exactly what PostgREST sees on its next pod startup. (Live PostgREST may be running with a stale value if you reconfigured but haven't rolled out a new pod — kubectl rollout restart deployment/<app>-postgrest -n postgrest to refresh.)
UIS-managed role contract
The <app>_web_anon role's privileges are exclusively UIS-managed. ./uis configure postgrest --app <app> is the single source of truth: it wipes and re-applies grants based on --schemas. Any manual GRANT … TO <app>_web_anon will be lost on the next configure.
If you need an extra grant for debugging or one-off access, prefer:
- A separate Postgres role (not the UIS-managed pair).
- An ad-hoc psql session as the
postgressuperuser, scoped to a specific query.
Don't extend the anon role's reach by hand — the configure handler will undo it.
Upgrading from PLAN-002 single-schema
PLAN-002 shipped a single-schema configure handler with a --schema flag. The current multi-schema handler (PLAN-XXX) replaces that with --schemas and stores the list on the per-app secret as a new PGRST_DB_SCHEMAS key.
If you have a per-app PostgREST instance configured under PLAN-002, the secret has only PGRST_DB_URI (no PGRST_DB_SCHEMAS). Upgrade in one step:
./uis configure postgrest --app <app> --database <app>_db --schemas <list>
This takes the Reconfigure-preserve-URI path:
- The existing
PGRST_DB_URIis preserved verbatim — password unchanged, no restart needed for credentials. - Grants are reset to match
<list>exactly viaDROP OWNED BY+ per-schema GRANTs. - The new
PGRST_DB_SCHEMASkey is added to the secret.
If <list> includes api_v1 (the PLAN-002 default), the resulting grants on api_v1 are functionally identical to before. Other schemas in <list> get the same USAGE + SELECT + DEFAULT PRIVILEGES treatment.
--rotate requires PGRST_DB_SCHEMAS to be present on the secret — running it on a PLAN-002-era secret without first running configure with --schemas will fail loudly with an explicit "run configure first" error. This is deliberate: rotate is not the upgrade path.
Multi-instance coexistence
After configuring two apps, the postgrest namespace contains:
postgrest/
├── atlas-postgrest (Deployment, Service, IngressRoute, Secret)
│ → Postgres roles: atlas_web_anon, atlas_authenticator
│ → matches HostRegexp(`api-atlas\..+`)
└── customers-postgrest (Deployment, Service, IngressRoute, Secret)
→ Postgres roles: customers_web_anon, customers_authenticator
→ matches HostRegexp(`api-customers\..+`)
No shared state between instances. Independent deploy / undeploy / configure cycles per app.
Resulting URLs
A single IngressRoute per instance answers every domain Traefik knows, via HostRegexp (see Ingress and Traefik Rules):
| Environment | URL |
|---|---|
| Local dev (Rancher Desktop) | http://api-atlas.localhost |
| Tailscale tunnel | https://api-atlas.<tailnet>.ts.net |
| Cloudflare tunnel | https://api-atlas.<your-public-domain> |
No per-domain configuration in PostgREST or its IngressRoute.
Where the OpenAPI spec is served, and the two aliases
PostgREST serves its OpenAPI document at the root, /, as application/openapi+json.
🔴 Every other path is a table name to PostgREST, so the conventional spec filenames do not 404 the way a reader expects:
GET /openapi.json -> 404 PGRST205 "Could not find the table 'api_v1.openapi.json'"
That does not read as "no spec here" — it reads as a failed dataset lookup, and an agent parsing it concludes the API has no machine-readable description at all. The spec is several hundred KB away at /.
So UIS routes two conventional names to the root:
| path | served |
|---|---|
/ | the spec |
/openapi.json | the spec — Traefik replacePath to / |
/swagger.json | the spec — Traefik replacePath to / |
🔵 This is routing only. There is no second document and no conversion step, so there is nothing that can drift out of date — the aliases cannot become stale because they serve the same bytes.
':::warning Deploying this alias falsifies anything that documented the 404 If a published artifact — an API description, a README, a data-catalogue entry — says these paths return 404, that sentence becomes false the moment this deploys, and the API starts telling machines not to use a path that works.
🔴 Change the text first, then deploy. The two can never be simultaneous: the spec at / is edge-cached, so a description corrected after the fact keeps serving the old wording for up to the Edge TTL.
🔵 The two orders are not symmetric, which is what makes this decidable:
| order | the window it leaves |
|---|---|
| text first | the description merely stops promising a path that happens to work — harmless |
| alias first | the API actively misdirects: a working path documented as broken, and the cache extends the window |
⚠️ More generally: a documented limitation is a claim with an expiry, and the expiry belongs beside it. "Returns 404 today" has no mechanism behind the word today. Name what would falsify it — "until the platform aliases these paths" — so the sentence carries its own trigger. :::
The alias route carries no ForwardAuth middleware. Its Traefik priority (15) is deliberately below oauth2-proxy's (20), so on a gated instance the gate still wins.
Do not raise it. An alias that outranked the gate would serve the full schema of every exposed view to anyone who asked, past authentication, and nothing downstream would report it.
Note the spec still describes itself as swagger: "2.0". Converting to OpenAPI 3.x is a separate question — a generated artefact that has to be published, versioned and kept in sync — and the alias deliberately does not touch it: the filename problem is routing, the version problem is not.
Limitations and gotchas
🔴 db-max-rows is unset, and its absence is part of the contract
UIS sets nine PostgREST settings and db-max-rows is not one of them. That is not an oversight, and it is not safe to "tidy up" later.
With it unset, a client asking for 100,000 rows gets 100,000 rows. Set it, and that client gets the first N — with a 200, a well-formed body and no error. A consumer computing coverage from the result reports plausible numbers that are quietly wrong, and nothing anywhere says so. It is the same shape as a check that cannot distinguish all the rows from the first N rows.
db-aggregates-enabled is a reasonable request — server-side count, sum, avg instead of pulling the table. The usual mitigation for the load it invites is exactly db-max-rows plus a statement timeout, and it is what a requester will propose, because it is the correct mitigation for that risk.
Granting the aggregates request with that mitigation silently caps every unpaged consumer. Two sensible decisions, made separately, combine into a data-integrity bug. If you enable aggregates, solve the load some other way, or find and fix every unpaged consumer first — and treat "nobody has complained" as unmeasured rather than as evidence.
Removing one consumer's exposure is not the same as it being safe to set. A known consumer can be migrated to a summary view by agreement; the next one will not have written a contract with anyone, and will find out in production.
If you decide to set it anyway
That is a legitimate call — an unbounded row limit is a real availability risk on a public API. But it changes an API contract, so:
- Announce it before setting it, not in the release notes afterwards.
- Publish a summary or aggregate view first, so unpaged consumers have somewhere to go.
- Update this page in the same change — the claim above must never be stale. A static test asserts that UIS really does not set it, so the page and the code cannot drift apart silently.
🔴 openapi-mode is unset, and unset is already the safe value
PostgREST's default is follow-privileges — the spec shows only what the requesting role may actually do. UIS does not set this option, so that default is what runs.
⚠️ This matters because the wrong fix is tempting. If the published spec advertises POST, PATCH and DELETE on relations the database refuses, the intuitive move is to set openapi-mode. Setting it to follow-privileges changes nothing — that is already the value. Setting it to ignore-privileges makes the problem permanent: the spec then advertises every exposed relation's methods regardless of grants, by design.
🔵 So a spec that over-advertises writes is not an openapi-mode problem. On PostgREST v14.10 with this option at its default, look instead at:
- A stale schema cache. PostgREST caches the schema, including privileges. Grants tightened after the cache was built are not reflected until it reloads —
NOTIFY pgrst, 'reload schema', which an application's publish job is what normally issues. Reload, then re-readGET /: if the write methods disappear, that was it. - Structural writability. An auto-updatable view or a plain table is structurally writable whether or not the role may write it. If the methods survive a reload, the advertisement is upstream behaviour rather than our configuration, and documenting the spec is then the right layer.
Those two are distinguished by one reload, so nobody needs to guess which it is.
What UIS does set
db-uri, db-schemas, db-anon-role, db-pool, server-cors-allowed-origins, the admin server port, and the error-file plumbing. Everything else is left at PostgREST's default, and a default that consumers have built on is a contract whether or not anyone wrote it down.
PostgREST reads configuration from three places, and this page can only speak for the first:
| source | where to look |
|---|---|
| the pod spec | kubectl get deploy <app>-postgrest -n postgrest -o yaml |
| the running process | its env, which a rolled-out change may not yet match |
| the database | pg_roles.rolconfig and pg_db_role_setting, keys under pgrst.* |
🔴 The third is the one that gets missed. A setting can live in the database and override what any manifest says, and nothing in this repository would show it. On 2026-09-20 a chain of reasoning concluded "unset in the manifest, therefore default" — the conclusion was right, and the step was not. Both database sources happened to be empty, which is why it held.
PostgREST's own log says when it cannot read them: Failed to query database settings for the config parameters.
SELECT rolname, rolconfig FROM pg_roles WHERE rolconfig IS NOT NULL;
SELECT * FROM pg_db_role_setting;
postgrest --version needs kubectl debug --target sharing the PID namespace — the image has no shell, and the admin server serves /live, /ready and /metrics but not /config.
⚠️ And PostgREST is deployed per application: the Deployment is <app>-postgrest, not postgrest. kubectl -n postgrest get deploy postgrest returns NotFound, which reads as "PostgREST is not deployed" — a worse answer than no answer. List them instead:
kubectl get deploy -n postgrest
⚠️ An application cannot change any of this. A template-info.yaml postgrest: block carries schemas and url_prefix and nothing else — no environment or config passthrough — so these settings are a UIS-operator decision, not an application one. An application that needs different behaviour has to ask for it here.
Embedded resources require real FK constraints
The ?select=*,kommune(*) embed pattern relies on PostgREST reading pg_constraint for actual FOREIGN KEY constraints on the underlying tables. PostgREST's @source and @references comment hints are navigation aids that point at existing FK metadata — they don't synthesise it. Wrapper views over fact-style tables (e.g. dbt-built marts, where relationships: tests are SQL assertions, not DDL) typically lack FK constraints, so embeds won't work out of the box. Three workarounds, in order of decreasing effort to maintain:
- Add
FOREIGN KEYconstraints to the underlying tables. In dbt-postgres:+constraints_enabled: true(see dbt-postgres constraints docs). Pure DDL, works with PostgREST's standard discovery — but flipping the flag is rarely a quick win in practice: expect non-trivial side effects on build ordering, fail-on-violation semantics, and compatibility with views that filter byis_activeor similar soft-delete columns. - Define computed relationships — SQL functions returning
SETOF <related_type>that PostgREST recognises as relations. Significant boilerplate per relationship; useful when FK constraints are infeasible. - Skip embeds; consumers do two queries. The right call when relationships are few and clients can afford the round trip. Atlas's v1 API takes this path — the
mart_*views are designed as fat rows (joined columns inline) so external consumers don't need embeds.
If you're unsure, start without embeds and add them later if external demand surfaces.
Column descriptions don't propagate to wrapper views
COMMENT ON COLUMN marts.dim_kommune.name IS '…' is not visible on api_v1.kommune defined as CREATE VIEW api_v1.kommune AS SELECT … FROM marts.dim_kommune. PostgREST projects empty description fields in the OpenAPI spec for view columns unless the consumer explicitly emits COMMENT ON COLUMN api_v1.kommune.name IS '…' per column. If your build pipeline already has descriptions in the underlying-table layer (e.g. dbt's target/manifest.json), have the migration generator re-emit them on the view.
Example: Atlas open-data API
Atlas (atlas.helpers.no) publishes Norwegian public-sector and NGO supply data via PostgREST as the first consuming application of this service. Atlas is a worked-out, production-shaped example of every concept this page describes — api_v1 schema as the public contract, role-pair anonymous access, generated views, Swagger 2.0 spec — verified end-to-end against rancher-desktop on 2026-04-30 (see Atlas's PostgREST API contributor docs).
The api_v1 surface
Nine wrapper views, one per marts.mart_* model in Atlas's curated models/marts/api/ directory. Each is auto-generated from dbt's target/manifest.json rather than hand-written, so column descriptions and view definitions stay in sync with the underlying dbt model. The full list, returned by PostgREST's own GET / introspection:
| Endpoint | What it serves |
|---|---|
/indicator_summary | One row per (source, contents_code) — coverage, latest year, min/max, upstream timestamp. The "what indicators exist and how complete are they" surface. |
/indicator_latest_values | One row per (kommune, indicator, contents_code) at the latest year — the wide-table surface for kommune-level dashboards. |
/indicator_missing_kommuner | Per-indicator gap report: which kommuner have null values at the latest year. |
/coverage_gap_barnefattigdom | The "child poverty per kommune" cut, ordered for journalist-style "worst-N" queries. |
/distrikt_summary | Kommune-level NGO presence summary (chapter counts by NGO). |
/ngo_index | One row per NGO — chapter counts, geographic spread. |
/ngo_overview | Per-NGO breakdown by chapter level (national/regional/local) + activity + kommune coverage. |
/activity_catalog | One row per service-category-tagged activity across all NGOs. |
/kommune_local_chapters | One row per (kommune, NGO chapter) for chapter-level joins. |
Application-side: how api_v1 is built
In Atlas's data repository, the api_v1.* views are produced by a generator that reads dbt's target/manifest.json after dbt run finishes, then emits one CREATE OR REPLACE VIEW api_v1.<name> per mart_<name> model in the curated set, plus a COMMENT ON COLUMN per column (descriptions sourced from schema.yml, propagated by dbt-osmosis). The generator runs at PR time as part of regenerate-api-v1.sh; the SQL file is checked in. Apply happens after dbt run on a fresh database via apply-api-v1.sh. Five validation gates (drift, coverage, static and runtime description coverage, row-count parity vs the underlying mart) keep the wrapper layer honest.
The pattern is concrete and reproducible — see PLAN-004 for the full design and rationale, and api-v1.md for the contributor-facing workflow. Hand-writing wrapper views is also fine for smaller surfaces; Atlas just outgrew it once views started repeating shape.
Atlas does not create the atlas_web_anon or atlas_authenticator roles or grant privileges — ./uis configure postgrest does that.
Platform-side: configure and deploy
./uis configure postgresql --app atlas --database atlas_db --json
# (Atlas's data pipeline runs against atlas_db here — migrations, ingest, dbt, apply-api-v1.sh)
./uis configure postgrest --app atlas \
--database atlas_db \
--schemas api_v1,marts,raw \
--url-prefix api-atlas
./uis deploy postgrest --app atlas
Querying the API — three real access patterns
# 1. List all source/contents combinations, ordered by latest year
$ curl -sS 'http://api-atlas.localhost/indicator_summary?order=latest_year.desc&limit=2'
[{"source_id":"fhi-bor-alene","contents_code":"SMR","contents_label":"Standardisert rate (100 = nasjonalt snitt)",
"latest_year":2025,"kommuner_with_value":357,"kommuner_with_null":0,
"min_value":58.88,"max_value":142.27,"upstream_updated":"2026-04-30T06:22:21.532+00:00"},
{"source_id":"fhi-bor-alene","contents_code":"RATE","contents_label":"Andel (prosent)",
"latest_year":2025,"kommuner_with_value":357,"kommuner_with_null":0,
"min_value":14.78,"max_value":35.71,"upstream_updated":"2026-04-30T06:22:21.532+00:00"}]
# 2. Filter by source — what does SSB 08764 (poverty rates) cover?
$ curl -sS 'http://api-atlas.localhost/indicator_summary?source_id=eq.ssb-08764&limit=2'
[{"source_id":"ssb-08764","contents_code":"EUskala50","contents_label":"EU-skala 50 prosent",
"latest_year":2024,"kommuner_with_value":357,"kommuner_with_null":1,
"min_value":0,"max_value":20.8,"upstream_updated":"2026-04-30T06:19:23.61+00:00"},
{"source_id":"ssb-08764","contents_code":"EUskala60","contents_label":"EU-skala 60 prosent",
"latest_year":2024,"kommuner_with_value":357,"kommuner_with_null":1,
"min_value":4.6,"max_value":28.6,"upstream_updated":"2026-04-30T06:19:23.61+00:00"}]
# 3. Top-3 kommuner by child poverty rate (the "worst kommuner" journalist query)
$ curl -sS 'http://api-atlas.localhost/coverage_gap_barnefattigdom?order=value_pct.desc&limit=3'
[{"kommune_nr":"9999","kommune_name":"Uoppgitt","fylke_name":"Uoppgitt","year":2024,
"value_pct":null,"personer":null},
{"kommune_nr":"5630","kommune_name":"Berlevåg","fylke_name":"Finnmark","year":2024,
"value_pct":28.6,"personer":119},
{"kommune_nr":"3419","kommune_name":"Våler (Innlandet)","fylke_name":"Innlandet","year":2024,
"value_pct":28.2,"personer":525}]
PostgREST's filter / order / limit operators handle this without any application-side code — the views are the contract, the operators are the API.
What doesn't work in v1: FK embeds
Atlas's api_v1.* does not support PostgREST's embedded-resource pattern (?select=*,kommune(*)) in v1. The reason is generic and covered by the Embedded resources require real FK constraints subsection above: Atlas's marts.* lacks Postgres FOREIGN KEY constraints because dbt's relationships: tests are SQL assertions rather than DDL, and PostgREST reads pg_constraint not dbt's manifest. Atlas's PLAN-004 [Q10] resolved this as (c) skip embeds in v1 — mart_* views are designed as fat rows (joined columns inline), so external consumers don't need embeds for kommune/fylke names, NGO names, etc. Revisit later via dbt-postgres +constraints_enabled: true or computed relationships if external demand surfaces.
Undeploy
# Remove K8s objects, keep Postgres roles and Secret (re-deploy works without re-configure)
./uis undeploy postgrest --app atlas
# Full teardown: drop roles, remove Secret
./uis configure postgrest --app atlas --purge
Troubleshooting
🔴 A query got fast on the second run, or two people measured it differently
If you are timing the API through its public hostname, you are probably timing Cloudflare.
The Cache Rule that makes the API fast is configured to ignore cache-control, so a repeat request is served from the edge in tens of milliseconds whatever the database is doing. ⚠️ And the response still says cache-control: no-store — that is Cloudflare telling the browser not to store it, not evidence that nothing was cached. It looks exactly like proof that you got a fresh response.
🔵 This has already cost the fleet an hour: two agents reported 103 s and 18 s for the same query, each "confirmed" by a fast repeat that was the CDN. With the cache busted they agreed to within 3%.
Vary the query string and check that you missed:
curl -s -D - -o /dev/null "https://api-<name>.<your-domain>/<view>?limit=$RANDOM" \
| grep -i cf-cache-status
# want MISS or DYNAMIC — a HIT means you measured the edge
⚠️ Vary a parameter PostgREST recognises — limit, offset, select. An invented name like ?cachebust= or the common ?_= idiom is parsed as a column filter, not ignored:
{"code":"PGRST100","message":"failed to parse filter ..."}
🔵 That is a 400 from a healthy endpoint, and it reads as a broken API rather than a bad cache-buster.
Or measure the origin directly, with Cloudflare out of the path entirely:
kubectl -n <namespace> exec deploy/<app>-postgrest -- \
wget -O /dev/null "http://localhost:3000/<view>?limit=1"
See the Cache Rule for what the rule sets and why.
PostgREST returns 404 for a view I just added
PostgREST caches the schema at startup. After adding a view to api_v1, signal a reload:
NOTIFY pgrst, 'reload schema';
Or restart the pods: kubectl rollout restart deployment/<app>-postgrest -n postgrest.
PostgREST returns 401 unauthorized for an anonymous request
The <app>_authenticator role lacks permission to switch to <app>_web_anon. ./uis configure postgrest --app <name> grants this automatically; if you see this error after a clean configure, run ./uis configure postgrest --app <name> --rotate to recreate the role pair, or check that the GRANT statement was not rolled back manually.
./uis configure postgrest exits unexpectedly or behaves oddly
Pull the latest UIS image and try again:
./uis pull
./uis pull updates the uis-provision-host container to the latest published ghcr.io/helpers-no/uis-provision-host:latest and restarts it. Older images may carry handler bugs that have already been fixed on main but haven't been picked up locally yet. Re-run the failing command after the pull completes.
./uis configure postgrest --app <name> --purge errors with "FATAL: database does not exist"
Pass --database <app>_db explicitly:
./uis configure postgrest --app atlas --database atlas_db --purge
Without --database, the purge path falls back to <app> as the database name (e.g. atlas, not atlas_db) and the underlying psql -d <app> connection fails. Tracked as a UX nit; the explicit---database form is correct and matches how you'd run any other configure invocation.
./uis configure postgrest errors with "Database '<name>' does not exist"
The configure precheck found no database named <name> in the cluster's PostgreSQL. This is the precheck working as intended — the message points at the missing prerequisite. Run step 0 first:
./uis configure postgresql --app <name> --database <name>_db --json
…then run your application's data pipeline against the new database so api_v1.* is populated, then re-run ./uis configure postgrest.
Out of scope
- The
api_v1schema and view definitions — application-side work, owned by the consumer's migrations. - pg_graphql for GraphQL endpoints — separate future investigation (
INVESTIGATE-pg-graphql.md). - JWT authentication and per-user RLS policies — deferred until a real authenticated-endpoint requirement appears.