Skip to main content

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's connection: 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
flapi.yaml
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:

  • properties is 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 of flapi.yaml.
  • init is DuckDB SQL that runs once, at startup, before the server takes requests. Use it to load extensions, create secrets and ATTACH databases. It is not a template: {{ conn.path }} in init stays 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 under connections: fails validation (Connection 'x' not found in configuration).
sqls/customers.yaml
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]
sqls/customers.sql
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:

sqls/products.sql
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 init is not rewritten. './data/northwind.sqlite' is resolved by DuckDB against the server's working directory, not the directory of flapi.yaml. Use an absolute path in production. A SQLite file that is not there does not stop startup: the first request fails with Unable to open database "./data/northwind.sqlite" in the log.
  • One query at a time. A connection whose init attaches 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: false turns 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:

sqls/order-customers.yaml
url-path: /order-customers
template-source: order-customers.sql
connection: [orders, northwind] # conn.path is the orders glob
sqls/order-customers.sql
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 SECRET keeps the credentials in memory for this process. Do not write CREATE 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_ONLY cannot stop a template that uses postgres_query to run arbitrary SQL with the role's rights.
  • READ_ONLY in the ATTACH, so no template can write through the attachment.
  • TLS. Postgres reads libpq's environment, so PGSSLMODE=require (or verify-full with PGSSLROOTCERT) applies to the attachment; for MySQL see the ssl_mode options of DuckDB's mysql extension.
  • Absolute paths in init for files (SQLite, DuckDB, certificates).
  • Credentials only through {{env.NAME}}, never written into the YAML, and never in a PERSISTENT secret.
  • One process per trust boundary: a tenant that must not see another tenant's data gets its own flAPI.

Sources with a dedicated guide​

SourceExtensionStatus with flAPI v26.11.25 (DuckDB 2.0.1)
Parquet, CSV, JSON filesbuilt in (parquet, json), httpfs for bucketsworks
PostgreSQL and MySQLpostgres (default), mysql (core)works
BigQuerybigquery (community)installs; pre-installed only in the -runtime Docker image
Snowflakesnowflake (community) + ADBC driverinstalls; needs the ADBC Snowflake driver on the host
ODBC (Oracle, DB2, Teradata, ...)odbc (core) + the vendor's ODBC driverinstalls
SAP ERP and SAP BWerpl (own repository, unsigned; brings the SAP RFC libraries)installs; not run against an SAP system here
Vector Searchvss (core)works
Google Sheetsgsheets (community)not published for DuckDB 2.0.1
Power BIpbix (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 queryCache
Source queries per request1, plus a SELECT COUNT(*) for total_count when the page is full (total-count: false drops it)0; one populate run per schedule
Freshnesscurrentas of the last refresh
Source downthat request fails (500)the last snapshot is still served
/healthknows nothing about the source; only stalled (below)starting while the first build runs, degraded when it failed or is stale
SourceUsually
Local Parquet/CSV/JSON, SQLite, DuckDB filelive
Postgres / MySQL near the server, with indexeslive; 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 ERPLcache
Files in object storagelive 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 500 whose request_id leads 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 makes GET /health answer 503 with "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 by init, 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 properties value starting with ./ or ../ resolves against the directory of flapi.yaml. A path inside init SQL is DuckDB's and resolves against the server's working directory. Start flAPI from another directory and an init path breaks while a property does not.
  • {{ conn.x }} in init. init is not rendered with the connection's properties; the braces reach DuckDB as text.
  • conn.* of the second connection. Only the first connection in connection: feeds conn.*.
  • {{ conn.path }} with double braces in a template. It HTML-escapes the path (/ becomes &#x2F;). Use {{{ conn.path }}}.
  • LIMIT {{ params.limit }} in a GET template. limit and offset belong to pagination; see SQL Templating.
  • CREATE PERSISTENT SECRET. It writes the password to ~/.duckdb/stored_secrets. Use CREATE SECRET.

Next steps​

The upstream guide is docs/guides/data-sources.md; the reference is CONFIG_REFERENCE § 2.3 Connections.

🍪 Cookie Settings