FastAPI#
SQLSpec provides a FastAPI extension that wires database sessions into the request lifecycle using standard dependency injection. The extension manages connection pools and ensures proper cleanup between requests.
Installation#
Install SQLSpec with the FastAPI extra:
uv add "sqlspec[fastapi]"
pip install "sqlspec[fastapi]"
poetry add "sqlspec[fastapi]"
pdm add "sqlspec[fastapi]"
Basic Setup#
Create a SQLSpec instance, register your database config, and attach the plugin to your
FastAPI app. The plugin provides a provide_session dependency that yields a session
for each request. Configure FastAPI-specific options under extension_config["fastapi"].
fastapi basic setup#from fastapi import Depends, FastAPI
from sqlspec import SQLSpec
from sqlspec.adapters.aiosqlite import AiosqliteConfig, AiosqliteDriver
from sqlspec.extensions.fastapi import SQLSpecPlugin
sqlspec = SQLSpec()
sqlspec.add_config(AiosqliteConfig(connection_config={"database": ":memory:"}))
app = FastAPI()
db_ext = SQLSpecPlugin(sqlspec, app)
@app.get("/teams")
async def list_teams(db: Annotated[AiosqliteDriver, Depends(db_ext.provide_session())]) -> dict[str, Any]:
result = await db.execute("select 1 as ok")
return result.one()
Key Concepts#
- Dependency Injection
Use
Depends(db_ext.provide_session())to inject a session into your route handlers. The session is scoped to the request and automatically cleaned up afterward.- Session Lifecycle
Sessions are created at the start of each request and closed when the request completes. For long-running operations, consider using background tasks with their own session.
- Multiple Databases
Register multiple configs with different names and create separate dependencies for each:
sqlspec.add_config(primary_config, name="primary") sqlspec.add_config(analytics_config, name="analytics") primary_dep = db_ext.provide_session("primary") analytics_dep = db_ext.provide_session("analytics")