Dependencies¶
FastAPI's dependency injection (Depends) builds what an endpoint needs (a database session, the current
user, common parameters) before calling it, caches each dependency for the request, and runs the cleanup code
of yield dependencies afterwards. The binary resolves the same graph, in the same order.
A function dependency shared through an Annotated alias, a dependency required by every route of
a router (dependencies=[...]), a class dependency and a yield dependency whose cleanup runs once the
request is over. Like every example on this site, it is compiled and compared with FastAPI in CI (how).
docs_src/tutorial/dependencies.py
from typing import Annotated
from fastapi import APIRouter, Depends, Header, HTTPException
async def verify_key(x_key: Annotated[str, Header()]):
if x_key != "fake-super-secret-key":
raise HTTPException(status_code=400, detail="X-Key header invalid")
# every route of this router requires the X-Key header
router = APIRouter(prefix="/dependencies", tags=["dependencies"], dependencies=[Depends(verify_key)])
async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
CommonsDep = Annotated[dict, Depends(common_parameters)]
@router.get("/items")
async def read_items(commons: CommonsDep):
return commons
class Pagination:
def __init__(self, skip: int = 0, limit: int = 3):
self.skip = skip
self.limit = limit
FRUITS = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"]
@router.get("/fruits")
async def read_fruits(page: Annotated[Pagination, Depends(Pagination)]):
return FRUITS[page.skip : page.skip + page.limit]
CLOSED: list[str] = []
async def get_connection():
connection = {"name": f"connection-{len(CLOSED) + 1}"}
try:
yield connection
finally:
CLOSED.append(connection["name"]) # runs once the request is over
@router.get("/connection")
async def use_connection(connection: Annotated[dict, Depends(get_connection)]):
return {"using": connection["name"], "closed_so_far": CLOSED}
What is native¶
Depends(...)with project functions, sub-dependencies, the per-request cache,Annotated[T, Depends(...)]aliases,dependencies=[...]on routes and routers.p: Model = Depends()with a Pydantic model (FastAPI calls the class): one query parameter per field, with its type, default andFieldconstraints (ge,le,max_length,pattern...), thenModel(**fields).yielddependencies: theyieldis a statement, in the body or underif,try(any clause) andwith/async withblocks; several only in exclusive branches of anif(a path without one is contextlib'sRuntimeError: generator didn't yield). Refused in a loop or twice on one path (contextlib's "generator didn't stop", raised outside the generator). The code afteryieldruns at the end of the request, most recent dependency first, before the session commit. An exception of the request (the endpoint's, a later dependency's, a validation error) is raised at theyield, as FastAPI does: anexceptclause sees it, what it raises replaces it (anHTTPExceptionbecomes the response), and an exception caught and not raised again is FastAPI'sFastAPIError("Response not awaited...", a 500).Depends(dep, scope="function")(FastAPI ≥ 0.121): the exit code runs when the endpoint returns, before the response is sent, and an exception there is the request's; the default scope,"request", runs it once the response is sent (for a streamed response, at the end of the stream). The cache key includes the scope.- A plain project class,
Depends(Pagination)orp: Pagination = Depends(): its parameters are those of the first__init__along its bases (ABC,objectand at most one plain project class each,metaclass=ABCMetaallowed), asinspect.signaturereads them (in the module of the class defining it); a__new__or a base of a library is refused. Depends(Service.async_init): a@classmethod(its parameters withoutcls) or a@staticmethodof a plain project class, found along its bases (Sub.async_initof a classmethod ofBasegetsSubascls).Depends(lambda: manager): the lambda's parameters, one function per lambda (its own cache key).- In an application factory (
def create_app(): ...), a dependency function or anAnnotatedalias (Auth = Annotated[Claims, Depends(claims)]) bound once at the factory's top level, before the endpoints that read it: compiled with the factory's locals, like the endpoints defined there. - An instance of a project class with
__call__as a dependency (checker = Checker("bar"),Depends(checker)): its parameters are those of__call__, sync or async. - A dependency built by a factory,
Depends(make_dep(Query([], alias="id"), int)): FastAPI reads the signature of the function the factory returns, whose defaults and annotations hold the factory's arguments. The factory may only define functions and return one of them (undecorated), or only return another factory's call (def require_admin(): return require_role("admin")); a*rolesparameter holds the tuple of the extra positional arguments. Its arguments are constants, builtin types and FastAPI markers of constants, naming the same objects where the call is and where the factory is; inside, a marker is only read as a parameter default or through its.default, and no factory parameter is reassigned. Anything else is refused at its line. app.dependency_overrides[dep] = otherwritten at module level (a project function overridden by a project function):otheris solved and called whereverdepis depended on, with its own parameters.- The session dependency:
async with maker() as s: yield swith optionalawait s.commit(),except: await s.rollback(); raise,finally: await s.close(); theasync_sessionmakeroptions (expire_on_commit,autoflush) are read from it, or from a project class wrapping it (its module instance can also be called outside a dependency,get_worker_session()->WRAPPER(), for a session of its own: theconnect_argsoptions of the engine it builds,-c statement_timeout=60s, are set in each of that session's transactions; a TimeZone there, orconnect_args=on the request session's maker, is refused). The commit afteryieldruns after the endpoint, like FastAPI ≥ 0.121 (a failure is only logged); the binary commits just before sending a complete body (FastAPI just after): same response, without the read-after-write race. Also accepted:s = maker()(annotated or not, possibly the first statement of thetry) thentry: yield s ... finally: [await] s.close();raise excof the caught exception instead ofraise; the maker read into a local first (factory = get_session_factory(),async with factory() as s:); a maker returned by a project function (SessionLocal = make_sessionmaker(engine), literal options); the maker an instance of a project class keeps (async with db_manager.session_maker() as s:), set once by a statement of its__init__or of a method the application's lifespan calls before itsyield(await db_manager.initialize()). A maker set conditionally, twice, from outside its class or by a method nothing calls at startup is refused at its line.
Synchronous session dependencies are described in SQL databases, security schemes used as dependencies in Security.
What stays in Python¶
- A plain class as a dependency (
Depends(MyClass), orDepends()with the class as annotation) is refused: only project functions, Pydantic models and the session dependency are accepted. p: Model = Depends(): a base other thanBaseModel, validators or other decorated methods,model_config, aliases, container fields (FastAPI reads those from the body) are refused.- A request-scoped
yielddependency depending on ascope="function"one is refused (FastAPI'sDependencyScopeError), as is a non-literalscope=. app.dependency_overrideswith anything else than a project function on both sides, or changed anywhere else than at module level, is refused (an override set by a test, in-process, does not reach the binary).