Full answer
Dependency injection means a function receives what it needs instead of creating it. In FastAPI:
def pagination(page: int = 1, size: int = 20):
return {"offset": (page - 1) * size, "limit": size}
@app.get("/books")
def list_books(p: Annotated[dict, Depends(pagination)]): ...How it works per request:
- FastAPI inspects the endpoint signature and finds
Depends(pagination). - It inspects
pagination's signature:pageandsizeare query parameters, so they are read and validated like endpoint parameters and appear in the OpenAPI docs. - It calls
pagination(...)and passes the result asp.
Dependencies can depend on other dependencies, forming a graph: get_current_user depends on get_token and get_db; require_admin depends on get_current_user. FastAPI resolves the whole tree.
Caching: if two dependencies in one request both need get_db, FastAPI calls it once and shares the result. Use Depends(get_db, use_cache=False) to get a fresh call.
Where to attach dependencies:
- As a parameter, when the endpoint needs the value.
- In
dependencies=[Depends(verify_key)]on the decorator, router or app, when you only need the side effect (a check that may raise).
Why use it:
- Reuse: write auth or pagination once.
- Separation: the endpoint describes what it needs, not how to build it.
- Testing:
app.dependency_overrides[get_db] = fake_dbswaps implementations without patching. - Documentation: dependency parameters show up in OpenAPI automatically.
Sync and async dependencies both work; sync ones run in the thread pool. Dependencies with yield add setup and teardown, covered separately.
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, Query
from fastapi.testclient import TestClient
app = FastAPI()
calls = {"settings": 0}
def get_settings():
calls["settings"] += 1
return {"api_key": "campus-key", "max_page_size": 50}
def pagination(page: Annotated[int, Query(ge=1)] = 1, size: Annotated[int, Query(ge=1)] = 20,
settings: dict = Depends(get_settings)):
size = min(size, settings["max_page_size"])
return {"offset": (page - 1) * size, "limit": size}
def verify_key(x_api_key: Annotated[str, Header()], settings: dict = Depends(get_settings)):
if x_api_key != settings["api_key"]:
raise HTTPException(status_code=401, detail="Bad API key")
Page = Annotated[dict, Depends(pagination)]
@app.get("/books", dependencies=[Depends(verify_key)])
def list_books(p: Page):
return {"page": p, "settings_calls_so_far": calls["settings"]}
c = TestClient(app)
print(c.get("/books?page=3&size=500", headers={"X-API-Key": "campus-key"}).json())
print(c.get("/books", headers={"X-API-Key": "wrong"}).status_code)
app.dependency_overrides[get_settings] = lambda: {"api_key": "test", "max_page_size": 5}
print(c.get("/books?size=500", headers={"X-API-Key": "test"}).json()["page"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The settings dependency is called once per request even though two dependencies use it. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'page': {'offset': 100, 'limit': 50}, 'settings_calls_so_far': 1} 401 {'offset': 0, 'limit': 5}
Key points
- A dependency is a callable whose result is injected via Depends()
- Dependencies have their own parameters and sub-dependencies
- Results are cached once per request by default
- dependencies=[...] runs checks without passing values
- dependency_overrides makes testing easy
Common mistakes
- Creating database sessions or clients inside every endpoint instead of a dependency
- Expecting values from dependencies=[...] to be passed into the endpoint
- Assuming a dependency is called twice when two sub-dependencies use it (it is cached)
- Patching modules in tests instead of using dependency_overrides
Follow-ups
- How would you write a dependency that requires a specific role?
- What does use_cache=False change?
- How do dependencies appear in the OpenAPI schema?
Tips
- Explain the per-request resolution and caching
- Give two real uses such as pagination and auth
- Mention dependency_overrides for testing