FastAPI Integration¶
sqlspec.extensions.fastapi provides SQLSpecPlugin for FastAPI (>= 0.162.0), wiring database connection pools into FastAPI's lifespan context manager and exposing Depends(...) callables for request-scoped driver sessions, connections, and declarative query filters.
Installation¶
Basic Setup and Session Injection¶
Pass a single database configuration, a sequence of configurations, or a SQLSpec registry to SQLSpecPlugin(..., app) and inject the session into route handlers using Depends(db_ext.provide_session()):
from typing import Annotated, Any
from fastapi import Depends, FastAPI
from sqlspec.adapters.aiosqlite import AiosqliteConfig, AiosqliteDriver
from sqlspec.extensions.fastapi import SQLSpecPlugin
app = FastAPI()
db_ext = SQLSpecPlugin(AiosqliteConfig(connection_config={"database": ":memory:"}), app)
@app.get("/teams")
async def list_teams(db: Annotated[AiosqliteDriver, Depends(db_ext.provide_session())]) -> dict[str, Any]:
return await db.select_one("SELECT 1 AS ok")
SQLSpecPlugin automatically opens configured connection pools when FastAPI starts and closes them when the application shuts down. A request connection is checked out the first time a dependency such as Depends(db_plugin.provide_session()) resolves it, so routes that never touch the database open none, and autocommit modes commit or roll back by response status only when the request used a connection.
Multi-Database Configuration¶
Pass multiple synchronous or asynchronous configurations with distinct session_key, connection_key, and pool_key names under extension_config["fastapi"], then pass the key (or bind_key) to db_plugin.provide_session("<key>"):
from typing import Annotated, Any
from fastapi import Depends, FastAPI
from sqlspec import SQLSpec
from sqlspec.adapters.aiosqlite import AiosqliteConfig, AiosqliteDriver
from sqlspec.adapters.sqlite import SqliteConfig, SqliteDriver
from sqlspec.extensions.fastapi import SQLSpecPlugin
spec = SQLSpec()
spec.add_config(
AiosqliteConfig(
connection_config={"database": ":memory:"},
extension_config={"fastapi": {"session_key": "db", "connection_key": "db_connection", "pool_key": "db_pool"}},
)
)
spec.add_config(
SqliteConfig(
connection_config={"database": ":memory:"},
extension_config={
"fastapi": {"session_key": "etl_db", "connection_key": "etl_connection", "pool_key": "etl_pool"}
},
)
)
app = FastAPI()
db_plugin = SQLSpecPlugin(spec, app)
@app.get("/report")
async def report(
db: Annotated[AiosqliteDriver, Depends(db_plugin.provide_session("db"))],
etl_db: Annotated[SqliteDriver, Depends(db_plugin.provide_session("etl_db"))],
) -> dict[str, list[dict[str, Any]]]:
users = await db.select("SELECT 1 AS id, 'Alice' AS name")
metrics = etl_db.select("SELECT 'metric1' AS name, 100 AS value")
return {"users": users, "metrics": metrics}
Transaction Commit Modes and Options¶
Configure extension_config["fastapi"] (FastAPIConfig, which inherits from StarletteConfig) per database bind; when "fastapi" is omitted, extension_config["starlette"] is inherited automatically (passing both with differing values raises ImproperConfigurationError):
| Commit Mode | Commits On | Rolls Back On | Best For |
|---|---|---|---|
"autocommit" (default) |
Clean HTTP 200–299 responses |
HTTP >= 300 responses (3xx, 4xx, 5xx), raised exceptions, or cancellation |
JSON REST APIs where every 2xx handler mutates state |
"autocommit_include_redirect" |
Clean HTTP 200–399 responses |
HTTP >= 400 responses, raised exceptions, or cancellation |
HTML, HTMX, and Inertia.js form handlers that commit and return 302 / 303 redirects |
"manual" |
Explicit session.commit() calls only |
Uncommitted handler work on clean return, raised exceptions, or cancellation | Explicit service-layer transaction boundaries |
| Key | Type | Default | Description |
|---|---|---|---|
tenant_extractor |
Callable[[Any], Any] |
- | Trusted scope extractor returning a tenant payload, string, UUID, None (no tenant from this source), or an awaitable. Requires tenant_strategy on the same configuration; called on first tenant use, never at request start. |
connection_key |
str |
'db_connection' |
Key for storing the connection in request.state once it is checked out on first access. Default: 'db_connection' |
pool_key |
str |
'db_pool' |
Key for storing connection pool in app.state. Default: 'db_pool' |
session_key |
str |
'db_session' |
Key for storing session in request.state. Default: 'db_session' |
commit_mode |
Literal['manual', 'autocommit', 'autocommit_include_redirect'] |
'autocommit' |
Transaction commit mode. Default: 'autocommit'. manual: No automatic commit; uncommitted work rolls back on release; autocommit: Commit on 2xx, rollback otherwise; autocommit_include_redirect: Commit on 2xx-3xx, rollback otherwise |
extra_commit_statuses |
set[int] |
set() |
Additional HTTP status codes that trigger commit. Default: set() |
extra_rollback_statuses |
set[int] |
set() |
Additional HTTP status codes that trigger rollback. Default: set() |
disable_di |
bool |
False |
Disable built-in dependency injection. Default: False. When True, the Starlette/FastAPI extension will not add middleware for managing database connections and sessions. Users are responsible for managing the database lifecycle manually via their own DI solution. |
enable_sqlcommenter_middleware |
bool |
True |
Control automatic SQLCommenter middleware registration. Default: True. When the driver's :class:~sqlspec.core.statement.StatementConfig has enable_sqlcommenter=True, the middleware is registered automatically. Set to False to explicitly disable middleware registration. |
sqlcommenter_framework |
str |
'starlette' |
Framework name for SQLCommenter attributes. Default: 'starlette'. Set to 'fastapi' when using FastAPI. |
enable_correlation_middleware |
bool |
True |
Enable request correlation ID middleware. Default: True |
correlation_header |
str |
X-Request-ID |
HTTP header to read the request correlation ID from when middleware is enabled. Default: X-Request-ID |
correlation_headers |
tuple[str, ...] or list[str] |
- | Additional HTTP headers to read as correlation ID fallbacks. |
auto_trace_headers |
bool |
True |
Read standard trace context headers as correlation ID fallbacks. Default: True. |
replica_session_key |
str |
- | Request key for a replica session. |
replica_connection_key |
str |
- | Request key for a replica connection. |
routing_session_key |
str |
- | Request key for a routing session. |
default_routing_mode |
Literal['primary', 'auto'] |
'auto' |
Default request routing mode. Default: 'auto'. |
enable_routing_middleware |
bool |
True |
Install request-scoped routing middleware. Default: True. |
routing_header |
str or None |
None |
Trusted application routing header name when explicitly enabled behind a gateway. Default: None. |
primary_pin_cookie |
str or None |
None |
Optional application primary pin cookie name. Default: None. |
primary_pin_secret |
str or bytes or None |
None |
Optional HMAC secret verifying signed primary pin cookies. Default: None. |
replica_pool_key |
str |
- | Request key for the selected replica pool. |
pagination_cursor_secret |
str or bytes |
- | Application-wide secret enabling HMAC-SHA256 signed pagination cursors. |
pagination_cursor_ttl |
int or float or dt.timedelta |
- | Default cursor expiration window in seconds or timedelta. |
pagination_cursor_encrypted |
bool |
- | Encrypt cursor payloads at rest when a cursor secret is configured. |
Set enable_correlation_middleware=False to stop this plugin from reading request IDs or adding them to response headers.
Tenant-Aware Requests¶
With driver_features={"tenant_strategy": "rls"} on a supported adapter, an authorization dependency verifies membership and calls set_request_tenant(request, org_id), and Depends(db_ext.provide_session()) checks out the tenant connection only when a route resolves it. See FastAPI Multi-Tenancy for single-database, separate auth database, and upfront extractor examples, and the Tenant Request Contract for the rules every framework shares.
Declarative Filter Dependencies¶
Use db_ext.provide_filters(FilterConfig(...)) (or from sqlspec.extensions.fastapi import FilterConfig, provide_filters) to generate typed FastAPI Depends callables that parse query parameters directly into StatementFilter lists (LimitOffsetFilter, CursorFilter returning HTTP 422 on malformed cursor tokens, OrderByFilter, SearchFilter, BeforeAfterFilter, and InCollectionFilter). Application-wide pagination_cursor_secret, pagination_cursor_ttl, and pagination_cursor_encrypted configured via FastAPIConfig, SQLSpecPlugin(...), or SQLSPEC_PAGINATION_CURSOR_SECRET / SECRET_KEY environment variables are inherited by both db_ext.provide_filters(...) and standalone provide_filters(...) with per-endpoint signing keys. A cursor secret is required: cursor requests raise ImproperConfigurationError when none resolves. Tokens are bound to the request tenant of every tenant-enabled configuration, so a token from one tenant is rejected for another. Search filters escape %, _, and / by default; set search_escape_wildcards=False in FilterConfig to opt out:
from typing import Annotated, Any
from uuid import UUID
from fastapi import Depends, FastAPI
from sqlspec.adapters.asyncpg import AsyncpgDriver
from sqlspec.core import FilterTypes
from sqlspec.extensions.fastapi import FilterConfig, SQLSpecPlugin, provide_filters
user_filters = provide_filters(
FilterConfig(
id_filter=UUID,
sort_field={"created_at", "name"},
pagination_type="cursor",
pagination_cursor_keys="id",
pagination_size=25,
search="name,email",
search_ignore_case=True,
)
)
def register_user_routes(app: FastAPI, db_ext: SQLSpecPlugin) -> None:
@app.get("/users")
async def list_users(
db: Annotated[AsyncpgDriver, Depends(db_ext.provide_session())],
filters: Annotated[list[FilterTypes], Depends(user_filters)],
) -> list[dict[str, Any]]:
return await db.select(
"SELECT id, name, email, created_at FROM users", *filters
)
Read Replica and Routing Dependencies¶
Use Depends(db_ext.provide_replica_session()) for a reader dependency. The typed factories are provide_async_replica_session and provide_sync_replica_session. Raw connections use provide_replica_connection, provide_async_replica_connection, or provide_sync_replica_connection. key= selects a registered bind or config. provide_routing_session() supplies the lazy routing facade when a handler needs reads and writes.
Add app.add_middleware(SQLSpecRoutingMiddleware) for request routing scopes and header/cookie hints. The middleware is exported from sqlspec.utils.routing. Read sessions keep the same tenant checks and lazy physical checkout as ordinary sessions. See Read Replicas for topology setup.
Connection Lifetime¶
- Normal responses: The request connection is committed or rolled back and released after the response is finalized.
- Streaming responses: The connection stays held until the body finishes or the client disconnects, so the request session works inside a
StreamingResponsebody. - Background work: A
BackgroundTaskkeeps the request connection until it completes, so the task can use the request session.
A session or stream cannot be used after its connection is released; trying to raises ImproperConfigurationError.
Recap¶
- Instantiate
db_ext = SQLSpecPlugin(config, app)(passing a single config, a list of configs, or aSQLSpecregistry) to bind pool lifecycles and request sessions to FastAPI. - Use
Depends(db_ext.provide_session())for single-database routes,Depends(db_ext.provide_session("key"))for multi-database setups,set_request_tenant(request, tenant_id)in auth dependencies for deferred tenant leases, andDepends(db_ext.provide_filters(FilterConfig(...)))for declarative query filters. - See the FastAPI Extension Reference for
SQLSpecPlugin,FastAPIConfig,set_request_tenant, andprovide_filterssignatures.