Difficulty: Intermediate
How does FastAPI's dependency injection system work with Depends(), and what problems does it solve?
FastAPI's dependency injection lets a path operation declare what it needs, such as a database session, the current user or pagination values, by adding a parameter wrapped in Depends(some_callable). For every request FastAPI resolves the whole dependency graph: it calls each dependency with values pulled from the request, caches results within that request, and passes the return values into your handler.
A dependency is any callable: a function, an async function or a class. FastAPI inspects its signature exactly like a handler, so a dependency can itself take query params, headers, a body or other dependencies.
get_token reads the Authorization header).get_current_user uses the token, require_admin uses the user).Depends(dep, use_cache=False) to opt out.HTTPException, the handler never runs.Parameters a dependency reads also appear in the OpenAPI docs, so skip and limit from a shared pagination dependency show up on every route that uses it.
A dependency that uses yield acts like a context manager: code before yield is setup, the yielded value is injected, and code after yield is teardown. This is the standard pattern for a database session: open it, yield it, then commit or roll back and close it in finally. Wrap the yield in try/except if you want to roll back on errors raised by the handler. Do not use the yielded session inside BackgroundTasks; open a fresh one there, because teardown timing relative to the response has changed across FastAPI versions.
| Level | Syntax | Typical use |
|---|---|---|
| Parameter | user: Annotated[User, Depends(get_current_user)] | You need the value |
| Decorator | @app.get(..., dependencies=[Depends(verify_api_key)]) | Run a check, ignore the value |
| Router | APIRouter(dependencies=[Depends(require_admin)]) | Protect a whole group, e.g. /admin |
| App | FastAPI(dependencies=[...]) | Global checks |
app.dependency_overrides[get_db] = get_test_db swaps real resources for fakes without touching handlers.Depends(get_db), not Depends(get_db()).def dependencies run in the threadpool, just like sync handlers.Depends() with no argument on a class-typed parameter uses the class itself as the dependency.Annotated type aliases (CurrentUser = Annotated[User, Depends(get_current_user)]) to avoid repeating yourself; this is the style FastAPI recommends since 0.95.from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, Query
app = FastAPI()
def get_db():
db = {"connected": True} # stand-in for SessionLocal()
try:
yield db # injected into the handler
finally:
db["connected"] = False # teardown: close the session
def get_current_user(authorization: Annotated[str, Header()]):
if authorization != "Bearer secret":
raise HTTPException(status_code=401, detail="Invalid token")
return {"id": 7, "role": "admin"}
def require_admin(user: Annotated[dict, Depends(get_current_user)]):
if user["role"] != "admin":
raise HTTPException(status_code=403, detail="Admins only")
return user
class Pagination: # a class works as a dependency too
def __init__(self, skip: int = 0, limit: Annotated[int, Query(le=100)] = 20):
self.skip, self.limit = skip, limit
DB = Annotated[dict, Depends(get_db)]
Admin = Annotated[dict, Depends(require_admin)]
@app.get("/admin/orders")
def list_orders(db: DB, admin: Admin, page: Annotated[Pagination, Depends()]):
return {"admin": admin["id"], "skip": page.skip, "limit": page.limit}
get_current_user runs once even though require_admin depends on it. Annotated aliases keep handler signatures short.
from fastapi.testclient import TestClient
from main import app, get_current_user
def fake_admin():
return {"id": 1, "role": "admin"}
app.dependency_overrides[get_current_user] = fake_admin
client = TestClient(app)
def test_admin_orders():
r = client.get("/admin/orders")
assert r.status_code == 200
app.dependency_overrides.clear()
dependency_overrides replaces a dependency everywhere it is used, including inside other dependencies.
Depends, dependency injection, yield dependencies, dependency caching, dependency_overrides