Connecting Data Sources
flAPI has no database drivers of its own. It embeds DuckDB 2.0.1, and DuckDB and its extensions (plug-ins that add file formats and database connectors) do the reading. A connection is a name plus two optional parts: properties your templates can read, and init SQL that sets DuckDB up at startup.
This page covers what every source has in common. The pages in this section cover one source each.
What one process means
Every connection of a flAPI process lives in one DuckDB instance. That has consequences before you write any YAML:
- One pool of resources. All sources share DuckDB's memory limit and worker threads (
duckdb.max_memory,duckdb.threads), and all requests share flAPI's request handler threads (max(CPU cores, 8), at most 64, not configurable). A heavy query on one source slows the others. - No isolation between connections. Every template can read every attached database and every file the process can reach, and use every secret (a DuckDB object holding credentials, created with
CREATE SECRET). An endpoint'sconnection:list is not an access boundary. - Separate credentials mean separate processes. If two teams or tenants must not see each other's data, run one flAPI per team, each with its own config and credentials.
How a connection works
The runnable examples read two sample files from the flAPI repository. Put them in a data/ directory next to your flapi.yaml, and run every command from that directory:
mkdir -p data sqls
curl -L -o data/customers.parquet https://github.com/DataZooDE/flapi/raw/main/examples/data/customers.parquet
curl -L -o data/northwind.sqlite https://github.com/DataZooDE/flapi/raw/main/examples/data/northwind.sqlite
project-name: sources-demo
template:
path: ./sqls
connections:
customers: # the name endpoints refer to
properties: # strings, available in templates as conn.*
path: ./data/customers.parquet # ./ and ../ resolve against this file's directory
northwind:
init: | # DuckDB SQL, run once at startup
INSTALL sqlite;
LOAD sqlite;
ATTACH IF NOT EXISTS './data/northwind.sqlite' AS nw (TYPE sqlite, READ_ONLY);
The parts:
propertiesis a map of strings. A template sees the properties of its endpoint's connection as{{{ conn.<key> }}}. A value that starts with./or../is turned into an absolute path under the directory offlapi.yaml.initis DuckDB SQL that runs once, at startup, before the server takes requests. Use it to load extensions, create secrets andATTACHdatabases. It is not a template:{{ conn.path }}ininitstays literal text.{{env.NAME}}does work, because it is substituted in the whole YAML file (Credentials).- An endpoint names its connection in
connection: [name]. A name that is not underconnections:fails validation (Connection 'x' not found in configuration).
url-path: /customers
request:
- field-name: segment
field-in: query
required: false
validators:
- type: enum
allowedValues: [AUTOMOBILE, BUILDING, FURNITURE, HOUSEHOLD, MACHINERY]
template-source: customers.sql
connection: [customers]
SELECT c_custkey, c_name, c_mktsegment
FROM read_parquet('{{{ conn.path }}}')
WHERE 1=1
{{#params.segment}}
AND c_mktsegment = '{{{ params.segment }}}'
{{/params.segment}}
ORDER BY c_custkey
Start the server with flapi -c flapi.yaml, then in a second terminal:
curl 'http://localhost:8080/customers?segment=BUILDING&limit=2'
{"data":[{"c_custkey":1,"c_name":"Customer#000000001","c_mktsegment":"BUILDING"},
{"c_custkey":8,"c_name":"Customer#000000008","c_mktsegment":"BUILDING"}],
"next":"/customers?offset=2&limit=2&segment=BUILDING","total_count":337}
A statement in init that fails stops startup and names the connection. With ATACH mistyped for ATTACH:
[error] Database initialization error: Error creating database, Details: connection 'northwind' init: Failed to parse init statements: Parser Error: syntax error at or near <redacted>
[error] flAPI cannot start until the database can be opened.
Literals in the message are redacted, because an init often carries credentials. A statement that parses but fails names its position: Failed to execute init statement 3 of 4: ....
Local files and globs
A file needs no init: put its path in properties and read it with read_parquet, read_csv or read_json, all built into flAPI. A glob (*, **) reads many files as one table, and filename = true adds a column naming the file each row came from:
connections:
orders:
properties:
path: ./files/orders/*.csv # a glob: every month's file
SELECT order_id, customer_id, order_date, amount,
regexp_extract(filename, '([0-9]{4}-[0-9]{2})\.csv$', 1) AS month
FROM read_csv('{{{ conn.path }}}', header = true, filename = true)
ORDER BY order_id
For Hive-partitioned Parquet (./data/events/year=*/month=*/*.parquet), DuckDB turns the directory names into columns, and a filter on them skips whole directories. Files in a bucket (s3://, gs://, az://) or behind https:// are read the same way once credentials are in place; see Cloud Storage. More in Parquet Files.
SQLite
SQLite is attached in init, as the northwind connection above does:
SELECT p.ProductID, p.ProductName, c.CategoryName, p.UnitPrice
FROM nw.Products p
JOIN nw.Categories c ON c.CategoryID = p.CategoryID
WHERE 1=1
{{#params.category_id}}
AND p.CategoryID = {{ params.category_id }}
{{/params.category_id}}
ORDER BY p.ProductID
Two things to know:
- A path inside
initis not rewritten.'./data/northwind.sqlite'is resolved by DuckDB against the server's working directory, not the directory offlapi.yaml. Use an absolute path in production. A SQLite file that is not there does not stop startup: the first request fails withUnable to open database "./data/northwind.sqlite"in the log. - One query at a time. A connection whose
initattaches SQLite is serialised: flAPI runs only one query on it at a time, because a read and a write at the same moment can deadlock a SQLite attachment. Other connections still run in parallel.serialize-access: falseturns it off.
A DuckDB file is attached the same way (ATTACH '/srv/data/warehouse.duckdb' AS wh (READ_ONLY)), but the server then holds its lock for as long as it runs, so no other process can write it.
sqlite and mysql are DuckDB core extensions, not community ones: plain INSTALL sqlite; and INSTALL mysql; fetch them.
Several connections in one template
A template can read everything the process has (What one process means). connection: decides two things only:
conn.*comes from the first connection in the list.- Every listed connection that is serialised takes its lock for the query.
So list every connection the template reads, and put the one whose conn.* you use first:
url-path: /order-customers
template-source: order-customers.sql
connection: [orders, northwind] # conn.path is the orders glob
SELECT o.order_id, o.amount, c.CompanyName, c.Country
FROM read_csv('{{{ conn.path }}}', header = true) o
JOIN nw.Customers c ON c.CustomerID = o.customer_id
ORDER BY o.order_id
A template cannot reach the conn.* of a second connection. For a second file, either write its path into the template, or give that connection an init that creates a view (CREATE OR REPLACE VIEW customers AS SELECT * FROM read_parquet('/srv/data/customers.parquet')) and query the view.
Credentials come from the environment
Write {{env.NAME}} anywhere in the YAML, including inside init, and list the variable in template.environment-whitelist (regular expressions, matched against the whole name):
template:
path: ./sqls
environment-whitelist:
- '^PG_(HOST|USER|PASSWORD)$'
- '^MYSQL_(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);
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);
- Only
{{env.NAME}}works.${PG_PASSWORD}is not substituted and not warned about: it stays the literal text${PG_PASSWORD}. - A variable the whitelist does not match stops startup, with
environment variable PG_PASSWORD referenced as {{env.NAME}} but not whitelisted. An empty or missing whitelist allows none. - Use temporary secrets.
CREATE SECRETkeeps the credentials in memory for this process. Do not writeCREATE PERSISTENT SECRET: it stores the secret unencrypted in~/.duckdb/stored_secrets, and every DuckDB-based process of that user, every flAPI included, loads it at startup.
Postgres and MySQL details are in PostgreSQL.
Production checklist for a database source
- A read-only role on the database side, granted only the tables you serve. flAPI's
READ_ONLYcannot stop a template that usespostgres_queryto run arbitrary SQL with the role's rights. READ_ONLYin theATTACH, so no template can write through the attachment.- TLS. Postgres reads libpq's environment, so
PGSSLMODE=require(orverify-fullwithPGSSLROOTCERT) applies to the attachment; for MySQL see thessl_modeoptions of DuckDB's mysql extension. - Absolute paths in
initfor files (SQLite, DuckDB, certificates). - Credentials only through
{{env.NAME}}, never written into the YAML, and never in aPERSISTENTsecret. - One process per trust boundary: a tenant that must not see another tenant's data gets its own flAPI.
Sources with a dedicated guide
| Source | Extension | Status with flAPI v26.11.25 (DuckDB 2.0.1) |
|---|---|---|
| Parquet, CSV, JSON files | built in (parquet, json), httpfs for buckets | works |
| PostgreSQL and MySQL | postgres (default), mysql (core) | works |
| BigQuery | bigquery (community) | installs; pre-installed only in the -runtime Docker image |
| Snowflake | snowflake (community) + ADBC driver | installs; needs the ADBC Snowflake driver on the host |
| ODBC (Oracle, DB2, Teradata, ...) | odbc (core) + the vendor's ODBC driver | installs |
| SAP ERP and SAP BW | erpl (own repository, unsigned; brings the SAP RFC libraries) | installs; not run against an SAP system here |
| Vector Search | vss (core) | works |
| Google Sheets | gsheets (community) | not published for DuckDB 2.0.1 |
| Power BI | pbix (community) | not published for DuckDB 2.0.1 |
Iceberg and Delta tables (iceberg_scan, delta_scan) are DuckDB core extensions too: INSTALL iceberg; LOAD iceberg; in an init, then SELECT * FROM iceberg_scan('{{{ conn.orders }}}'). MotherDuck and Unity Catalog (uc_catalog) extensions install for DuckDB 2.0.1 but are untested with flAPI.
Extensions
At startup flAPI loads duckdb.default-extensions, which is [httpfs, ducklake, fts, json, postgres, sqlite, parquet] unless you set it. Setting it replaces the list. DuckDB autoloads only its own core extensions (iceberg, delta, mysql, ...); community extensions (bigquery, snowflake) and erpl always need an explicit INSTALL and LOAD in an init.
flapi extensions install --config flapi.yaml --dir ./extensions pre-installs everything a config needs, for hosts without network access. Details, including which extensions ship with each distribution: DuckDB Extensions.
Remote configs and duckdb-hardening
When flapi.yaml is loaded from a bucket or a URL (flapi -c s3://...), templates run with DuckDB's external access restricted: they read only the config's own location, template.path, the DuckLake data-path, attached database files and the allowed-directories you list. init runs before the policy, with full access, so its ATTACHes and secrets keep working, but a template cannot ATTACH, INSTALL, LOAD or CREATE SECRET. An extension only a template uses (iceberg_scan, read_xlsx, ...) must be loaded in an init or listed in duckdb.default-extensions. See Security Hardening.
Live query or cache?
An endpoint without a cache runs its template against the source on every request. With a cache, a scheduled refresh copies the data into a DuckLake table (flAPI's local, snapshot-versioned cache store) and requests read only that table; see Caching.
| Live query | Cache | |
|---|---|---|
| Source queries per request | 1, plus a SELECT COUNT(*) for total_count when the page is full (total-count: false drops it) | 0; one populate run per schedule |
| Freshness | current | as of the last refresh |
| Source down | that request fails (500) | the last snapshot is still served |
/health | knows nothing about the source; only stalled (below) | starting while the first build runs, degraded when it failed or is stale |
| Source | Usually |
|---|---|
| Local Parquet/CSV/JSON, SQLite, DuckDB file | live |
| Postgres / MySQL near the server, with indexes | live; cache if the query is heavy or the database must be protected |
| BigQuery, Snowflake (billed per query or per warehouse minute) | cache: a live paginated endpoint can cost two billed queries per page |
| SAP via ERPL | cache |
| Files in object storage | live for small reads; cache for wide globs |
When a source fails
- At startup, a failing
init(unreachable database, missing extension, bad credentials) stops the server, so an orchestrator sees a crash loop instead of a half-working instance. - After startup, a source that goes away makes each request that touches it fail with a
500whoserequest_idleads to the error in the log; endpoints on other sources keep working. Whether DuckDB's postgres or mysql extension reconnects by itself after the database comes back is not verified; if requests keep failing, restart flAPI. - There is no query timeout. A REST query runs until the source answers.
stall-timeout-s(default 60 s) only makesGET /healthanswer503with"status":"stalled"while a request has been in flight longer than that, so a load balancer stops sending traffic; the query itself keeps running. - Rotating credentials needs a restart. Secrets and
ATTACHes are created byinit, which runs only at startup; a config reload does not re-run it.
How to follow a request_id and read /health: Observability.
Common mistakes
${VAR}is not substituted. flAPI does not support it, and it does not warn. Write{{env.VAR}}and whitelist it.- Relative paths have two bases. A
propertiesvalue starting with./or../resolves against the directory offlapi.yaml. A path insideinitSQL is DuckDB's and resolves against the server's working directory. Start flAPI from another directory and aninitpath breaks while a property does not. {{ conn.x }}ininit.initis not rendered with the connection's properties; the braces reach DuckDB as text.conn.*of the second connection. Only the first connection inconnection:feedsconn.*.{{ conn.path }}with double braces in a template. It HTML-escapes the path (/becomes/). Use{{{ conn.path }}}.LIMIT {{ params.limit }}in a GET template.limitandoffsetbelong to pagination; see SQL Templating.CREATE PERSISTENT SECRET. It writes the password to~/.duckdb/stored_secrets. UseCREATE SECRET.
Next steps
- Parquet Files and PostgreSQL: the two most common sources
- Caching: serve a slow or billed source from DuckLake
- Cloud Storage: S3, GCS, Azure, remote configs
- DuckDB Extensions: what ships, offline hosts, packed binaries
- SQL Templating:
conn.*, bound parameters, pagination
The upstream guide is docs/guides/data-sources.md; the reference is CONFIG_REFERENCE § 2.3 Connections.