Skip to main content

SQL Templating

A flAPI template is a SQL file with Mustache tags. On every request flAPI validates the parameters, renders the template and runs the result on DuckDB. Most of this page is about one question: which values reach DuckDB as bound parameters, and which as SQL text?

By the end you will know:

  • which brace form to use where, and why neither form escapes SQL;
  • how to make a filter optional without losing the binding;
  • how to return each caller only their own rows;
  • why LIMIT and OFFSET belong to pagination, not to your template.

Before you start​

The examples read customers.parquet from the flAPI repository (columns c_custkey, c_name, c_nationkey, c_acctbal, ...):

mkdir -p templates-guide/data templates-guide/sqls && cd templates-guide
curl -L -o data/customers.parquet https://github.com/DataZooDE/flapi/raw/main/examples/data/customers.parquet

Step 1: Write a first template​

flapi.yaml
project-name: templates-guide
template:
path: ./sqls
connections:
customers:
properties:
path: './data/customers.parquet'

An endpoint is a YAML file and a SQL file in sqls/:

sqls/customer.yaml
url-path: /customers/:id
request:
- field-name: id
field-in: path
required: true
validators:
- type: int
min: 1
template-source: customer.sql
connection: [customers]
sqls/customer.sql
SELECT c_custkey, c_name, c_nationkey, c_acctbal
FROM read_parquet('{{{ conn.path }}}')
WHERE c_custkey = {{ params.id }}

Start the server with flapi -c flapi.yaml and call it from a second terminal:

curl -s http://localhost:8080/customers/7
# {"data":[{"c_custkey":7,"c_name":"Customer#000000007",...}],"next":"","total_count":1}
curl -s http://localhost:8080/customers/abc
# {"errors":[{"message":"Invalid integer value","field":"id"}]}

The validator runs first: abc is rejected with 400 before any SQL is rendered. The answer is wrapped in {data, next, total_count} because GET endpoints are paginated (Step 7).

These are all the variables a template can use:

VariableContains
params.*Request parameters: query, path, header and body fields
conn.*The properties of the endpoint's first connection (conn.path here)
auth.*The caller, on an authenticated request (Step 5)
env.*Environment variables matching template.environment-whitelist
cache.*Cache table names, and in a cache populate template the snapshot and watermark values (Caching)

There is no context.*: {{{ context.auth.username }}} and {{{ context.conn.path }}} render as empty strings.

Step 2: Look at the SQL flAPI runs​

Restart the server with the config service on, using a token you choose:

export FLAPI_CONFIG_SERVICE_TOKEN=my-dev-token
flapi -c flapi.yaml --config-service

In the second terminal, export the same token and render the template:

export FLAPI_CONFIG_SERVICE_TOKEN=my-dev-token
flapii templates expand /customers/:id -p '{"id":"7"}'
{
"bindings": [{"position": 1, "name": "id", "type": "integer", "value": 7}],
"expanded": "SELECT c_custkey, c_name, c_nationkey, c_acctbal\nFROM read_parquet('/home/me/templates-guide/data/customers.parquet')\nWHERE c_custkey = ?\n"
}

{{ params.id }} became ?, and 7 travels separately as an integer. DuckDB runs this as a prepared statement, so the value can never change the statement. conn.path was pasted in as text. (A connection property that starts with ./ or ../ is made absolute against the directory of flapi.yaml.)

Without the exported token, flapi --config-service generates a random one and flapii gets a 401. If the server is not on localhost:8080, pass --base-url http://host:port or set FLAPI_BASE_URL. To also parse and plan the SQL without running it, add ?validate_only=1 to the underlying POST .../template/expand call (flapii CLI).

Step 3: Double or triple braces, bound or text​

The rule of thumb:

  • Values (after =, <, IN (, LIKE): write {{ params.x }} bare, or '{{{ params.x }}}' in quotes. Outside sections, flAPI binds both.
  • Names and keywords (ORDER BY, a table, DATE '...'): write {{{ params.x }}} and restrict it with an enum or a strict regex validator.
  • conn.*, env.*, auth.*: write '{{{ ... }}}'. These are never bound.

Two terms used below. A section is a block between {{#name}} (or {{^name}}) and {{/name}} that Mustache renders or skips (Step 4). A value site is a place where SQL expects a value, such as the right side of =.

What the two brace forms do​

  • {{ x }} HTML-escapes the value. It replaces &, <, >, ", ', /, ` and = with entities: ' becomes &#39;, / becomes &#x2F;.
  • {{{ x }}} inserts the value as it is.
Neither form escapes SQL

Mustache knows nothing about SQL quotes or comments. What protects you is that flAPI rewrites a params.* reference into a bound ? wherever it can, and the validator everywhere else.

When a value is bound​

flAPI binds a params.* reference when all of these hold:

  1. The field has a typed validator: int, number, boolean, date, time, string, email, uuid or enum. A field without one is always text.
  2. The reference is outside every section.
  3. It is at a value site.

At a value site outside sections, a typed field is bound like this:

You writeDuckDB receives
c = {{ params.x }}c = ?
c = {{{ params.x }}}c = ?
c = '{{{ params.x }}}'c = ? (the quotes go, the value is bound as text)
c LIKE '%{{{ params.x }}}%'c LIKE ('%' || ? || '%')
c IN ('{{{ params.a }}}', '{{{ params.b }}}')c IN (?, ?)

An absent value binds NULL at an unquoted site and '' inside quotes.

Where a value stays text​

These sites stay text, and the validator is your only defence there:

SiteExample
Inside a section{{#params.x}} AND c = {{{ params.x }}} {{/params.x}}
A typed literal or a keyword that takes a string ({{{ }}} only)DATE '{{{ params.d }}}', INTERVAL '{{{ params.n }}} days'
Where a name is expected ({{{ }}} only)FROM {{{ params.t }}}, JOIN, INTO, AS, BY, ...
Glued to an identifier ({{{ }}} only)sales_{{{ params.year }}}
An enum field without quotes ({{{ }}} only)ORDER BY {{{ params.sort }}}
A DuckLake time-travel clause ({{{ }}} only)AT (VERSION => {{{ params.v }}})
A SQL comment-- {{ params.x }}
Every variable that is not params.*{{{ conn.path }}}, {{{ auth.username }}}, {{{ env.X }}}

The "{{{ }}} only" rows matter: the rewriter checks the surrounding SQL only for triple braces. A double-brace reference to a typed field outside a section becomes ? wherever it is, so at most of those sites it breaks the statement (see Common mistakes).

Binding is also the fast path. A bound template renders to the same SQL text for every value, and each request thread keeps up to 64 prepared SELECTs keyed by that text, so DuckDB plans the query once.

One endpoint, every kind​

sqls/customers.yaml
url-path: /customers
request:
- field-name: name
field-in: query
validators:
- type: string
max-length: 50
- field-name: nation
field-in: query
validators:
- type: int
min: 0
max: 24
- field-name: sort
field-in: query
validators:
- type: enum
allowedValues: [c_custkey, c_name, c_acctbal]
template-source: customers.sql
connection: [customers]
mcp-tool:
name: search_customers
description: Find customers by part of their name and by nation
sqls/customers.sql
SELECT c_custkey, c_name, c_nationkey, c_acctbal
FROM read_parquet('{{{ conn.path }}}')
WHERE c_name LIKE '%{{{ params.name }}}%'
{{#params.nation}}
AND c_nationkey = {{{ params.nation }}}
{{/params.nation}}
ORDER BY {{#params.sort}}{{{ params.sort }}}{{/params.sort}}{{^params.sort}}c_custkey{{/params.sort}}
  • name is bound: ?name=O'Brien is just a string that matches nothing. Without ?name=, it binds '' and LIKE '%%' matches every row, so the filter needs no section.
  • nation is inside a section, so it is pasted as text. The int validator (0 to 24) is what keeps it safe: ?nation=99 is a 400.
  • sort is a column name, which cannot be a parameter. It is text, and the enum validator allows only three names.
flapii templates expand /customers -p '{"name":"Brien","nation":"15","sort":"c_acctbal"}'
# "expanded": "... WHERE c_name LIKE ('%' || ? || '%')\n AND c_nationkey = 15\nORDER BY c_acctbal\n"
# "bindings": [{"position": 1, "name": "name", "type": "varchar", "value": "Brien"}]

The mcp-tool: block also makes this endpoint an MCP tool. Without MCP authentication, startup prints a MCP_UNAUTHENTICATED_TOOLS security warning; that is expected in this local example.

Step 4: Sections, inverted sections and defaults​

  • {{#params.x}} ... {{/params.x}} renders its body when x was sent. A string sent empty (?name=) counts as sent.
  • {{^params.x}} ... {{/params.x}} renders its body when x was not sent.
  • Together they give a default, as ORDER BY above does.

A field can also have a default of its own. It is applied before validation, so the template always sees a value:

request:
- field-name: sort
field-in: query
default: c_custkey
validators:
- type: enum
allowedValues: [c_custkey, c_name, c_acctbal]

Do not use a default for limit or offset; see Step 7.

Keep an optional value bound​

A section is the natural way to make a filter optional, but everything inside it is text. For a free-text value that is a problem: '{{{ params.name }}}' inside a section sends c_name = 'O'Brien' to DuckDB, which fails with a 500. To keep an optional value bound, leave it outside the section and let NULL switch the filter off:

sqls/customers-exact.yaml
url-path: /customers-exact
request:
- field-name: name
field-in: query
validators:
- type: string
max-length: 50
template-source: customers-exact.sql
connection: [customers]
sqls/customers-exact.sql
SELECT c_custkey, c_name
FROM read_parquet('{{{ conn.path }}}')
WHERE ({{ params.name }} IS NULL OR c_name = {{ params.name }})
ORDER BY c_custkey

Without ?name=, both placeholders bind NULL and every row comes back. ?name=O%27Brien returns no row and no error.

A list in one parameter​

Bind it as one string and split it in SQL. The regex validator makes sure it is a list of numbers:

sqls/customers-by-ids.yaml
url-path: /customers-by-ids
request:
- field-name: ids
field-in: query
required: true
validators:
- type: string
regex: '^[0-9]{1,9}(,[0-9]{1,9}){0,99}$'
template-source: customers-by-ids.sql
connection: [customers]
sqls/customers-by-ids.sql
SELECT c_custkey, c_name
FROM read_parquet('{{{ conn.path }}}')
WHERE list_contains(string_split({{ params.ids }}, ','), CAST(c_custkey AS VARCHAR))
ORDER BY c_custkey

?ids=3,7 returns two customers; ?ids=3;7 fails the regex with 400.

Step 5: Use the caller and the environment​

auth.* is set on an authenticated request: a REST request, or an MCP tools/call under mcp.auth. flAPI fills it from the credentials it checked; a caller cannot set it through parameters.

VariableValue
auth.usernameThe user name (for a JWT, its sub claim)
auth.rolesThe roles, joined with commas: sales,eu
auth.emailThe email claim, only with type: oidc; empty for basic and bearer
auth.typebasic, bearer (also for type: jwt) or oidc
auth.authenticatedtrue

On an anonymous request all of them are empty. env.* holds only the variables that match a pattern in template.environment-whitelist; with an empty whitelist it holds none.

The next two steps use a new project, who-am-i, with its own copy of data/customers.parquet:

flapi.yaml
project-name: who-am-i
template:
path: ./sqls
environment-whitelist: ['^FLAPI_REGION$']
connections:
customers:
properties:
path: './data/customers.parquet'
deals:
init: |
CREATE OR REPLACE TABLE deals AS
SELECT * FROM (VALUES (1, 'alice', 100), (2, 'alice', 250), (3, 'carol', 75)) t(id, owner, amount);
cors:
allow-origins: [https://app.example.com]

The deals connection has no file: its init: SQL runs once at startup and creates a small table in memory (Connections). The cors: block names the web origins whose pages may call this server; without it, flAPI allows every origin and, because the endpoints below require a login, warns CORS_WILDCARD_WITH_AUTH at startup.

sqls/me.yaml
url-path: /me
with-pagination: false
template-source: me.sql
connection: [customers]
auth:
enabled: true
type: basic
users:
- username: alice # password: reader-pass
password: '$pbkdf2-sha256$600000$FpkEyJklqXpwdoxWhoRzvw$RA15LygYf0O0yiG8OPQ91NWeeSNqcxTwMl4pRXLcmq0'
roles: [sales, eu]

The password is stored as a PBKDF2 hash; Authentication shows how to make one.

sqls/me.sql
SELECT '{{{ auth.username }}}'      AS username,
'{{{ auth.roles }}}' AS roles,
'{{{ auth.type }}}' AS auth_type,
'{{{ env.FLAPI_REGION }}}' AS region,
count(*) AS customers
FROM read_parquet('{{{ conn.path }}}')
FLAPI_REGION=eu-west flapi -c flapi.yaml      # first terminal
curl -s -u alice:reader-pass http://localhost:8080/me
# [{"username":"alice","roles":"sales,eu","auth_type":"basic","region":"eu-west","customers":1500}]

Step 6: Restrict rows to the caller​

With auth.*, one endpoint can return each caller only their own rows. Three rules:

  • Filter only on what the server verified. auth.username and auth.roles come from the credentials flAPI checked. Never filter on a request parameter, header or body field that names the user or tenant: the caller can type anything there. Of the verified values, use only those 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. Put them in single quotes with triple braces, '{{{ auth.username }}}'.
  • Test roles as a list. auth.roles is one comma-joined string, so split it: list_contains(string_split('{{{ auth.roles }}}', ','), 'admin'). A substring match such as LIKE also matches a role named notadmin.
  • Fail closed. Write the filter without a section around it. An anonymous request has an empty auth.username, so it matches no owner. Do not wrap the filter in {{#auth.username}}: with no user, the filter would vanish and every row would come back.
sqls/deals.yaml
url-path: /deals
with-pagination: false
template-source: deals.sql
connection: [deals]
auth:
enabled: true
type: basic
users:
- username: alice
password: '$pbkdf2-sha256$600000$FpkEyJklqXpwdoxWhoRzvw$RA15LygYf0O0yiG8OPQ91NWeeSNqcxTwMl4pRXLcmq0'
roles: [sales]
- username: bob
password: '$pbkdf2-sha256$600000$FpkEyJklqXpwdoxWhoRzvw$RA15LygYf0O0yiG8OPQ91NWeeSNqcxTwMl4pRXLcmq0'
roles: [notadmin]
- username: root
password: '$pbkdf2-sha256$600000$FpkEyJklqXpwdoxWhoRzvw$RA15LygYf0O0yiG8OPQ91NWeeSNqcxTwMl4pRXLcmq0'
roles: [admin]
sqls/deals.sql
SELECT id, owner, amount
FROM deals
WHERE owner = '{{{ auth.username }}}'
OR list_contains(string_split('{{{ auth.roles }}}', ','), 'admin')
ORDER BY id
curl -s -u alice:reader-pass http://localhost:8080/deals
# [{"id":1,"owner":"alice","amount":100},{"id":2,"owner":"alice","amount":250}]
curl -s -u bob:reader-pass http://localhost:8080/deals # role notadmin, owns nothing
# []
curl -s -u root:reader-pass http://localhost:8080/deals # role admin: all three rows

auth.* is text, never bound, so it is quoted: '{{{ auth.username }}}'.

Step 7: Leave LIMIT and OFFSET to pagination​

GET endpoints are paginated by default (with-pagination: true, 100 rows per page). flAPI wraps your query and applies ?limit= and ?offset= itself, so those two names are reserved:

  • Do not declare limit or offset as request fields.
  • Do not write 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": [].

GET /customers?limit=2&offset=2 on the endpoint from Step 3 returns rows 3 and 4 and "next": "/customers?offset=4&limit=2". If you need a bare array and your own LIMIT, set with-pagination: false.

A full page runs your query twice: once for the page, and once as SELECT COUNT(*) over it for total_count. On a warehouse that bills per scan, the second query costs money. Set total-count: false on endpoints whose clients only page forward, or serve the endpoint from a cache.

Step 8: Preview an MCP tool call with _dryRun​

An endpoint with an mcp-tool: block is also an MCP tool. Add "_dryRun": true to the arguments and the tool renders the template without running it:

curl -s -X POST http://localhost:8080/mcp/jsonrpc -H 'Content-Type: application/json' -d '{
"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": "search_customers", "arguments": {"name": "000000007", "_dryRun": true}}}'

The result carries "dry_run": true, rendered_sql (with ? placeholders) and bindings, the same shape as templates expand. It also has "rows": []: nothing ran, so that is not the query's answer.

Step 9: Write data​

The same rules apply to POST, PUT, PATCH and DELETE. A write answers rows_affected and, when a statement has a RETURNING clause, its rows as data. POST answers 201, the others 200.

sqls/notes-create.sql
INSERT INTO notesdb.notes (id, title)
VALUES ({{ params.id }}, {{ params.title }})
RETURNING id, title;

Both values are bound, so {"id":1,"title":"O'Brien's list"} needs no escaping. With operation.returns-data: true, data is always present. A write template may hold several ;-separated statements; they run in one transaction (operation.transaction, on by default), each as its own prepared statement. The full walk-through is in Write Operations.

Known limitation in v26.11.25: a POST cannot serve a plain SELECT (#271)

A POST whose template is a single SELECT returns no rows. Until it is fixed, make the SELECT the second statement; with returns-data: true the rows of a final SELECT become data:

SET VARIABLE q = {{ params.q }};
SELECT id, title FROM notesdb.notes
WHERE title ILIKE '%' || getvariable('q') || '%'

When a template fails. A broken template, or SQL that DuckDB rejects, is a 500 whose body carries a request_id and nothing else. Look that id up in the server log (Observability). To catch errors before a request does, run flapi -c flapi.yaml --validate-config in CI: it checks every template's sections and warns about undeclared parameters.

Common mistakes​

  • '{{ params.x }}' with double braces inside quotes. Outside a section it becomes the string '?', not a placeholder, and the request fails with 500 (Failed to bind parameter in the log). The same happens in DATE '{{ params.d }}'. Write {{ params.x }} without quotes, or '{{{ params.x }}}'.
  • ORDER BY {{ params.sort }}. Double braces become ?, and DuckDB answers Parameter not supported in ORDER BY clause. Use {{{ params.sort }}} with an enum validator. The same goes for table and column names.
  • {{ conn.path }}, or {{ }} on a string inside a section. HTML escaping turns /srv/data/x.parquet into &#x2F;srv&#x2F;data&#x2F;x.parquet and O'Brien into O&#39;Brien. Nothing reports it; the file is just not found, or the row does not match. Use {{{ }}} for every non-params variable and for strings in sections.
  • Free text in a section. '{{{ params.name }}}' inside {{#params.name}} is pasted as written, so a quote in the value breaks the SQL. Keep the value outside the section, or restrict it with a regex validator.
  • LIMIT {{ params.limit }} in a GET template. Pagination owns limit and offset.
  • A parameter the endpoint does not declare. {{ params.region }} without a region field has no validator and is never bound. flapi --validate-config warns about it.
  • context.*. It does not exist and renders empty. Use auth.* and conn.*.
  • auth.roles matched as a substring. It is one comma-joined string; split it.
  • A row filter inside {{#auth.username}}. It disappears for anonymous callers, who then see every row.
  • {{cache.currentSnapshotTimestamp}}. That variable does not exist; see Caching for the cache variables.

How it works​

The template is checked for balanced sections at load time. On each request, PreparedTemplateRewriter replaces each bindable params.* reference with ? and records a binding, Mustache renders what is left, and DuckDB prepares the SQL and binds the values with their validator's type.

The injection tests behind these claims ship in the repository: test_sql_injection_corpus.py (GET payloads across every validator type) and test_sql_injection_write_corpus.py (POST payloads, including multi-statement RETURNING templates). The upstream guide is docs/guides/sql-templates.md.

Next steps​

🍪 Cookie Settings