Lesson 11 of 59Building a real API
Dependency Injection
Share database sessions, auth and settings across routes with Depends, and swap them out in tests.
Real routes need things before they can do their job: a database session, the logged-in user, the app's settings, pagination parameters. Copying that setup into every route is how you end up with forty slightly different auth checks. FastAPI's dependency injection system lets you write each piece once, declare which routes need it, and replace it in tests with one line. It is also a favourite topic in FastAPI interviews.
The problem Depends solves
Here are two routes that both need pagination and a database session, written without help:
@app.get("/todos")
def list_todos(limit: int = 20, offset: int = 0):
limit = min(limit, 100)
db = SessionLocal()
try:
return db.query(Todo).offset(offset).limit(limit).all()
finally:
db.close()
@app.get("/notes")
def list_notes(limit: int = 20, offset: int = 0):
limit = min(limit, 100) # copied
db = SessionLocal() # copied
try:
return db.query(Note).offset(offset).limit(limit).all()
finally:
db.close() # copied, and easy to forgetDependency injection (DI) flips this around. Instead of a function creating what it needs, it declares what it needs, and something else (the framework) creates it and passes it in. In FastAPI the declaration is Depends.
Your first dependency
A dependency is just a function. FastAPI calls it before your route and passes the return value in. A dependency can take its own parameters, and they are read from the request exactly like a route's: query, path, headers, body.
from typing import Annotated
from fastapi import Depends, Query
from pydantic import BaseModel
class Page(BaseModel):
limit: int
offset: int
def get_page(
limit: Annotated[int, Query(ge=1, le=100)] = 20,
offset: Annotated[int, Query(ge=0)] = 0,
) -> Page:
return Page(limit=limit, offset=offset)
PageDep = Annotated[Page, Depends(get_page)]from app.deps import PageDep
@app.get("/todos")
def list_todos(page: PageDep):
return repo.list(limit=page.limit, offset=page.offset)
@app.get("/notes")
def list_notes(page: PageDep):
return notes.list(limit=page.limit, offset=page.offset)Both routes now accept ?limit= and ?offset=, both validate them the same way, and /docs shows the parameters on both. Pass the function itself, Depends(get_page), not Depends(get_page()): FastAPI does the calling.
The PageDep = Annotated[...] alias is the recommended style. Each route just writes page: PageDep, and your editor knows page is a Page.
page: Annotated[Page, Depends(get_page)] on a route?Dependencies that depend on dependencies
Dependencies can declare their own dependencies. FastAPI builds the whole graph, resolves it from the leaves up, and caches each dependency within a request: if two things need get_db, they share one session.
def get_db():
... # yields a database session, see below
def get_token(authorization: Annotated[str, Header()]) -> str:
return authorization.removeprefix("Bearer ")
def get_current_user(token: Annotated[str, Depends(get_token)], db: Annotated[Session, Depends(get_db)]) -> User:
user = db.get(User, decode_user_id(token))
if user is None:
raise HTTPException(status_code=401, detail="Not authenticated")
return user
CurrentUser = Annotated[User, Depends(get_current_user)]
DB = Annotated[Session, Depends(get_db)]
@app.delete("/todos/{todo_id}", status_code=204)
def delete_todo(todo_id: int, user: CurrentUser, db: DB):
...FastAPI reads the route's signature: it needs get_current_user and get_db before it can run.
In one request to delete_todo above, how many times is get_db called?
# delete_todo depends on get_current_user and get_db # get_current_user depends on get_token and get_db # (default settings, no use_cache=False)
Yield dependencies: setup and teardown
A database session must be closed after the request, even if the route raised an error. A dependency written as a generator handles that: code before yield is setup, the yielded value is injected, and code after yield runs once the route is done.
from collections.abc import Iterator
from sqlalchemy.orm import Session
from app.db.engine import SessionLocal
def get_db() -> Iterator[Session]:
db = SessionLocal()
try:
yield db # the route runs while we are paused here
db.commit() # no exception: save the work
except Exception:
db.rollback() # something failed: undo it
raise
finally:
db.close() # always give the connection backThis is the same shape as a context manager from the Python course, and that is no accident: FastAPI wraps your generator in one. If several yield dependencies are active, their teardowns run in reverse order of setup, like nested with blocks.
Order what happens during a request that uses the get_db yield dependency and succeeds.
- Tap the steps below in the right order.
Yield dependencies and exceptions
Yield dependencies are where FastAPI has changed behaviour most often, and answers copied from 2022 are wrong today. The short history:
Before 0.106
After the response
Exit code ran after the response was sent. You could not raise an HTTPException after yield, but background tasks could still use the session.
0.106
Before the response
Exit code moved before the response, so it could change the outcome. Background tasks could no longer use a yielded session, because it was already closed.
0.110
You must re-raise
Exceptions from the route are thrown into the dependency at the yield. If you catch one, you must raise it again (or raise a new one).
0.118
After the response again, by default
Exit code runs after the response is sent, so streaming responses can keep using the session. A failure after yield can no longer change the status the client got.
0.121
You choose: scope
`Depends(dep, scope="function")` runs the exit code right after the route returns, before the response. The default, `scope="request"`, keeps the 0.118 behaviour.
Rule 1: re-raise what you catch. When the route raises, FastAPI throws that exception into your generator at the yield. If your except swallows it, FastAPI never gets an exception to turn into a response, and it has no response either. You get a FastAPIError: Response not awaited and a 500, even when the route raised a perfectly good HTTPException(404). Always end an except block in a yield dependency with raise:
def get_db() -> Iterator[Session]:
db = SessionLocal()
try:
yield db
except Exception:
db.rollback()
raise # without this, a 404 from the route becomes a 500
finally:
db.close()Rule 2: know when your exit code runs. With the default scope="request", the order is: setup, route, response sent, exit code. That is right for cleanup that cannot fail in a way the client cares about: closing a session, releasing a lock, closing a file a streaming response was reading. It is wrong for anything that decides the outcome, and a commit decides the outcome. Run this to see the difference:
Press Run (⌘ Enter) to see what happens.The same thing happens in real FastAPI: a yield dependency that raises after yield produces a 200 for the client and an error only in your logs. There are two good fixes, and teams pick one and use it everywhere:
# Fix 1: the dependency only manages the session; the service commits explicitly
def get_db() -> Iterator[Session]:
with SessionLocal() as db:
yield db
def create_todo(db: Session, data: TodoCreate) -> Todo:
todo = Todo(**data.model_dump())
db.add(todo)
db.commit() # fails here, inside the route, so the client gets an error
return todo
# Fix 2: keep commit-after-yield, but finish before the response (FastAPI 0.121+)
DB = Annotated[Session, Depends(get_db_with_commit, scope="function")]Fix 1 makes the transaction boundary visible in the code that owns the business rule, which is why Transactions and Concurrency Bugs in Web Apps uses it. Fix 2 is the smaller change to an existing codebase. One constraint: a scope="request" dependency cannot depend on a scope="function" one (FastAPI raises DependencyScopeError at startup), because the inner one would already be closed when the outer one still needs it.
Using handle and create_todo from the block above, what does this print?
status = handle(create_todo) print(status, log[-1])
except Exception: log.warning(...) with no raise. A route using it raises HTTPException(status_code=404). What does the client get?Build a resolver yourself
Here is a working mini version of FastAPI's resolver. It inspects default values for Depends, resolves them recursively, caches per request, and supports overrides.
Press Run (⌘ Enter) to see what happens.calls shows get_db ran once even though two functions asked for it. The override replaced it everywhere in the graph, including inside get_current_user, without touching any route code.
Overriding dependencies in tests
That last line is the reason DI matters so much. In a test you do not want a real database, a real payment provider or a real logged-in user. FastAPI keeps a dict, app.dependency_overrides, that maps a dependency to a replacement:
from fastapi.testclient import TestClient
from app.deps import get_current_user
from app.main import app
def fake_user():
return User(id=1, username="ada")
def test_delete_requires_nothing_else():
app.dependency_overrides[get_current_user] = fake_user
client = TestClient(app)
response = client.delete("/todos/1")
assert response.status_code == 204
app.dependency_overrides.clear()No login flow, no token, no header. The route code is unchanged; only what gets injected differs. You will use this all the time in the testing lesson.
app.dependency_overrides[get_db] = get_test_db. get_current_user also depends on get_db. Which session does get_current_user receive?Match each FastAPI feature to its use.
Class-based dependencies and callables with state
Depends accepts any callable, not only functions. Two patterns come up constantly.
A class as a dependency: FastAPI reads the parameters of __init__ from the request, calls the class, and injects the instance. When the type and the dependency are the same class, Depends() with no argument is a shortcut:
class Pager:
def __init__(
self,
limit: Annotated[int, Query(ge=1, le=100)] = 20,
offset: Annotated[int, Query(ge=0)] = 0,
):
self.limit = limit
self.offset = offset
@app.get("/todos")
def list_todos(page: Annotated[Pager, Depends()]): # same as Depends(Pager)
...A configured instance with __call__: you create the object once, with settings, and FastAPI calls it per request. This is how you build parameterised dependencies, such as a rate limit with a different budget per route, or a permission check for a given role:
class RequireRole:
def __init__(self, role: str):
self.role = role # set once, at import time
def __call__(self, user: CurrentUser) -> User:
if self.role not in user.roles:
raise HTTPException(status_code=403, detail="Forbidden")
return user
require_admin = RequireRole("admin")
@app.delete("/users/{user_id}")
def delete_user(user_id: int, admin: Annotated[User, Depends(require_admin)]):
...The instance lives for the whole process, so anything stored on self is shared by every request. Configuration is fine there. Mutable state (a hit counter, an in-memory cache) is shared across concurrent requests, and def dependencies run in a thread pool, so two threads can update it at once. It is also per process, so with four workers you have four counters. For real rate limits use Redis, as Rate Limits and Quotas shows.
Dependency caching within a request
You saw that get_db runs once per request even when three things ask for it. The precise rule: within one request, FastAPI caches each dependency's result by the callable plus its security scopes. Two consequences matter at work.
The cache is per request, never across requests. If you want a value built once per process, such as settings or an HTTP client, the dependency must return something cached elsewhere: an @lru_cache function (which Settings and Config uses for settings) or an object created in the lifespan.
use_cache=False asks for a fresh call. Use it when two parts of the request genuinely need independent values, for example two separate sessions so that an audit log entry commits even if the main transaction rolls back. It is rarely needed, and using it on get_db by accident is how one request ends up holding two connections from the pool and deadlocking itself when the pool is small.
Router- and app-level dependencies
Some dependencies are needed for their side effect, not their value: "the caller must be an admin", "record this call in the audit log", "check the API key". Declaring an unused parameter on every route is noisy and easy to forget on the next route. Instead, attach the dependency at a higher level with dependencies=[...]:
from fastapi import APIRouter, Depends
router = APIRouter(
prefix="/admin",
tags=["admin"],
dependencies=[Depends(require_admin), Depends(audit_log)],
)
@router.get("/users") # require_admin and audit_log run first
def list_all_users(db: DB): ...
@app.post("/webhooks/stripe", dependencies=[Depends(verify_stripe_signature)])
def stripe_webhook(...): ... # one route
app = FastAPI(dependencies=[Depends(reject_banned_ips)]) # every routeThey run before the route's own dependencies, in order: app, then router, then the decorator. Their return values are thrown away, but their exceptions stop the request, which is exactly what a guard should do. You can also add dependencies when including a router: app.include_router(router, dependencies=[...]), handy when the same router is mounted in two places with different rules. A router-level guard is the safest way to protect a whole area of the API, because a new route added to the router is protected automatically. Note that dependency_overrides replace these dependencies too, which is how tests skip the admin check.
Security dependencies and scopes
Security is Depends with one extra: a list of scopes that the dependency can read. FastAPI adds the scopes to the OpenAPI schema, so /docs shows which permissions each route needs, and passes them to the dependency through a SecurityScopes parameter. Scopes from every level of the graph are collected, so a route asking for orders:write through a shared get_current_user gets a check for exactly that scope.
from fastapi import Depends, HTTPException, Security
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
oauth2 = OAuth2PasswordBearer(
tokenUrl="auth/token",
scopes={"orders:read": "Read orders", "orders:write": "Create and change orders"},
)
def get_current_user(scopes: SecurityScopes, token: Annotated[str, Depends(oauth2)]) -> User:
claims = decode_token(token) # raises 401 if invalid
granted = set(claims.get("scope", "").split())
for needed in scopes.scopes:
if needed not in granted:
raise HTTPException(
status_code=403,
detail=f"Missing scope {needed}",
headers={"WWW-Authenticate": f'Bearer scope="{scopes.scope_str}"'},
)
return load_user(claims["sub"])
@app.get("/orders")
def list_orders(user: Annotated[User, Security(get_current_user, scopes=["orders:read"])]): ...
@app.post("/orders")
def create_order(user: Annotated[User, Security(get_current_user, scopes=["orders:write"])]): ...Note the status codes: a missing or invalid token is a 401, a valid token without the scope is a 403. Because the cache key includes the scopes, the two Security uses above are cached separately. Scopes describe what a token may do, which suits OAuth clients and API keys. What a user may do to a particular record (only their own orders, only orders in their tenant) is a different question; Authorization: Roles, Permissions and Ownership covers it, and Authentication and JWTs covers issuing the tokens.
Practice
A dependency resolver
Write the engine behind Depends. The Depends class is given. Write resolve(fn, overrides=None) that calls fn and returns its result, where:
- Every parameter of
fnwhose default value is aDepends(dep)receives the result of resolvingdep(recursively:depmay haveDependsparameters too). - Parameters with any other default are left alone (not passed), so they keep their default.
- Per-request cache: during one call to
resolve, each dependency function runs at most once, and every parameter that needs it gets the same result. Separate calls toresolvedo not share a cache. overridesmaps a dependency function to a replacement. Wheneverdepis inoverrides, call the replacement instead, at any depth.
def get_db():
return "session"
def get_user(db=Depends(get_db)):
return f"user from {db}"
def route(user=Depends(get_user), db=Depends(get_db)):
return [user, db]
resolve(route) # ["user from session", "session"]
resolve(route, {get_db: lambda: "fake"}) # ["user from fake", "fake"]inspect.signature(fn).parameters gives you each parameter and its .default.
- dependency injection
- A function declares what it needs and the framework creates and passes it in, instead of the function building it.
- Depends
- Marks a parameter as provided by a dependency function:
Annotated[Session, Depends(get_db)]. - yield dependency
- A generator dependency: code before
yieldis setup, code after it is teardown that always runs. - dependency_overrides
- A dict on the app mapping a dependency to a replacement, used to inject fakes in tests.
- per-request cache
- Within one request, each dependency runs once and its result is shared by everything that asks for it.
- dependency scope
scope="request"(default) runs yield exit code after the response is sent;scope="function"runs it before.- Security
- A
Dependsthat also carries OAuth scopes, read by the dependency throughSecurityScopesand shown in OpenAPI. - router dependency
- A dependency in
APIRouter(dependencies=[...])that runs for every route in the router, for its side effect only.