How PostgREST exposes a PostgreSQL schema as a REST API
A team with data already in PostgreSQL often needs an HTTP API for applications, partners or internal tools, but writing and maintaining a custom service for every table is slow and error-prone. PostgREST is a standalone web server that turns a PostgreSQL database directly into a RESTful API, with endpoints and operations determined by the database's structural constraints and permissions. It runs beside the database as its own process, so the API layer is defined by the schema rather than by hand-written handler code. The decision that matters most is not the endpoint list but the database itself: the roles, grants and row-level security policies determine what each caller can read and write. This page covers the supported setup method, prerequisites, mapping of tables and views to endpoints, authentication and schema isolation, placing the service behind NGINX, testing, and the failure points that cause the most trouble.
The mapping works in the direction most teams do not expect. Tables and views in the exposed schema become resources, and the HTTP method chosen by the caller is translated into a SQL operation that runs under a database role. A caller with no grant on a table receives no access to it, even if the URL is known, because PostgreSQL enforces the privilege, not PostgREST. Before going further, confirm with your own database owner which schemas, views and functions will be exposed, and review the grants on each one. Views are a common way to limit columns or rows without changing base tables, and functions can implement operations that do not fit simple table verbs. Treat the exposed schema as a published interface that needs review like any other API contract.
Expect the first failures to come from the schema and the roles rather than from the web server. Missing GRANT statements produce permission errors that look like API bugs, and row-level security policies that were written for application logic can silently hide rows from API callers. Plan a test database with representative roles, run requests as each role, and keep the test cases in version control so they survive schema changes. Ask your team to confirm which PostgREST release and PostgreSQL major version they will target, since both affect setup and support, and check the current PostgREST documentation before writing configuration for production.
What you need before PostgREST goes near production
PostgREST is only as safe as the database and network around it. The cards below cover the decisions to settle before the first endpoint is exposed: the PostgreSQL version, the database role PostgREST connects as, where each component sits on the network, how traffic is encrypted, and which identity provider signs the tokens. Confirm each item in your own environment before building.
PostgreSQL version and support window
Pick a major version that is still inside its support window for the whole planned life of the API. The supported versions listed by the PostgreSQL project run to November 2026 for version 14, November 2027 for 15, November 2028 for 16, November 2029 for 17 and November 2030 for 18. Check your choice against the PostgreSQL versioning policy and confirm the exact minor release you will run, since minor releases carry security fixes and do not change the storage format.
Versioning policyDedicated schema and login role
PostgREST should connect with a dedicated login role that has no ownership of tables and no rights beyond what the API needs. Expose only a named API schema, keep application tables in a separate private schema, and map each JWT role to a database role with explicit grants. Confirm that the anonymous role has no access to anything you do not intend to publish.
Network placement of each component
Decide which network segment holds NGINX, PostgREST and PostgreSQL before deployment. A common layout keeps only NGINX reachable from clients, lets PostgREST talk to PostgreSQL on a private segment, and blocks any direct client path to the database port. Write the allowed flows down and confirm them with your network and firewall owners, including health checks and any load balancer in front of NGINX.
TLS certificates at every hop
Plan certificates for the public NGINX endpoint, and decide whether traffic between NGINX and PostgREST, and between PostgREST and PostgreSQL, is also encrypted. Confirm who issues and renews each certificate, which certificate authority your clients trust, and how renewal is tested. The PostgreSQL authentication methods documentation describes certificate-based options if you choose to encrypt the database connection and authenticate with certificates.
Authentication methodsIdentity provider that issues JWTs
Name the identity provider that signs the tokens PostgREST will verify, and confirm how it publishes its signing keys, token lifetime and the claims that carry the database role. Decide who owns the claim mapping and how role changes in the identity provider reach the database grants. Confirm the signing algorithm and key rotation procedure with the team that operates the provider before writing any role mapping.
PostgREST release to pin
Choose the PostgREST release you will deploy and pin it in your build, then read its release notes for changes to configuration keys and authentication behavior. Confirm that the release supports your PostgreSQL major version and that your team has a process for testing a newer release against a copy of the schema before upgrading. Check the current stable documentation for the configuration reference.
PostgREST docsConfiguration sequence from schema to NGINX
This sequence takes a PostgreSQL schema from private tables to a TLS-protected REST API, with each database grant, token rule and proxy route tested against the access model before the next layer is added.
Create the API schema and roles
Create a dedicated schema that holds only the tables, views and functions you intend to expose, keeping it separate from internal application schemas. Create the
anonrole for unauthenticated requests and anauthenticatedrole for signed-in users, both as NOLOGIN roles that PostgREST switches into per request. Also create an authenticator login role with the minimum rights needed to switch into the other two. The step is done when\dulists all three roles and none of them owns application tables.Grant only the required table and function privileges
Grant
USAGEon the API schema and thenSELECT,INSERT,UPDATEorDELETEonly on the specific tables each role needs. GrantEXECUTEon individual functions rather than the whole schema, and revoke the defaultEXECUTEprivilege PostgreSQL gives toPUBLICon functions where it is not wanted. Check the result withinformation_schema.role_table_grantsand the role-specific privilege views, and record what each role can do so the expected results in later checks are written down before testing.Enable row-level security where rows differ by user
For any table where a signed-in user should see only their own rows, enable row-level security with
ALTER TABLE ... ENABLE ROW LEVEL SECURITYand write policies that compare a column to a claim read from the JWT, such ascurrent_setting('request.jwt.claims', true). Confirm the table owner is not the role PostgREST uses, because owners can bypass policies unless forced. The step is complete when a test user sees only their rows and a query that should return nothing does so, which confirms the policy filters rows rather than only the grants.Configure the database connection and JWT settings
Create the PostgREST configuration with the database connection string for the authenticator role, the schema to expose, and the anonymous role name. Set the JWT verification key or secret and the claim that names the database role, using the settings documented in the PostgREST configuration reference. Store the connection string and secret outside the configuration file in your secrets store. Confirm the exact configuration keys against the version you deploy, since names have changed across releases.
Start PostgREST and test with and without a token
Start PostgREST as a service under its own system account, bound to a local interface. Call an exposed endpoint with no
Authorizationheader and confirm it returns only rows granted toanon. Call it again with a valid token whose role claim isauthenticatedand confirm the returned rows match the row policies. Then call a table the role was not granted and confirm the request is denied. Keep these three responses as the baseline for the grant design, because every later change should reproduce them.Place NGINX in front for TLS and routing
Configure NGINX to terminate TLS on the public name, forward only the API path prefix to the local PostgREST port, and pass the
Authorizationheader through unchanged. Add request size and timeout limits that suit your workload, and decide which headers and paths are blocked. Confirm that the public HTTPS endpoint returns the same rows and denials as the local tests, and that plain HTTP does not reach the API. Verify certificate chain and redirect behavior with your normal tooling.Rerun the access checks after each change
Treat the baseline responses from the earlier steps as a regression suite. After any change to grants, policies, JWT settings or NGINX routes, repeat the anonymous, authenticated and denied calls and compare them with the recorded results. Ask your security team to review the grant listing and the token issuer settings before go-live. Ask for a documented procedure for rotating the JWT key, since PostgREST reads it from configuration and a change needs a service restart.
How JWT claims become database roles
PostgREST does not have its own user table. Each request carries a bearer token in the Authorization header, PostgREST verifies the token's signature and claims, reads the role claim (configured through jwt-role-claim-key, which defaults to a role claim), and then runs the query inside a transaction that switches to that database role. PostgreSQL then applies its ordinary grants and row-level policies, so the database decides what the caller can read or write. The token's issuer (iss), audience (aud) and expiry (exp) checks must be set up on the PostgREST side and confirmed against the identity provider you actually use, including the exact issuer string, the audience your provider puts in tokens, and the signing key or JWKS source. Test this with a token from the real provider, not a hand-made one, because a mismatch in any of these fields is the most common reason a valid-looking login returns errors.
Requests without a token run as the anonymous role, set with db-anon-role. Treat that role as a public API: grant it only the tables, views and functions you intend anyone on the internet to read, and nothing that writes. The connection role configured in db-uri should have no direct data rights at all. It exists only to log in and then switch to the anonymous or authenticated role, so it needs NOINHERIT and membership in the roles PostgREST switches to, not table grants of its own. If the connection role owns or can read sensitive tables, a mistake in a grant on a view or function can expose data without any token check failing. Ask the team to demonstrate this by calling each endpoint with no token, with a low-privilege token and with a token for a privileged role, and recording which calls succeed.
Decide early which claims your role mapping depends on, because anyone who can issue tokens with a given role claim gets that role's database rights. Confirm with the identity provider owner who can set that claim, how roles are removed when a person leaves, and how long tokens live. Short expiry limits the damage from a stolen token, but PostgREST does not revoke an unexpired token by itself, so revocation depends on your provider and on keeping lifetimes short. Document the mapping from identity groups to database roles as a controlled list that security and the database owner review together.
Request flow from client through NGINX and PostgREST to PostgreSQL
The request starts at the client on the public network, where NGINX terminates TLS and routes API paths to PostgREST on the internal network. The identity provider issues the JWT, which the client presents as a bearer token. PostgREST verifies the signature and switches to the database role named in the token, so PostgreSQL then applies table grants and row-level security to each query. Check that the trust boundary between the internal network and the database holds, and that PostgREST connects with a low-privilege login role rather than an owner account.
Request path from client through NGINX and PostgREST to PostgreSQL, with trust boundaries marked.
Mapping JWT claims, database roles and API endpoints
This table maps each layer of a PostgREST request, from the token claim to the database role, schema, endpoint, verb and row filter. Read it top to bottom to trace how one authenticated request is allowed or refused. The main takeaway is that PostgREST enforces access inside PostgreSQL, so the grants and row-level security policies are the real access model and must be tested as carefully as the token.
| Layer | What it maps | Design check |
|---|---|---|
| JWT role claim | Token claim (by default role) read by PostgREST and set as the database role for the request | Confirm the claim name and value format with your identity provider before writing any grants |
| Anonymous role | Role used for requests without a valid token, configured as the anonymous role | Grant it only the reads intended for the public, or none at all |
| Authenticator role | Login role PostgREST connects as, which switches to the role named in the claim | Keep it low-privilege and grant it membership only in the roles it must assume |
| Exposed schema | Schema whose tables and functions appear under the API path | Expose a dedicated API schema, not the schema that holds base tables and private data |
| Tables and views | Each table or view in the exposed schema becomes a resource endpoint | Expose views to shape responses and hide internal columns |
| Functions | Stored functions in the exposed schema become RPC endpoints | Review execute privileges and any function that writes data |
| HTTP verbs | GET maps to select, POST to insert, PATCH to update and DELETE to delete, each checked against granted privileges | Grant only the verbs each role needs; a missing grant returns a permission error, not an empty result |
| Row-level security | Policies evaluate against the current role and claims, filtering rows for each request | Test policies with at least two claim values, since a policy that checks the wrong claim leaks rows silently |
Hardening PostgREST and the schema it serves
PostgREST exposes whatever the database role it connects as is allowed to reach, so most of the security work happens in the schema, the grants and the edge in front of it. The cards below cover the database side, the token side and the NGINX edge, and each one names a setting to verify against the PostgREST version you run.
Expose only a dedicated API schema
Create a separate schema, such as api, that holds only the views and functions meant for clients, and point PostgREST at it with db-schemas. Keep base tables in private schemas that the API roles cannot read. This keeps a new table from appearing in the API by accident, because PostgREST builds its endpoints from what is exposed. Check the exposed schema list after every migration.
Grant the minimum to each API role
Give each anonymous or user role only the SELECT, INSERT, UPDATE or DELETE rights its clients need, on specific tables or views, and no ALTER or TRUNCATE rights. Review default privileges so that new objects do not inherit broad access. Write down which role serves which client, because an over-granted role becomes the effective API permission set.
Enforce row access with row-level security
Enable row-level security on every exposed table that holds per-user data, then write policies that compare a row to claims from the JWT, such as a user identifier. Confirm that the table owner does not bypass policies unintentionally, and test each policy with two users to prove that one cannot read the other's rows. Policies are enforced by PostgreSQL, so they apply regardless of which client sends the request.
Keep the login role out of reach
The role in the connection string, set through db-uri, is the login PostgREST uses before it switches roles for each request. Give it no direct grants on API data and set it to NOINHERIT so it cannot quietly gain rights from other roles. Store its password in a secret manager or environment file with restricted file permissions, not in a repository or a container image layer.
Handle the JWT secret and its rotation
PostgREST verifies JWTs with the key in jwt-secret or with a JWKS endpoint, depending on your setup. Keep symmetric secrets out of version control, make them long and random, and plan a rotation that accepts old and new keys for a short overlap. Confirm which claims your version checks, such as expiry, and set short token lifetimes so that a leaked token expires soon. Verify the current key settings in the docs for your release.
Terminate TLS and limit traffic at NGINX
Terminate TLS at NGINX with ssl_protocols and a certificate your clients trust, and keep PostgREST bound to localhost or a private network. Where the network path between NGINX and PostgREST crosses a shared segment, decide whether to encrypt it too, and test the upstream connection. Add limit_req for request rates, client_max_body_size for payload size, and short timeouts. Confirm each directive against your NGINX version.
Log and alert on authentication failures
Log rejected JWTs and 401 or 403 responses at NGINX with the client address, path and time, and forward them to the log platform your security team already reviews. PostgREST logs go to standard output and can be set to a verbosity level, so check what each level records before enabling it in production. Alert on bursts of failures against one path, and test that the alert fires with a deliberate bad token.
Testing the API before users depend on it
Treat the generated API as code that needs tests before any client depends on it. PostgREST derives its endpoints and operations from the database's structure and permissions, so a test suite should verify the database grants and row-level policies directly, then confirm the HTTP layer behaves the same way. Start with grant tests that connect as the anonymous role and as each authenticated role defined in the configuration, and check that every table, view and function they can reach is one they are meant to reach. A request that returns data it should not return is a failed test, even if the endpoint itself works. Run the same checks for write operations such as POST, PATCH and DELETE, because a grant on a view or a missing policy can expose writes that reads never revealed.
Row-level tests need two real users whose rows must stay separate. Create two accounts with distinct JWT subjects, insert rows owned by each, and confirm that each user sees only their own rows through the API and that updates or deletes against the other user's identifiers affect nothing. Add token tests for expired tokens, tokens with the wrong audience and unsigned tokens, and confirm each is rejected before a database role is assumed. Check the JWT secret or key configuration and the role claim mapping as part of this layer, since a misconfigured claim can silently grant the wrong role. Confirm the exact settings and claim names against the PostgREST documentation for the version you run.
Schema changes are the most common way a tested API breaks. Adding a column, renaming a table, changing a view or altering a function can change what the generated API exposes without any application code changing. Make the full test suite a required step in every migration pipeline, and run it against a copy of production-like data before the change reaches shared environments. Keep the grant and row-level tests in version control next to the migrations so that a new table is not exposed by default. Ask your team to define who approves a change to anything in the exposed schema, and to confirm which tests must pass before the PostgREST service reloads its schema cache.
Common PostgREST failures and how to fix them
This table maps the failures teams most often hit when running PostgREST, with the likely cause and the first fix to try for each. Read it by matching the symptom you see to a row, then work through the cause before changing anything else. Most failures trace back to authentication configuration, grants and policies, or the schema cache rather than to the data itself.
| Symptom | Likely cause | First fix to try |
|---|---|---|
| 401 responses on authenticated requests | The JWT secret in PostgREST does not match the secret that signed the token, or the token lacks the role claim PostgREST expects | Compare the configured JWT secret with the signing secret, then decode the token and confirm the role claim names an existing database role |
| Empty result sets from existing tables | No grant exists for the role, or a row-level security policy filters every row for that role, so the data is present but not visible | Check table grants for the request role, then review policies with row-level security enabled and test the same query as that role in psql |
| Endpoint returns 404 for a table that exists | The schema is not listed in the exposed schemas setting, so PostgREST never publishes its objects | Add the schema to the exposed schemas configuration, reload PostgREST, and confirm the table is granted to the anonymous or authenticated role |
| 403 or permission denied for unauthenticated requests | The anonymous role has no privileges, or it has more privileges than intended on sensitive tables | Decide which tables the anonymous role should read, grant only those, and revoke anything else from it |
| New columns or tables missing from the API | The schema cache was built before the change and has not been reloaded | Send a schema cache reload signal to PostgREST or restart the service, then confirm the change appears in the OpenAPI output |
| Authenticated requests work directly but fail through NGINX | NGINX strips or rewrites the Authorization header, or the proxy location routes requests to the wrong upstream path | Pass the Authorization header explicitly in the proxy configuration and test with curl against both the proxy and PostgREST directly |
| Errors appear only for some clients or browsers | CORS headers are missing or the preflight request is blocked by the proxy | Confirm the proxy returns the expected CORS headers for OPTIONS requests and compare them with PostgREST's own settings |
Questions teams ask before exposing PostgreSQL as an API
How much effort does a PostgREST build take, and what drives it?
Effort depends mostly on how many tables and views you expose, how complex your authentication model is, how many row-level rules must be expressed in the database, and how much identity integration is needed. A small read-only schema with one identity provider is a very different job from a multi-tenant schema with per-role row filters and several token issuers. PostgREST itself is a single web server, so the work sits in schema design, grants, policies and testing. Ask any partner to break the quote down by these drivers rather than by a single lump sum, and confirm how many environments the scope covers.
Can our internal team build this without a partner?
A team with solid PostgreSQL experience can build a PostgREST API alone, provided it has people who can design roles and grants, configure a JWT issuer, write and test row-level security policies, and operate NGINX as a reverse proxy. The risky gaps are usually security-side: getting the mapping from token claims to database roles wrong, or granting more than the API needs. Before deciding, check whether you have someone who can review grants and run negative tests against each role. If one of those skills is missing, a fixed-scope engagement can cover that part while your team keeps ownership.
What do we need to provide for the work to go smoothly?
The work needs several inputs from your side:
- Schema owners who can confirm which tables, views and functions should be exposed and what each column means.
- Access to your identity provider so tokens can be issued and checked, along with the claims that map users to roles.
- Non-production and production environments, or at least a staging copy that matches production's schema.
- A named approver who signs off on the grant matrix before anything reaches production.
- Network and certificate decisions for putting NGINX in front of the API.
Missing any of these usually shows up as delay later in the project, so confirm them in the written scope.
How long does it take to expose a schema through PostgREST?
Duration is set by the same drivers as effort: the number of exposed objects, the complexity of roles and row-level rules, the identity integration, and how many environments must be promoted. This page does not give a timeline because no researched figure supports one for your environment. Ask a partner to state the phases, the decisions needed from your team in each phase, and what depends on your identity provider or change approvals. A timeline that does not name those dependencies is not a plan you can check.
Does PostgREST replace application code for business logic?
No. PostgREST covers the data access layer well: it derives endpoints and operations from the database's structure and permissions. Complex workflows, calls to external systems, file handling and multi-step transactions usually still belong in application code or in database functions that you design and test deliberately. Expect some logic to live in the database, which changes how it is versioned, reviewed and deployed. Decide early which rules belong in grants and row-level policies, which belong in stored functions, and which stay in services.
What should we ask a partner for in a fixed-scope quote?
A fixed-scope quote should state the following in writing:
- The exact list of tables, views and functions in scope, and what is excluded.
- The authentication design, including the identity provider, token claims and the role each claim maps to.
- The grant matrix and row-level policies to be delivered, and who approves them.
- The NGINX configuration, TLS approach and environments covered.
- Testing performed, including negative tests for each role, and the handover documents.
- What is one-time (build, review, handover) and what recurs (upgrades, patching, support), if you want ongoing help.
Ask for assumptions and change-request rules too, since they determine what happens when the schema grows.
What security risks should we check before exposing the database?
The main risks are over-broad grants, unsafe role mapping from JWT claims, missing row-level policies on sensitive tables, and API endpoints that reveal schema details to unauthenticated callers. Confirm that the anonymous role has no more access than you intend, that each token claim is validated by the issuer before it is trusted, and that schema isolation keeps internal tables out of the exposed schema. Testing each role against an expected deny list is the quickest way to find gaps. For regulated data, also confirm how request logs are kept and who can read them.
How DeployOpen works on this
DeployOpen plans, implements, hardens, documents and supports self-hosted open-source platforms inside your own infrastructure. For a PostgREST integration, that means agreeing the exposed schema, roles, authentication and proxy setup in writing first, then building and testing them in your environment so your security and database teams can review the result.
How we scope
- We list the schemas, tables, views and functions that will be exposed as endpoints, and those that stay private.
- We agree how JWT claims map to PostgreSQL roles, and which identity provider issues the tokens.
- Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts.
How we build
- We create the anonymous and authenticated roles with least-privilege grants, and set up row-level rules where the data needs them.
- We configure the PostgREST service, its database connection and NGINX in front of it within your infrastructure.
- We test endpoints with both valid and invalid tokens and confirm that denied requests never reach the data.
How we hand over
- You receive the schema-to-endpoint map, role and grant definitions, and the PostgREST and NGINX configuration as files.
- We document how to add a table or function to the API, and how the review of grants is repeated after schema changes.
- We walk your database and platform engineers through the deployment and the test results so they can run it themselves.
How we support
- Ongoing support, upgrades and continuous testing are available as retainers, covering PostgREST and PostgreSQL version changes.
- Retainer work can include retesting access controls after new schemas, functions or roles are added to the API.
- We confirm the upgrade notes for each PostgREST release against your environment before you apply it.

