REST API (FastAPI)
This section documents the nl2sql-api FastAPI package that exposes the core
engine over HTTP. Implementation lives in packages/api/src/nl2sql_api/.
Runtime Model
Application lifecycle
Source: packages/api/src/nl2sql_api/main.py
lifespanconfigures logging, builds one engine withNL2SQL.from_config()(the fileNL2SQL_CONFIGnames, else./nl2sql.yaml) and callsengine.check()before it serves. Arequireddatasource that fails, or no datasource ready at all, raisesEngineNotReady: the API logs the report and starts anyway, so a restart loop never hides the reason.GET /readythen answers503 not_readyand an admin reads each failing datasource and its stage underproblems; an optional one that fails leaves the others serving. Any other failure ofcheck()closes the engine and stops the start. The engine is stored inapp.state.engineand closed at shutdown. Logs are text, or JSON lines withNL2SQL_LOG_FORMAT=json.- Retention: the lifespan calls
engine.storage.purge()once before it serves and then once a day (purge_daily, everyPURGE_INTERVAL_Sseconds), so traces and results older than their store'smax_age_daysare deleted (see Storage → Retention). A failed purge is logged and never stops the server. - Dashboard schedules: the lifespan starts a runner that calls
engine.dashboards.run_scheduled()every minute (run_schedules, everySCHEDULE_INTERVAL_Sseconds), so a dashboard with a schedule refreshes as its owner while the server runs (see Dashboards). A failed run is logged and never stops the server. - The package imports the engine only through the top-level
nl2sqlnamespace (from nl2sql import NL2SQL, QueryResult, UserContext, configure_logging, ...), never an engine submodule.packages/api/tests/test_architecture.pyenforces it. create_app(config_path=None)builds the app: one router module per namespace (health,query,approvals,conversations,dashboards,workspaces,answers,datasources,datasource,index,indexing,knowledge,evals,settings,llm,web) under/api/v1(webat the root), anderrors.installfor the error envelope.nl2sql_api.main:appiscreate_app()foruvicorn nl2sql_api.main:app.- CORS is restricted to the origins in
api.cors_origins(see CORS origins); with none configured, no cross-origin browser access is allowed.
Dependency injection
Source: packages/api/src/nl2sql_api/dependencies.py
get_engine(request)returns the singletonNL2SQLinstance.- Routes are thin over the engine's namespaces (
engine.datasources,engine.index, ...); there are no service classes between them. identity.caller(innl2sql_api/identity.py) returns the caller'sUserContext; see Identity.identity.adminguards the routes that change datasources, LLMs or the index; see Admin routes.
Interactive docs
FastAPI serves Swagger UI at /docs, ReDoc at /redoc and the OpenAPI schema at
/openapi.json, with a summary, description and tag on every route. Start the
server on a config:
nl2sql-api serve --config nl2sql-demo/nl2sql.yaml --port 8000 # one worker, 127.0.0.1; then open http://localhost:8000/docs
API Index
| API | Router Path | Purpose |
|---|---|---|
| Health | routes/health.py |
Liveness (/health), readiness (/ready, from the engine's own check), /meta (mode, auth source, request_llm; with a caller also the datasources and what is recorded) and /about. |
| Query | routes/query.py |
Execute natural language queries, whole or streamed as Server-Sent Events, with a clarification choice or granted approval_ids, and a request's own keys and models. |
| Results | routes/query.py |
A run's manifest, pages, CSV and chart (/results/{trace_id}/...). |
| Traces and feedback | routes/query.py |
A run's trace, ratings, and corrections as proposals. |
| Approvals | routes/approvals.py |
List, grant and deny the approvals a hook asked for. |
| Conversations | routes/conversations.py |
Conversations: start, list, read, delete, send a turn (whole or streamed), retry, run a chat tool, report. |
| Datasources | routes/datasources.py |
Connect a database, list datasources, read a schema or its diagram. |
| Settings and API keys | routes/settings.py |
The agents' models (/llm, /llm/providers), replace the LLM (PUT /settings/llm), change models only (PATCH /settings/llm), API keys (/api-keys) and the event catalog. |
| Evals | routes/evals.py, routes/jobs.py |
The configured suites and the scorers; the eval job. |
| Indexing | routes/index.py, routes/jobs.py |
Index status, drift check, retrieval inspector, the index job. |
| Knowledge | routes/knowledge.py, routes/jobs.py |
The merged knowledge, proposals, the profile job. |
| Saved answers | routes/answers.py |
Save, list, read, delete and run a person's own answers. |
| Dashboards | routes/dashboards.py, routes/workspaces.py |
Dashboards and workspaces: open, refresh, edit, pin, move, delete; the starter questions. |
| Errors | errors.py |
The one error envelope and the request id. |
The built web app is served at / and is not an API route. The committed contract is packages/api/openapi.json; test_openapi_snapshot_is_current
fails when a route changes without it (rewrite it with python packages/api/tests/test_openapi_snapshot.py).
Error Handling
Every non-2xx response is the error envelope,
{"error": {"code", "message", "fix", "details", "request_id"}}. Only the facade's own NL2SQLError (and its named
subclasses) is mapped to its status; anything else, a built-in ValueError, KeyError, PermissionError or a
pydantic ValidationError included, is a 500 that names a request id and never the exception's text. Routes carry
no except Exception.
POST /api/v1/query still returns pipeline errors as a normal HTTP 200 inside QueryResult.errors.
Route handlers that call blocking engine code are declared with def rather than
async def, so Starlette runs them in its threadpool instead of blocking the
event loop.
Configuration
The REST API is configured by the same nl2sql.yaml as the engine. Beyond the
runtime server options of nl2sql-api serve (--config, --host, --port, --demo, --dir, --hosted, --questions-per-minute, --questions-per-session; one worker, no reload; see Hosted demo),
its own settings are the api section of that file (see
The api section), and the admin roles are
policies.admin_roles. The engine validates the api section and never reads it.
CORS origins
api.cors_origins lists the browser origins allowed to call the API
cross-origin. Each entry is a full origin (scheme, host and, if non-default,
port).
With one or more origins configured, only those origins are accepted and
credentialed requests (cookies, Authorization) are permitted.
With none, no origins are allowed and credentials are disabled. That is the intended default, not a misconfiguration: a browser page served from another origin cannot call the API until you opt it in. The list is read from the engine's config, which is loaded at startup, so changing it requires restarting the server.
This setting governs the browser same-origin policy only. Non-browser clients --
curl, server-side callers, the Python SDK -- do not send an Origin header and
are unaffected by it; use authentication and network controls to restrict those.
Identity
The engine enforces RBAC; the API decides who is asking. api.auth picks one source, and every request resolves one
UserContext through the identity.caller dependency. The request body is never read for it.
api.auth |
Identity | No identity |
|---|---|---|
api_keys |
Authorization: Bearer <key>, verified by engine.api_keys.verify: the key's user, tenant and roles. |
401 with WWW-Authenticate: Bearer |
proxy |
The api.proxy.user_header, tenant_header (else settings.tenant_id) and roles_header (comma-separated), honoured only from a peer in api.proxy.trusted_from. |
401 (also for a peer outside trusted_from, whose headers are ignored) |
static |
One role, api.static_role, for every request, as the one user static. |
401 when static_role is unset |
none (default) |
The local operator: user_id: "local" with the policies.admin_roles. |
403 unless the request is made straight to localhost |
Under none, nl2sql-api serve refuses to bind a host that is not loopback, and a request whose Host is not
localhost, 127.0.0.1 or [::1], or that carries X-Forwarded-For, Forwarded or X-Real-IP, is a 403, so a
reverse proxy on the same host or a DNS-rebinding page is not taken for the operator.
# api.yaml behind an authenticating proxy at 10.0.0.5.
auth: proxy
proxy: { trusted_from: [10.0.0.5/32] }
A test or an embedding app overrides identity.caller and identity.admin with app.dependency_overrides.
Admin routes
The routes that change the running process need an admin role, checked by the
identity.admin dependency:
POST /api/v1/datasourcesandDELETE /api/v1/datasources/{datasource_id}- The Connect routes
GET /api/v1/datasource-typesandPOST /api/v1/datasources/test PUTandPATCH /api/v1/settings/llmand the/api/v1/api-keysroutes- Every
/api/v1/evalsroute,POST /api/v1/jobs/evalandPOST /api/v1/jobs/demo POST /api/v1/jobs/index,POST /api/v1/jobs/profile,DELETE /api/v1/indexandGET /api/v1/index/checkPOST /api/v1/knowledge/reloadand every/api/v1/proposalsroute
| Key | Default | Meaning |
|---|---|---|
policies.admin_roles |
[admin] |
The roles that may call the admin routes. |
A caller whose roles include one in policies.admin_roles is let through; one with
roles but none of them admin is HTTP 403; one with no identity is HTTP 401. The check
uses admin_roles alone, so policies.allow_all does not make a caller an admin.
The read-only routes (/health, /ready, /meta, GET /datasources, GET /llm, which
never returns API keys, and GET /index) need no role.