SQL Templates
Every endpoint has a SQL template: a SQL file with Mustache tags. flAPI validates the request parameters, renders the template and runs it on DuckDB. This page is the short reference; the step-by-step guide with runnable examples is SQL Templating.
Quick example
url-path: /customers
request:
- field-name: segment
field-in: query
validators:
- type: enum
allowedValues: [AUTOMOBILE, BUILDING, FURNITURE, HOUSEHOLD, MACHINERY]
- field-name: min_balance
field-in: query
validators:
- type: number
min: 0
template-source: customers.sql
connection: [customers]
SELECT c_custkey, c_name, c_mktsegment, c_acctbal
FROM read_parquet('{{{ conn.path }}}')
WHERE ({{ params.min_balance }} IS NULL OR c_acctbal >= {{ params.min_balance }})
{{#params.segment}}
AND c_mktsegment = '{{{ params.segment }}}'
{{/params.segment}}
ORDER BY c_custkey
min_balanceis outside any section, so both references are bound as prepared-statement parameters. Absent, it bindsNULLand the filter switches itself off.segmentis inside a section, so it is pasted as text. Theenumvalidator is what keeps it safe.conn.pathis never bound; it is always text, so it uses triple braces.- No
LIMIT: GET endpoints are paginated, and?limit=/?offset=belong to the pagination.
Variables
| Variable | Contains |
|---|---|
params.* | Validated request parameters (query, path, header, body) |
conn.* | The properties of the first connection in the endpoint's connection: list |
auth.* | auth.username, auth.roles (comma-joined), auth.email (only with type: oidc), auth.type, auth.authenticated; empty on an anonymous request |
env.* | Environment variables matching template.environment-whitelist |
cache.* | Cache table names and, in a populate template, watermark and snapshot values |
context.* does not exist: {{{ context.auth.username }}} renders as an empty string.
What is bound and what is text
A params.* reference is bound as a ? parameter when all three hold:
- the field has a typed validator (
int,number,boolean,date,time,string,email,uuid,enum); - the reference is outside every section (
{{#...}}/{{^...}}); - it stands where SQL expects a value (
c = {{ params.x }},c = '{{{ params.x }}}',LIKE '%{{{ params.x }}}%',IN (...)).
Everything else is pasted into the SQL as text, and the validator is the only defence there: references inside a section, names (ORDER BY {{{ params.sort }}}, FROM {{{ params.t }}}), typed literals (DATE '{{{ params.d }}}'), SQL comments, and every conn.*, auth.* and env.* variable.
| Where | Write | Defence |
|---|---|---|
| A value, outside sections | {{ params.x }} bare, or '{{{ params.x }}}' | prepared-statement binding |
| A value, inside a section | {{{ params.x }}} (quoted for strings) | the validator |
| A column or table name | {{{ params.x }}} | an enum or strict regex validator |
conn.*, auth.*, env.* | '{{{ ... }}}', inside single quotes | text, not a bound parameter: for auth.* use only claims the caller cannot edit (your own users:, a token you signed, an identity provider's immutable sub or object id) |
Double braces HTML-escape
{{ x }}HTML-escapes the value:&,<,>,",',/,`and=become entities, so/srv/data/x.parquetturns into/srv/data/x.parquetandO'BrienintoO'Brien.{{{ x }}}inserts the value as it is.
Neither form escapes SQL. Use {{{ }}} for every conn.*, auth.* and env.* variable, and for strings inside sections. Inside quotes, never use double braces on a params.* value: outside a section '{{ params.x }}' becomes the string '?' and the request fails with 500.
Sections
{{#params.x}} ... {{/params.x}}renders whenxwas sent.{{^params.x}} ... {{/params.x}}renders whenxwas not sent.- Together they give a default:
ORDER BY {{#params.sort}}{{{ params.sort }}}{{/params.sort}}{{^params.sort}}c_custkey{{/params.sort}}.
Rows for the caller
Filter on auth.*, which flAPI sets from the credentials it checked, never on a parameter the caller sends. Use only values the caller cannot edit: your own users:, a token you signed, or an identity provider's immutable sub or object id, never preferred_username or email from an identity provider where users can change their own profile. Split the comma-joined roles (role names must not contain commas), and write the filter without a section so an anonymous request matches nothing:
SELECT id, owner, amount
FROM deals
WHERE owner = '{{{ auth.username }}}'
OR list_contains(string_split('{{{ auth.roles }}}', ','), 'admin')
See Restrict rows to the caller.
Pagination owns LIMIT
GET endpoints are paginated by default (with-pagination: true, 100 rows per page). Do not declare limit or offset as request fields, and do not put LIMIT {{ params.limit }} or a fixed LIMIT in a paginated GET template: it applies before flAPI's offset, so ?limit=2&offset=2 returns "data": []. For a bare array with your own LIMIT, set with-pagination: false.
Check what runs
flapii templates expand /customers --params '{"segment":"BUILDING"}' # the SQL and its bindings
flapi -c flapi.yaml --validate-config # section balance, undeclared params
templates expand needs a server started with --config-service; see flapii CLI.
DuckDB 2.0 notes
flAPI v26.11.23 moved from DuckDB 1.5 to DuckDB 2.0.1. A few SQL behaviours changed that can affect templates written for 1.5:
- Lambda syntax. The single-arrow lambda
x -> x + 1is an error. Writelambda x : x + 1, e.g.list_transform(tags, lambda t : upper(t)). - Division by zero.
//and%by zero raise an error instead of returningNULL. Guard withNULLIF(divisor, 0). - Transactions. Any error inside an explicit transaction aborts it.
MERGE/UPDATE ... FROMwith several matching source rows give a nondeterministic value. Keep cache merge keys unique.- Output.
INTERVALvalues render as DuckDB's text (1 day 00:01:00); nestedSTRUCT/MAPkey order inside a row is not specified. - Files. New database files and DuckLake catalogs are 2.0-only: DuckDB 1.x cannot read them. Existing 1.5 files keep working unchanged.
See DuckDB's own migration guide for the full list.
Next steps
- SQL Templating Guide: the full walk-through with runnable examples
- Parameters and Validation: the validators behind every text site
- Endpoints Overview: complete endpoint configuration
- Examples: templates in action