Dependencies
Dependencies are FastAPI's mechanism for sharing logic: database sessions, authentication, pagination, background work. You write a plain function, declare it with Depends(), and FastAPI calls it before your endpoint, injects the result, and runs cleanup afterwards. Dependencies compose: a dependency can have its own dependencies.
A Basic Dependency
from fastapi import Depends, FastAPI
app = FastAPI()
def get_db():
db = connect()
try:
yield db
finally:
db.close()
@app.get("/items/")
def list_items(db = Depends(get_db)):
return db.fetch_items()
The yield statement is a sub-dependency with cleanup: everything after yield runs after the response is sent (finally blocks included).
Dependencies with Parameters
Dependency functions can declare their own parameters (query, path, body) and their own dependencies - they are mini-endpoints:
from typing import Annotated
from pydantic import Field
def query_params(
skip: Annotated[int, Field(ge=0)] = 0,
limit: Annotated[int, Field(ge=1, le=100)] = 20,
):
return {"skip": skip, "limit": limit}
@app.get("/items/")
def list_items(params: dict = Depends(query_params)):
return {"page": params}
Auth Example
from fastapi import Header, HTTPException, status
def current_user(authorization: str | None = Header(default=None)):
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Not authenticated")
token = authorization.removeprefix("Bearer ")
return {"token": token}
@app.get("/me/")
def me(user: dict = Depends(current_user)):
return user
Overriding Dependencies (Testing)
app.dependency_overrides maps a dependency to a replacement, which is how you swap the real database for a test fixture without touching endpoint code:
app.dependency_overrides[get_db] = lambda: test_db
# run tests
app.dependency_overrides.clear()
When to Use Dependencies
- Resource management: database sessions, HTTP clients (open/close around the request).
- Cross-cutting concerns: authentication, rate limiting, audit logging.
- Shared parameter groups: pagination, locale, feature flags.
- Anything you would otherwise copy-paste into several endpoints.
Summary
Dependencies are plain functions injected with Depends() that run before your endpoint, can declare their own parameters and sub-dependencies, support cleanup via yield/finally, and can be overridden for testing. Use them for sessions, auth, pagination, and any reusable request-scoped logic.