Appearance
3.14.4 — Dependency Injection with Depends
Nearly every endpoint in the order service starts the same way. Open a database session. Find out who the logged-in user is, which itself needs the database. Load the settings. Check the caller is not over their rate limit. Then, after the endpoint finishes, commit or roll back the session and close it, even if the endpoint crashed. Copy those fifteen lines into forty endpoints and you have forty chances to forget the rollback. FastAPI's answer is dependency injection: an endpoint simply declares what it needs, and the framework works out how to build it, builds it once per request, hands it in, and cleans it up afterwards. This page shows how Depends works, from the simplest case to the dependency graph FastAPI builds behind the scenes, and the one cleanup-timing detail that causes real production bugs.
1. What dependency injection means
In plain words: a function should receive the things it needs, rather than create them itself.
Compare two versions of an endpoint that lists a customer's orders.
python
# Version 1: the endpoint creates what it needs
def list_my_orders(request):
settings = load_settings_from_env() # (1)
db = create_session(settings.database_url) # (2)
user = find_user_from_token(request, db) # (3)
...python
# Version 2: the endpoint declares what it needs
def list_my_orders(user: CurrentUser, db: DbSession):
...(1),(2)and(3)Version 1 knows how to load settings, how to open a session and how authentication works. Every endpoint repeats that knowledge. Changing how sessions are opened means editing every endpoint.
Version 2 only says what it needs. Something else, the framework, decides how to provide it. The pieces it needs are called dependencies, and handing them in is called injecting them. The benefits are concrete:
- No repetition. "How to get the current user" is written once.
- Easy to swap. A different implementation, such as a sandbox payment gateway in a staging environment, can be provided without touching any endpoint.
- Guaranteed cleanup. The thing that opened a resource is responsible for closing it.
- Visible requirements. The function signature says exactly what each endpoint uses, and FastAPI shows them in the API documentation.
2. The simplest dependency
A dependency in FastAPI is just a function, or anything callable. You mark a parameter with Depends(that_function), and FastAPI calls the function and passes in its return value.
python
from typing import Annotated
from fastapi import Depends, FastAPI, Query
app = FastAPI()
def pagination(page: Annotated[int, Query(ge=1)] = 1,
page_size: Annotated[int, Query(ge=1, le=100)] = 20) -> dict: # (1)
return {"offset": (page - 1) * page_size, "limit": page_size}
Page = Annotated[dict, Depends(pagination)] # (2)
@app.get("/orders")
def list_orders(page: Page): # (3)
return page
@app.get("/products")
def list_products(page: Page):
return pagetext
$ curl "localhost:8000/orders?page=3&page_size=10"
{"offset":20,"limit":10}
$ curl "localhost:8000/products?page_size=500"
{"detail":[{"type":"less_than_equal","loc":["query","page_size"],"msg":"Input should be less than or equal to 100", …}]}(1)The dependency has its own parameters, and FastAPI treats them exactly like endpoint parameters. Here they are validated query parameters from 3.14.3.(2)Wrap the dependency in anAnnotatedalias once.Pagenow means "a dict, provided bypagination".(3)Every list endpoint gets validated pagination by declaring one parameter. Both endpoints documentpageandpage_sizein/docs, because FastAPI merges a dependency's parameters into the endpoint's.
Pass the function itself to Depends, without brackets. Depends(pagination()) would call it once at import time, which is wrong.
3. Dependencies that depend on dependencies
A dependency can itself declare dependencies. FastAPI follows the chain and builds them in the right order. That forms a dependency graph. Here is the order service's real shape, with a database session, settings and the current user.
python
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
app = FastAPI()
log = []
def get_settings() -> dict:
log.append("get_settings")
return {"currency": "INR"}
def get_db(): # (1)
log.append("db: open")
try:
yield "db-session" # (2)
log.append("db: commit") # (3)
except Exception as error:
log.append(f"db: rollback ({type(error).__name__})") # (4)
raise
finally:
log.append("db: close") # (5)
DbSession = Annotated[str, Depends(get_db)]
Settings = Annotated[dict, Depends(get_settings)]
def get_current_user(db: DbSession,
x_user: Annotated[str | None, Header()] = None) -> dict: # (6)
log.append(f"get_current_user uses {db}")
if x_user is None:
raise HTTPException(status_code=401, detail="not logged in")
return {"name": x_user}
CurrentUser = Annotated[dict, Depends(get_current_user)]
@app.get("/me")
def me(user: CurrentUser, db: DbSession, settings: Settings, again: Settings): # (7)
log.append("endpoint runs")
return {"user": user, "currency": settings["currency"]}text
$ curl -H "X-User: asha" localhost:8000/me
{"user":{"name":"asha"},"currency":"INR"}
log: ['db: open', 'get_current_user uses db-session', 'get_settings', 'endpoint runs', 'db: commit', 'db: close'](1)A dependency written as a generator withyieldis a dependency with cleanup, built on the same idea as@contextmanagerin 3.13.9.(2)The yielded value is what gets injected.(3)Code afteryieldruns after the endpoint has finished successfully.(4)If the endpoint, or any later dependency, raises, the exception is thrown into the generator at theyield. We roll back and re-raise. Re-raising matters: swallowing it would hide the error from FastAPI's exception handling.(5)finallyalways closes the session.(6)The current-user dependency itself needs the database session.(7)The endpoint asks for the user, the session, and the settings twice.
Now read the log closely. The session was opened once, even though both get_current_user and the endpoint asked for it. get_settings ran once, even though the endpoint asked for it twice. Within one request, FastAPI calls each dependency function only once and reuses the result everywhere it is needed. That per-request caching is why the user lookup and the endpoint share the same database session and the same transaction. If you really need a fresh call each time, write Depends(func, use_cache=False).
Figure 1 shows the graph FastAPI built for /me, and the order it ran the pieces.
yield runs last.Errors flow into the cleanup
What happens when something fails? Two requests show both kinds of failure.
text
$ curl localhost:8000/me # no X-User header
{"detail":"not logged in"} ← status 401
log: ['db: open', 'get_current_user uses db-session', 'db: rollback (HTTPException)', 'db: close']python
@app.get("/boom")
def boom(db: DbSession):
log.append("endpoint raises")
raise ValueError("bad data")text
$ curl localhost:8000/boom
Internal Server Error ← status 500
log: ['db: open', 'endpoint raises', 'db: rollback (ValueError)', 'db: close']In both cases the session was rolled back and closed. The endpoint wrote no cleanup code at all. That is the guarantee you get from putting resource handling in one yield dependency.
4. When does the cleanup run? Before or after the response?
This detail has caused real data-loss bugs, so it gets its own section. By default, the code after yield runs after the response has already been sent to the client. FastAPI lets you choose with the scope argument. Here are three versions of the same dependency, with a marker logged at the exact moment the response body leaves the server.
python
def session():
log.append("open")
yield "s"
log.append("cleanup")
@app.get("/default")
def default_scope(s: Annotated[str, Depends(session)]): ...
@app.get("/function")
def function_scope(s: Annotated[str, Depends(session, scope="function")]): ...
@app.get("/request")
def request_scope(s: Annotated[str, Depends(session, scope="request")]): ...text
/default ['open', 'endpoint', 'RESPONSE SENT', 'cleanup']
/function ['open', 'endpoint', 'cleanup', 'RESPONSE SENT']
/request ['open', 'endpoint', 'RESPONSE SENT', 'cleanup']- With the default, which behaves like
scope="request", cleanup runs after the client already has the response. - With
scope="function", cleanup runs around the endpoint function only, before the response is sent.
Now picture the get_db dependency from section 3, which commits after yield. With the default scope, the client receives 201 Created first, and only then does the commit run. If the commit fails, for example because of a unique-constraint violation or a lost database connection, the client has already been told the order succeeded. The order does not exist.
There are two safe patterns.
- Commit inside the request, in the endpoint or service code, before returning. Use the dependency only to roll back on error and close. This is the most common choice.
- Use
scope="function"for dependencies whose cleanup can fail in ways the client must hear about.
The default exists for a good reason: some dependencies must stay open while the response is being sent, such as a database session used by a streaming response (3.14.8). Just make the choice deliberately.
5. Classes and callable objects as dependencies
Depends accepts anything callable. That gives two useful patterns.
A class as a dependency
Calling a class creates an instance, so a class can be a dependency. FastAPI reads its __init__ parameters exactly like a function's.
python
class OrderFilters:
def __init__(self, status: str | None = None, min_total: float = 0.0):
self.status = status
self.min_total = min_total
@app.get("/reports/orders")
def order_report(filters: Annotated[OrderFilters, Depends()]): # (1)
return {"status": filters.status, "min_total": filters.min_total}text
$ curl "localhost:8000/reports/orders?status=paid&min_total=500"
{"status":"paid","min_total":500.0}(1)An emptyDepends()means "use the type annotation as the dependency". It saves writingOrderFilterstwice. The result is a real object with attributes, which editors can autocomplete.
A configurable dependency: an instance with __call__
Sometimes a dependency needs settings, such as "at most 5 requests per minute here, 100 there". A function cannot take extra settings without FastAPI treating them as request parameters. An instance of a class with __call__ solves it: the settings go into __init__, and FastAPI calls the instance on each request, reading the parameters of __call__.
python
import time
from collections import defaultdict, deque
from fastapi import HTTPException, Request
class RateLimit:
def __init__(self, times: int, per_seconds: int): # (1)
self.times = times
self.per_seconds = per_seconds
self.hits: dict[str, deque] = defaultdict(deque)
def __call__(self, request: Request) -> None: # (2)
key = request.client.host if request.client else "unknown"
now = time.monotonic()
window = self.hits[key]
while window and now - window[0] > self.per_seconds: # (3)
window.popleft()
if len(window) >= self.times:
raise HTTPException(status_code=429, detail="too many requests") # (4)
window.append(now)
@app.post("/password-reset", dependencies=[Depends(RateLimit(times=3, per_seconds=60))]) # (5)
def password_reset():
return {"sent": True}(1)Settings are fixed once, when the route is defined.(2)FastAPI calls the instance per request and injectsRequest.(3)Drop timestamps older than the window. Adequemakes removing from the front O(1) (3.13.3).(4)429 Too Many Requests is the standard status for rate limiting.(5)This dependency returns nothing useful, so it goes in the decorator'sdependencieslist instead of the parameter list. It still runs, and can still reject the request.
This limiter keeps its counts in the memory of one process, so with four worker processes the real limit is four times higher, and the counts reset on every deploy. Production rate limits live in a shared store such as Redis. Part 10 covers the algorithms. The dependency shape stays exactly the same.
6. Dependencies for a whole router or app
Some requirements apply to every endpoint in a group, such as "every admin endpoint needs an admin user" or "every partner endpoint needs a valid API key". Put the dependency on the router, or on the whole app.
python
from fastapi import APIRouter, Header, HTTPException
def require_partner_key(x_api_key: Annotated[str, Header()]) -> None:
if x_api_key != "partner-secret": # a real check compares a stored hash
raise HTTPException(status_code=403, detail="invalid API key")
partners = APIRouter(prefix="/partners", dependencies=[Depends(require_partner_key)]) # (1)
@partners.get("/catalogue")
def catalogue():
return {"items": 1200}
app.include_router(partners)text
$ curl localhost:8000/partners/catalogue
{"detail":[{"type":"missing","loc":["header","x-api-key"],"msg":"Field required", …}]} ← 422
$ curl -H "X-API-Key: wrong" localhost:8000/partners/catalogue
{"detail":"invalid API key"} ← 403
$ curl -H "X-API-Key: partner-secret" localhost:8000/partners/catalogue
{"items":1200}(1)Every route on this router runs the check first. A new partner endpoint added next year is protected automatically, because nobody has to remember to add the check.
FastAPI(dependencies=[...]) does the same for every route in the app. 3.14.7 builds real authentication on exactly this pattern, using Security, a variant of Depends that also records the permissions an endpoint needs in the API documentation.
7. Swapping an implementation
Because endpoints only declare what they need, the app can be told to provide something else. app.dependency_overrides is a dict from the original dependency to a replacement.
python
class PaymentGateway:
def charge(self, order_id: str, paise: int) -> str:
raise NotImplementedError
class RazorpayGateway(PaymentGateway):
def charge(self, order_id, paise):
return f"rzp_{order_id}"
class SandboxGateway(PaymentGateway):
def charge(self, order_id, paise):
return f"sandbox_{order_id}"
def get_gateway() -> PaymentGateway:
return RazorpayGateway()
@app.post("/orders/{order_id}/pay")
def pay(order_id: str, gateway: Annotated[PaymentGateway, Depends(get_gateway)]):
return {"payment_id": gateway.charge(order_id, 49900)}
app.dependency_overrides[get_gateway] = SandboxGateway # (1)text
$ curl -X POST localhost:8000/orders/ORD-7/pay
{"payment_id":"sandbox_ORD-7"}(1)Every endpoint that depended onget_gatewaynow gets aSandboxGateway, with no change to any endpoint.
In real services, the choice between implementations usually comes from settings inside get_gateway itself, which is clearer than editing the overrides dict. But the mechanism shows the payoff of the design: the endpoint depends on the idea of a payment gateway, not on one company's client. Part 9 calls this programming to an interface.
8. How FastAPI resolves dependencies
Putting it together, here is what happens.
Once, at start-up, when @app.get runs:
- FastAPI reads the endpoint's signature, as in 3.14.3.
- For every
Depends(x), it readsx's signature too, recursively, building a tree. That tree is the dependant you saw in 3.14.3, with sub-dependants nested inside it. - It merges every parameter from the whole tree, such as query parameters, headers and cookies, into one list, for validation and for the documentation.
On every request:
- Walk the tree depth-first. Dependencies are resolved before the things that need them.
- Keep a per-request cache keyed by the dependency function. If a dependency was already solved in this request, reuse its value.
- For a
yielddependency, run it up to itsyield, take the value, and register the rest of the generator with an exit stack, theAsyncExitStackcousin ofExitStackfrom 3.13.9. - Call the endpoint with all the values.
- Unwind the exit stack in reverse order, throwing in any exception, at the point chosen by each dependency's scope.
Plain def dependencies run in the thread pool, exactly like def endpoints, and async def dependencies run on the event loop. The same rule from 3.14.3 applies: never block inside an async def dependency.
What the interviewer will push on
"What is dependency injection, and how does FastAPI implement it?" A function receives what it needs instead of creating it. In FastAPI, Depends(callable) marks a parameter. At start-up FastAPI builds a tree from the signatures, and per request it resolves the tree depth-first with a per-request cache. The tell is mentioning the cache: a dependency used in three places runs once per request.
"How do you manage a database session per request?" A yield dependency that opens the session, yields it, rolls back on exception and closes in finally. The senior detail is cleanup timing: by default code after yield runs after the response is sent, so commit inside the request or use scope="function", or a failed commit will follow a success response.
"How would you apply authentication to every endpoint in a group?" Router-level dependencies=[Depends(require_user)], or app-level for everything. Mention that new endpoints are then protected by default.
"How do you pass configuration into a dependency?" A class instance with __call__: configuration in __init__, request data in __call__. Or a factory function that returns a dependency function, which is a closure (3.13.4).
"What does Depends() with no argument do?" It uses the parameter's type annotation as the dependency, which is useful for classes whose __init__ parameters are query parameters.
Something to volunteer that nobody asks for: an in-memory rate limiter or cache inside a dependency is per process, so with four Uvicorn workers the limit is four times higher and resets on every deploy. Shared state for limits belongs in Redis or the database. Saying this shows you think about how the code actually runs in production.
Recall
- Dependency injection: a function declares what it needs, and the framework provides it. Benefits: no repetition, easy swapping, guaranteed cleanup, visible requirements.
Depends(func)(pass the function, do not call it). A dependency's own parameters are validated like endpoint parameters and documented. UseAnnotatedaliases such asDbSession = Annotated[Session, Depends(get_db)].- Dependencies can depend on dependencies, forming a dependency graph, solved depth-first with per-request caching (
use_cache=Falseto opt out). - A
yielddependency gives setup, value and cleanup. Exceptions are thrown in at theyield, so roll back and re-raise. By default cleanup runs after the response is sent.scope="function"runs it before. Commit inside the request. Depends()with no argument uses the type. A callable instance (__call__) gives configurable dependencies such asRateLimit(times=3, per_seconds=60).dependencies=[...]on a route, router or app runs checks without injecting a value.app.dependency_overridesswaps an implementation.- Internals: the tree is built at start-up from signatures. Per request, it is resolved depth-first,
yielddependencies are pushed onto an exit stack, anddefdependencies run in the thread pool.
Self-test: Why did get_db run once when two things asked for it? What exact sequence of log lines appears when the endpoint raises? Why can committing after yield tell a client "created" for an order that was never saved? How do you give a dependency a setting such as "3 per minute"?
Quiz Bank
FoundationalWhat is the difference between putting a dependency in an endpoint's parameters and in the decorator's dependencies list?
As a parameter, user: Annotated[User, Depends(get_current_user)], the dependency runs and its return value is injected so the endpoint can use it. In the decorator's dependencies=[Depends(check)], or on a router or the app, the dependency still runs before the endpoint and can still reject the request by raising, but its return value is discarded. Use the list for checks whose only job is to allow or deny, such as an API-key check or a rate limit, so the endpoint signature is not cluttered with unused parameters.
AppliedTwo dependencies both need the current user, and the user lookup hits the database. Is the user loaded twice per request?
No. FastAPI caches each dependency's result for the duration of one request, keyed by the dependency function. The first time get_current_user is needed, it runs and its result is stored. Every later use in the same request, whether in another dependency or in the endpoint, gets the same object. This also means they share any sub-dependency, such as the database session. Pass use_cache=False only if you really need a fresh call. The cache never spans requests, so each request still authenticates.
InterviewWrite a yield dependency for a SQLAlchemy session, and explain the cleanup timing problem.
python
async def get_session():
async with session_factory() as session:
try:
yield session
except Exception:
await session.rollback()
raiseThe session is opened before the endpoint, injected, rolled back if anything raises, and closed when the async with block ends. The timing problem: by default, code after yield runs after the response has been sent. If commit lived after the yield, a failed commit would happen after the client had already received a success response, so the client believes an order exists that was never saved. Commit explicitly inside the endpoint or service before returning, so commit failures become error responses. Or declare the dependency with Depends(get_session, scope="function"), so its exit code runs before the response.
StaffA codebase has dependencies that call other dependencies seven levels deep, and nobody can tell what an endpoint actually needs. How would you restructure it?
Deep dependency chains usually mean dependencies are doing business logic. Keep dependencies for request-scoped plumbing only: settings, database session, current user, permissions and pagination. Each should be short, and the chains no more than two or three levels. Move business decisions into plain service classes that receive their collaborators, such as a repository and a payment gateway, through their constructors, and are created by a single dependency. Endpoints then depend on the user, the session and one service object. Use Annotated aliases with clear names, so signatures read like documentation. Put cross-cutting checks on routers. The result is that every endpoint's signature lists its real inputs, and the business logic can be read without knowing FastAPI at all.
Next: dependencies run around one endpoint. Some work must wrap every request, such as logging, timing, CORS and error formatting, and some must run once when the server starts. 3.14.5 covers exception handlers, middleware, the lifespan and background tasks.