Dependency Injection
FastAPI Depends composes per-request providers for settings, databases, and auth.
Search across all documentation pages
FastAPI Depends composes per-request providers for settings, databases, and auth.
Quick-reference recipe card - copy-paste ready.
from collections.abc import Generator
from fastapi import Depends, FastAPI
app = FastAPI()
def get_db() -> Generator[dict, None, None]:
db = {"items": []}
yield db
@app.get("/items")
def list_items(db: dict = Depends(get_db)):
return db["items"]When to reach for this:
from fastapi import Depends, FastAPI, Header, HTTPException
app = FastAPI()
def get_settings():
return {"api_key": "dev"}
def verify(x_api_key: str | None = Header(default=None), settings=Depends(get_settings)):
if x_api_key != settings["api_key"]:
raise HTTPException(401)
@app.get("/secure", dependencies=[Depends(verify)])
def secure() -> dict[str, str]:
return {"ok": "true"}What this demonstrates:
yield dependencies run teardown after the response.app.dependency_overrides in tests.| Alternative | Use When | Don't Use When |
|---|---|---|
| Alternate framework in this cookbook | Team standard or existing monolith | Greenfield API with different constraints |
| Managed BaaS | CRUD-only MVP | Custom auth, workflows, or compliance needs |
| gRPC | Internal high-performance RPC | Public HTTP clients and browser access |
Use it when the patterns and trade-offs on this page match your API or data boundary.
Skipping validation, timeouts, or explicit error contracts at the HTTP edge.
Use the framework test client, override dependencies, and assert status plus JSON shape.
Yes - examples target Python 3.14 with pinned framework versions from the stack footer.
Validate and serialize at boundaries; keep services working with typed domain objects.
Prefer async routes when I/O dominates; keep CPU work small or offload to workers.
Thin handlers; services own rules; repositories own queries.
Publish OpenAPI or schema docs that match response models in code.
Explicit URL or header versioning with deprecation windows - avoid silent breaks.
Follow the Related links for the next layer of depth in this section.
Authenticate callers, authorize per resource, rate-limit, and never log secrets.
Measure DB and upstream latency before swapping frameworks.
Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.
Reviewed by Chris St. John·Last updated Jul 19, 2026