Skip to main content

Connecting to PostgreSQL

flAPI reads PostgreSQL through DuckDB's postgres extension, which is in flAPI's default extension set. You attach the database once, at startup, and query its tables like local ones. DuckDB pushes filters and column lists down to the server.

MySQL works the same way with the mysql core extension; see MySQL below.

Setup​

Credentials come from environment variables. Write {{env.NAME}} in the YAML, including inside init, and whitelist the names:

flapi.yaml
project-name: shop-api
template:
path: ./sqls
environment-whitelist:
- '^PG_(HOST|USER|PASSWORD)$'
connections:
shop:
init: |
INSTALL postgres;
LOAD postgres;
CREATE OR REPLACE SECRET pg_shop (TYPE postgres, HOST '{{env.PG_HOST}}', PORT 5432,
DATABASE 'shop', USER '{{env.PG_USER}}', PASSWORD '{{env.PG_PASSWORD}}');
ATTACH '' AS pg (TYPE postgres, SECRET pg_shop, READ_ONLY);
export PG_HOST=db.internal PG_USER=flapi_reader PG_PASSWORD='...'
flapi -c flapi.yaml

What happens:

  • init runs once, at startup. The ATTACH connects right away, so a database that cannot be reached stops the server instead of failing later.
  • CREATE SECRET (without PERSISTENT) keeps the credentials in this process's memory. Do not write CREATE PERSISTENT SECRET: it stores the password unencrypted in ~/.duckdb/stored_secrets, where every DuckDB-based process of that user loads it.
  • init is not rendered as a template: {{ conn.host }} inside it would reach DuckDB as literal text. Only {{env.NAME}} is substituted there, because it is substituted in the whole YAML file.
  • Only {{env.NAME}} works. ${PG_PASSWORD} stays the literal text ${PG_PASSWORD}. A variable the whitelist does not match stops startup.

Query an attached table​

sqls/orders.yaml
url-path: /orders
request:
- field-name: customer_id
field-in: query
required: true
validators:
- type: int
min: 1
- field-name: status
field-in: query
required: false
validators:
- type: enum
allowedValues: [open, shipped, cancelled]
template-source: orders.sql
connection: [shop]
sqls/orders.sql
SELECT order_id, status, total, created_at
FROM pg.public.orders
WHERE customer_id = {{ params.customer_id }}
{{#params.status}}
AND status = '{{{ params.status }}}'
{{/params.status}}
ORDER BY created_at DESC
  • customer_id is outside any section and has an int validator, so it is bound as a prepared-statement parameter.
  • status is inside a section, so it is pasted as text; the enum validator is what keeps it safe.
  • No LIMIT: GET endpoints are paginated by default, and ?limit= / ?offset= are reserved for the pagination.

flAPI has nine validator types: int, number, boolean, date, time, string, email, uuid and enum. A boolean filter is a boolean validator, not an enum of strings. See Validation.

To run SQL on the server side as written, use postgres_query('pg', 'SELECT ...'). It runs with the role's full rights, regardless of READ_ONLY.

With caching​

For heavy queries, or a database you must protect from API traffic, serve the endpoint from a DuckLake cache. A full refresh rebuilds the table each time:

sqls/orders.yaml (cache block)
cache:
enabled: true
table: orders_cache
schedule: 15m
template-file: orders_cache.sql
sqls/orders_cache.sql
CREATE OR REPLACE TABLE {{cache.catalog}}.{{cache.schema}}.{{cache.table}} AS
SELECT order_id, customer_id, status, total, created_at
FROM pg.public.orders

The serving template then reads {{cache.catalog}}.{{cache.schema}}.{{cache.table}} instead of pg.public.orders. For incremental refreshes (a cursor, with a first-run bootstrap) see Caching.

MySQL​

mysql is a DuckDB core extension, not a community one. It is not in flAPI's default set, so the INSTALL downloads it on first start (pre-install it for offline hosts with flapi extensions install):

template:
path: ./sqls
environment-whitelist:
- '^MYSQL_(HOST|USER|PASSWORD)$'
connections:
crm:
init: |
INSTALL mysql;
LOAD mysql;
CREATE OR REPLACE SECRET my_crm (TYPE mysql, HOST '{{env.MYSQL_HOST}}', PORT 3306,
DATABASE 'crm', USER '{{env.MYSQL_USER}}', PASSWORD '{{env.MYSQL_PASSWORD}}');
ATTACH '' AS crm (TYPE mysql, SECRET my_crm, READ_ONLY);

Tables are then crm.<table>, and mysql_query('crm', 'SELECT ...') runs SQL on the server as written.

Production checklist​

  • A read-only database role, granted only the tables you serve. READ_ONLY in the ATTACH stops writes through the attachment, but not a postgres_query call.
  • READ_ONLY in every ATTACH.
  • TLS. The postgres extension uses libpq, so PGSSLMODE=require (or verify-full with PGSSLROOTCERT) in flAPI's environment applies to the attachment.
  • Credentials only through {{env.NAME}}, and only in temporary secrets.
  • Rotating the password needs a restart: secrets and ATTACHes are created by init, which runs only at startup.
  • No query timeout. A slow query runs until the database answers; GET /health reports stalled after stall-timeout-s (default 60 s). Set a statement_timeout on the database role if you need a hard limit.

Next steps​

🍪 Cookie Settings