Your backend¶
Setup 2 of 3
You write the dashboard, the data stays on your server. The components send their queries to one endpoint of your API, which answers with the rights of the signed-in user. No frame, no database in the browser.
POST per render: "revenue by country"Choose it when you write the dashboards of your product yourself, on data that must not leave your server: too large to download, or not the same for everyone.
Choose another setup when the dashboard is written by a model or by a user: its scripts would run in your page, with your cookies. It goes in the sandbox, which can call the same endpoint. With no server at all, see the static page.
1. The page¶
Add <source-api> with the address of your endpoint, and name the measures and dimensions your server knows. There is no table attribute and no SQL in the page.
<source-api url="/api/queries"></source-api>
<date-range-filter presets="30d,90d,365d,ytd" default="90d"></date-range-filter>
<ui-filter dimension="channel" type="segmented" label="Channel"></ui-filter>
<score-card measure="revenue"></score-card>
<bar-chart measure="revenue" by="country"></bar-chart>
<line-chart measure="revenue" granularity="month" breakdown-by="channel"></line-chart>
<data-table by="category" measures="revenue, orders" sort-by="revenue"></data-table>
<script src="https://unytics.io/bi-components/dist/bi-components.js" defer></script>
The script is the same file as in a static page. <source-api> is what sends the queries to your server instead of DuckDB-WASM, which is then never downloaded.
2. The endpoint¶
The components of a render send their queries together, as one request. Each query has an id; your server gives one answer per id.
POST /api/queries
{
"queries": {
"q1": { "mode": "semantic", "metrics": ["revenue"], "dimensions": null, "date_range": ["2026-09-01", "2026-11-29"], "filters": null, ... },
"q2": { "mode": "semantic", "metrics": ["revenue"], "dimensions": ["country"], ... }
}
}
200
{
"answers": {
"q1": { "rows": [{ "revenue": 592881.64 }], "meta": { "formats": { "revenue": "eur" }, "labels": { "revenue": "Revenue" } } },
"q2": { "error": "Unknown names: margin" }
}
}
- A query describes a chart: names of measures and dimensions, the filters and the period selected in the page. It is never SQL.
- An answer is
{ rows, meta }, or{ error }. The error text is shown in the component that asked, and nowhere else. - A refused request (HTTP 4xx or 5xx) fails every query it held, with the
detailorerrorof its body.
Here is a complete server, with FastAPI and DuckDB. It knows two measures and three dimensions, applies filters, the period and a time granularity, and restricts every query to the countries its viewer may see:
import duckdb
from fastapi import FastAPI, Request
MEASURES = { # name: (SQL, label, format)
"revenue": ("sum(revenue)", "Revenue", "eur"),
"orders": ("count(*)", "Orders", "int"),
}
DIMENSIONS = ["country", "channel", "category"]
GRANULARITIES = ["day", "week", "month", "quarter", "year"]
db = duckdb.connect()
db.execute("create table orders as select * from read_csv('orders.csv')")
app = FastAPI()
def answer(spec: dict, countries: list[str]) -> dict:
metrics, dimensions = spec.get("metrics") or [], spec.get("dimensions") or []
filters, granularity = spec.get("filters") or {}, spec.get("date_granularity")
unknown = [m for m in metrics if m not in MEASURES] + [d for d in [*dimensions, *filters] if d not in DIMENSIONS]
if spec.get("mode") != "semantic" or unknown or granularity not in [None, *GRANULARITIES]:
raise ValueError(f"Unknown names: {', '.join(unknown)}" if unknown else "Unsupported query")
columns = [*(["date"] if granularity else []), *dimensions]
select = [f"strftime(date_trunc('{granularity}', date), '%Y-%m-%d') as date"] if granularity else []
select += dimensions + [f"{MEASURES[m][0]} as {m}" for m in metrics]
where, values = ["country in (select unnest(?))"], [countries] # the viewer's rights, on every query
for dimension, value in filters.items():
where.append(f"{dimension} in (select unnest(?))")
values.append(value if isinstance(value, list) else [value])
if spec.get("date_range"):
where.append("date between ? and ?")
values += spec["date_range"]
sql = f"select {', '.join(select)} from orders where {' and '.join(where)}"
if columns:
sort_by = spec.get("sort_by") if spec.get("sort_by") in [*columns, *metrics] else columns[0]
sql += f" group by all order by {sort_by} {'desc' if spec.get('sort_ascending') is False else 'asc'}"
if isinstance(spec.get("limit"), int):
sql += f" limit {min(spec['limit'], 1000)}"
cursor = db.cursor().execute(sql, values)
names = [column[0] for column in cursor.description]
return {
"rows": [dict(zip(names, row)) for row in cursor.fetchall()],
"meta": {"formats": {m: MEASURES[m][2] for m in metrics}, "labels": {m: MEASURES[m][1] for m in metrics}, "time_col": "date"},
}
@app.post("/api/queries")
async def queries(request: Request) -> dict:
countries = ["France", "Spain"] # in your application: what the signed-in user may see
answers = {}
for id, spec in (await request.json())["queries"].items():
try:
answers[id] = answer(spec, countries)
except ValueError as error:
answers[id] = {"error": str(error)} # shown in the component that asked
return {"answers": answers}
It runs on the orders.csv of the examples, with pip install fastapi uvicorn duckdb then uvicorn server:app, and answers the page of step 1. What matters in it:
- Names come from lists the server owns. Nothing a query contains is written into the SQL text: names are looked up, values are query parameters.
- The viewer's rights are added to every query, whatever it asked.
metasaves attributes in the page: the format and the label of each measure, and the name of the time column of a time series.
It leaves out comparisons with a previous period (compare="yoy") and stricter checks of what it receives. Answer the queries describes every field of a query and of an answer, in any language; the server of the playground is a complete version of the one above.
Who is looking¶
Your server decides what each person may see. How it knows who is asking is up to you:
| A session cookie | Nothing to do: a request to the same site carries its cookies. |
| A token | headers, a property of the element: api.headers = () => ({ authorization: `Bearer ${getToken()}` }). The function is called for each request. |
| Something the page knows | body, a JSON object added to every request: <source-api url="/api/queries" body='{"workspace": "emea"}'>, or the body property (an object or a function). |
| An API on another site | credentials="include", and CORS on that server. |
Changing an attribute or a property makes every component ask again:
document.querySelector('source-api').body = { workspace: 'apac' };
Never trust what the page sends to say what its user may see: the page runs in their browser and anyone can call your API with any query. A body selects among things the signed-in user is allowed; the session or the token says who they are.
How queries travel¶
- One request per render. The queries asked within 10 ms leave together: the score cards and the charts of a page are one
POST, and so is what a click on a filter refreshes. A batch of more than 100 queries is split. - The latest query of a component wins. A new query replaces the previous one, whose answer is ignored.
- A query times out after 30 seconds, with an error in its component.
- A named query, asked by a script with
dashboard.query('category_mix'), leaves as{ "mode": "named", "name": "category_mix", "filters": ..., "date_range": ... }: your server holds its definition.
In a single-page application or a Markdown site¶
Each <source-api> added to a page installs a new dashboard, with an empty selection, and the components follow it. A site that replaces its content without reloading (a single-page application, the instant navigation of mkdocs-material) thus starts each page fresh, with nothing to call.
Give filters a value at start with default, so that the first render already asks for the right period:
<date-range-filter presets="30d,90d,365d" default="90d"></date-range-filter>
<ui-filter option="period_comparison_method" type="segmented" options="prev_period:vs previous period, yoy:vs last year" default="yoy"></ui-filter>
A page has either a <source-api> or <source-table> elements, not both.
Go further¶
- Answer the queries: the fields of a query, what
metaholds, comparisons, time series, what to check. - Components: the attributes available with named measures (
compare,granularity,attributes,param-*). - Custom charts and scripts:
window.dashboard.query(...)sends your own queries to the same endpoint. - Python, FastAPI, Streamlit.
Example of this setup: a dashboard on a FastAPI backend, a Markdown page of this site, with three viewer profiles whose rights are applied by the server.