Skip to content

Dependency Injection with Depends: Sub-dependencies, Caching, Global & Router Dependencies, Overrides ​

"'Dependency Injection' means, in programming, that there is a way for your code (in this case, your path operation functions) to declare things that it requires to work and use: 'dependencies'." — FastAPI documentation, "Dependencies", fastapi.tiangolo.com/tutorial/dependencies

Summary: FastAPI's dependency injection is a request-scoped resolver built into the router. A path operation declares what it needs as parameters (session: SessionDep, user: CurrentUser); each need is a dependable, an ordinary callable passed to Depends(). At import time FastAPI reads the signatures and builds a dependency graph; on every request it solves that graph depth-first, reads each dependable's own query, header, cookie and body parameters, calls it (sync ones in the thread pool), caches the result for the rest of the request, and injects it. Dependencies written with yield get setup and teardown around the request, dependencies can be attached to a decorator, a router or the whole app for side effects such as auth, and app.dependency_overrides swaps any node of the graph in tests. Focus: what dependency injection and inversion of control are, Depends() with functions and classes, the Annotated alias (SessionDep), sub-dependencies and the dependency graph, resolution order, per-request caching and use_cache=False, the cache key (callable, security scopes, scope), dependencies with yield (setup, teardown, finally, exceptions, teardown order, when teardown runs relative to the response and background tasks, Depends(scope="function")), dependencies in path operation decorators, APIRouter and global FastAPI(dependencies=...) dependencies, parameterised dependencies (callable classes, closure factories), async vs sync dependencies, Request/Response injection, request.state and lifespan state, the security preview (OAuth2PasswordBearer, Security(), SecurityScopes), app.dependency_overrides, engine vs session (singleton vs per-request), max_concurrency, anti-patterns (global mutable state, service locator, over-injection), and the comparison with Laravel's service container and Go's constructor injection (wire, fx). Learning goal: Design the dependencies of a FastAPI service so that every route states exactly what it needs, every resource has the right lifetime (process, request, function), cleanup always happens, auth and tenancy are enforced in one place, and every external piece can be replaced in a test with one dictionary entry.

This page owns Depends and everything the dependency system does. It does not re-teach its neighbours. Routes, parameters and the lifespan basics are in FastAPI Fundamentals. Query(), Header(), cookies and validators are in Request Validation: a dependency uses them exactly like a route does. APIRouter, prefixes and project layout are in APIRouter & Project Structure. Engines, sessions and models are in SQLAlchemy 2 & SQLModel. Password hashing, JWT and the real token check are in Authentication in FastAPI. Fixtures and the full test-database recipe are in Testing FastAPI. Workers and pool sizing are in FastAPI in Production. The principle behind all of it is the Dependency Inversion Principle. The Go side is Mocking with Interfaces, Dependency Injection for Testability, and where dependencies point in a layered design is in Clean, Hexagonal & Onion Architecture.

Facts below were checked against the FastAPI tutorial and advanced guide (dependencies, classes as dependencies, sub-dependencies, dependencies in decorators, global dependencies, dependencies with yield, advanced dependencies, testing dependencies, security, lifespan events, using the request directly), the Depends()/Security() reference, the FastAPI release notes up to 0.165.0 (2026-11-18), the FastAPI 0.128.8 source (fastapi/dependencies/utils.py, models.py, params.py, saved), the Starlette docs (requests, applications, lifespan, thread pool), PEP 593, the SQLAlchemy 2.0 session guide, the SQLModel tutorial, Laravel 13's service container docs, the google/wire and uber-go/fx docs, and Martin Fowler's 2004 article. The page is written for Python 3.12+ and current FastAPI. The snippets ran on the only interpreter on the build machine, CPython 3.9.6, with the newest releases that still install there: FastAPI 0.128.8 (0.129.0 dropped 3.9), Starlette 0.49.3, Pydantic 2.13.5, SQLAlchemy 2.0.58, Uvicorn 0.39.0, httpx 0.28.1, pytest 8.4.2 and eval-type-backport. Every order of events, status code, header and error quoted as "real" below is what that run printed. Features newer than 0.128.8 (max_concurrency in 0.163.0, the cancellation-cleanup fixes in 0.162.x, WebSocket security dependencies in 0.144.0, the router tree of 0.137.0, Starlette's dictionary-style request.state[...] in 0.52.0) are described from release notes and marked as such.

Page map ​

If you are looking forGo to
The tables to memoriseEverything in one minute
Why a framework should inject thingsWhy it exists
Fowler 2004 to FastAPI 0.165Where it comes from
A before/after servicePython
DI, IoC, dependable, dependantWhat dependency injection is
Depends(fn)Depends() and the dependable
Depends() with a classClass dependencies
SessionDep = Annotated[...]Annotated aliases and SessionDep
Dependencies of dependenciesSub-dependencies and the dependency graph
What runs firstResolution order
"Called once per request"Caching and use_cache
yield, finally, cleanupDependencies with yield
HTTPException in a dependency, exceptExceptions in dependencies
Teardown after the response, background tasksWhen teardown runs
@app.get(..., dependencies=[...])Dependencies in the decorator
APIRouter(dependencies=...), FastAPI(dependencies=...)Router and global dependencies
RoleChecker("admin"), factoriesParameterised dependencies
async def or def dependencyAsync and sync dependencies
Request, Response, request.stateRequest and Response injection
OAuth2PasswordBearer, Security()Security dependencies (scopes preview)
Tests: app.dependency_overridesOverriding dependencies
Engine vs session, app.stateLifespan resources vs per-request dependencies
Limit concurrent sessions (0.163.0)max_concurrency
Global state, service locator, over-injectionAnti-patterns
Pagination, auth, tenant examplesThree worked dependencies
What FastAPI does at import and per requestMechanics
Bugs and fixesSolving the classic problems
Depends vs a DI containerChoosing
Monolith to distributedIn architecture
Run it yourselfLab
Laravel's service containerFor PHP/Laravel developers
Go constructor injection, wire, fxThe Go angle

Everything in one minute ​

The vocabulary. Each row is unpacked in the concept catalogue.

TermWhat it isPlain wordsIn the snippet
Dependency injectionCode declares what it needs; a framework provides it"Ask, don't fetch"every route parameter with Depends
DependableThe callable passed to Depends()"The provider"get_session, Pagination, require_admin
DependantCode that declares a dependency"The consumer"list_notes, and get_tenant_user too
Sub-dependencyA dependency of a dependency"Providers have needs too"get_session needs get_engine
Dependency graphAll dependables of one path operation"The tree FastAPI solves"see the graph diagram
Annotated aliasX = Annotated[T, Depends(fn)]"Declare once, reuse"SessionDep, CurrentUser, PageDep
Yield dependencyGenerator dependable: setup, yield value, teardown"Borrow and return"get_session
Per-request cacheOne value per dependable per request"Solved once, shared"oauth2_scheme
Overrideapp.dependency_overrides[original] = replacement"Swap a node in tests"tests/test_overrides.py

Where a dependency can be attached, and what you get back.

Attached atSyntaxValue passed to the function?Runs forTypical use
Parameteruser: Annotated[User, Depends(get_user)]YesThat routeData the route uses
Decorator@router.delete(..., dependencies=[Depends(require_admin)])NoThat routeGuards, side effects
RouterAPIRouter(dependencies=[Depends(verify_api_key)])NoEvery route of the routerAuth for a group
App (global)FastAPI(dependencies=[Depends(request_context)])NoEvery matched routeRequest id, tenant, audit
Inside another dependencydef b(a: Annotated[A, Depends(get_a)])Yes, to bWherever b is usedComposition

Lifetimes. The question "how long does this object live?" decides where it is created.

LifetimeCreated inExampleShared byCleanup
Process (singleton)lifespan before yieldEngine and its pool, httpx.AsyncClient, settingsAll requests of one workerlifespan after yield
RequestDependency, cached per requestSession, current user, tenantEvery dependant in that requestYield teardown, after the response
FunctionDepends(dep, scope="function") (0.121.0+)A session used only to check the userThat path operation callBefore the response is sent
CallDepends(dep, use_cache=False)A fresh random value, a counterNobodyPer call

When the code after yield runs. From the release notes; the last row is the real run on 0.128.8.

FastAPI versionTeardown runsConsequence
before 0.106.0After the response and after background tasksBackground tasks could use the yielded session; exceptions after yield could not change the response
0.106.0 (2023-12-25)Before the response is sent"Using resources from dependencies with yield in background tasks is no longer supported"
0.110.0 (2024-02-24)(unchanged)An exception caught with except and not re-raised is no longer forwarded: you must raise
0.118.0 (2025-09-29)After the response againA StreamingResponse can use the session while it streams
0.121.0 (2025-11-03)Default after the response; scope="function" before itYou choose per dependency
0.128.8, real runresponse start → background tasks → teardown c, b, atests/test_lifecycle.py

Why it exists ​

Every endpoint of a real API needs the same handful of things: a database session, the authenticated user, the tenant, pagination values, a client for some other service. Without a mechanism for it, each route reads headers by hand, opens and forgets to close sessions, copies the auth check, and imports module-level globals that tests then have to monkeypatch. Dependency injection turns those needs into declarations. The route says session: SessionDep, user: TenantUser; the framework knows how to build each one, in what order, how long it lives and how to clean it up. FastAPI's version is unusual in two ways. It is request-scoped: there is no global container of objects, just a graph that is solved per request with a per-request cache. And it is declarative through the signature: a dependable is an ordinary function whose parameters are read like a route's parameters, so its query, header and cookie inputs are validated and appear in the OpenAPI document.

Without DI (the Before app)With Depends (the After app)
One module-level Session shared by every requestOne Session per request from get_session, closed in finally
A failed request leaves the shared session broken for everyoneThe dependency rolls back and closes; the next request is clean
Auth parsing copied into every routeget_current_user written once, used through an alias
int(request.query_params["page"]): "abc" gives a 500Pagination class dependency: 422 with a precise error
Routes ask a ServiceLocator for what they needRoutes declare what they need; nothing hidden
Tests mutate globals and must restore themapp.dependency_overrides[get_engine] = ...
Inputs invisible in /openapi.jsonDependency inputs documented on every operation

An everyday picture. A hospital operating theatre. The surgeon (the path operation) does not walk to the pharmacy, sterilise instruments or check the patient's wristband; she states on the plan what the operation needs: "anaesthetist, instrument tray, blood type O-negative, patient identity verified". The theatre coordinator (FastAPI) reads every plan before the day starts (import time) and, for each operation, gets things ready in the right order: identity check first, because the blood order depends on it. If two items on the plan need the same identity check, it is done once for that operation (the per-request cache). Some items are borrowed and must be returned: the instrument tray is unpacked before (setup), handed over (yield) and counted and sent for sterilisation after the patient leaves the room (teardown after the response). The theatre itself and its equipment (the engine and its connection pool) are set up once in the morning (lifespan), not for every patient. During a training exercise the coordinator swaps the real patient for a mannequin with the same wristband (dependency_overrides) and nothing else about the plan changes.

Three common misunderstandings, up front ​

  1. "Depends is a container that holds singletons." It holds nothing between requests. Each request gets a fresh solve and a fresh cache; long-lived objects belong in the lifespan, and a dependency only hands them out.
  2. "The code after yield runs before the client gets the response." On 0.118.0 and later it runs after the response is sent, and in the real run even after background tasks. A commit() placed after yield can fail when the client already has its 200. Commit in the route, or use scope="function".
  3. "Overriding a dependency in tests is monkeypatching." It is a dictionary lookup FastAPI performs for every node of the graph. The override replaces the node and its sub-dependencies, and its own parameters are read from the request like any dependency's.

Where it comes from ​

The pattern is older than Python web frameworks. Martin Fowler's article "Inversion of Control Containers and the Dependency Injection pattern" (23 January 2004) named it. He saw Java containers describing themselves as implementing "Inversion of Control" and asked "what aspect of control are they inverting?". Then: "Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection." He also set it against the Service Locator: "With service locator the application class asks for it explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class - hence the inversion of control."

The Python pieces FastAPI uses arrived later. PEP 593 added typing.Annotated in Python 3.9 ("This PEP adds an Annotated type to the typing module to decorate existing types with context-specific metadata"). FastAPI 0.95.0 (2023-03-18) "adds support for dependencies and parameters using Annotated and recommends its usage", and the release note singles out "Annotated dependencies that are then shared by multiple path operation functions". The yield-dependency timing then changed several times, as the one-minute table shows: 0.106.0 (2023-12-25) moved teardown before the response, 0.110.0 (2024-02-24) stopped forwarding swallowed exceptions, 0.118.0 (2025-09-29) moved teardown back after the response, and 0.121.0 (2025-11-03) added scope. The OAuth2 password flow with bearer tokens has answered 401 since 0.20.0 (2019-04-27): "Upgrade Password flow using Bearer tokens to use the correct HTTP status code 401 UNAUTHORIZED, with WWW-Authenticate headers". 0.122.0 (2025-11-24) did the same for the other integrated security utilities ("Use 401 status code in security classes when credentials are missing"; the how-to page: "Before FastAPI version 0.122.0, when the integrated security utilities returned an error to the client after a failed authentication, they used the HTTP status code 403 Forbidden", and its example is HTTPBearer). 0.123.0 (2025-11-30) fixed caching ("Cache dependencies that don't use scopes and don't have sub-dependencies with scopes"). After the snippet pin, 0.137.0 (2026-06-14) kept routers as a tree instead of copying routes, which lists "Dependencies per router" among the features it enables. 0.144.0 (2026-10-18) added "WebSocket support to security dependencies". 0.162.5 and 0.162.7 (November 2026) fixed sync and async yield-dependency cleanup on cancellation. 0.163.0 (2026-11-14) added Depends(max_concurrency=...).

1  2004-01  Fowler: "Inversion of Control Containers and the Dependency Injection pattern"
2  2019-04  FastAPI 0.20.0: OAuth2 password bearer flow answers 401 + WWW-Authenticate
3  2020-10  Python 3.9 released with typing.Annotated (PEP 593, Python-Version 3.9)
4  2023-03  FastAPI 0.95.0: Annotated dependencies recommended (SessionDep-style aliases)
5  2023-12  0.106.0: yield teardown before the response; no yielded resources in background tasks
6  2024-02  0.110.0: except without raise is no longer forwarded (must re-raise)
7  2025-09  0.118.0: yield teardown after the response again (StreamingResponse)
8  2025-11  0.121.0 Depends(scope="function"); 0.122.0 HTTPBearer & co. 401 instead of 403; 0.123.0 cache fix
9  2026-02  0.128.8: last release for Python 3.9 (the snippet pin)
10 2026-06  0.137.0: router tree, "dependencies per router" enabled
11 2026-11  0.144 WebSocket security deps; 0.162.x cancellation cleanup; 0.163.0 max_concurrency

Python ​

Before ​

A notes API with no dependency injection. One Session is created at import and shared by every request; a ServiceLocator hands out the session and the token table; each route parses Authorization, X-Tenant-ID and the page values itself; nothing rolls back after a failure.

py
"""The Before app: no dependency injection. Works on a quiet day; every route repeats the plumbing.

Bugs on purpose:
- one module-level Session shared by every request (global mutable state);
- a service locator: routes ask a registry for what they need;
- auth, tenant and pagination parsing copied into each route;
- no teardown: nothing rolls back after a failed request;
- tests can only swap things by mutating module globals.
"""
from __future__ import annotations

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.db import Note, create_schema_and_seed, make_engine

engine = make_engine("sqlite://")           # created at import time, even in tests
create_schema_and_seed(engine)
SESSION = Session(engine)                   # one Session for the whole process


class ServiceLocator:
    """Anti-pattern: every caller depends on the locator and hides what it really needs."""

    _services: dict = {}

    @classmethod
    def register(cls, name: str, obj: object) -> None:
        cls._services[name] = obj

    @classmethod
    def get(cls, name: str):
        return cls._services[name]


ServiceLocator.register("db", SESSION)
ServiceLocator.register("tokens", {"alice-token": ("alice", "acme"), "bob-token": ("bob", "acme")})

app = FastAPI(title="Notes API (before)")


@app.get("/notes")
def list_notes(request: Request):
    auth = request.headers.get("authorization", "")            # copy 1 of the auth code
    user = ServiceLocator.get("tokens").get(auth.removeprefix("Bearer "))
    if user is None:
        return JSONResponse({"error": "unauthorized"}, status_code=401)
    tenant = request.headers.get("x-tenant-id", "")
    page = int(request.query_params.get("page", "1"))          # copy 1 of pagination; "abc" -> 500
    size = int(request.query_params.get("size", "20"))
    db: Session = ServiceLocator.get("db")
    rows = db.scalars(
        select(Note).where(Note.tenant_id == tenant).order_by(Note.id).limit(size).offset((page - 1) * size)
    ).all()
    return [{"id": n.id, "title": n.title, "owner": n.owner} for n in rows]


@app.post("/notes", status_code=201)
async def create_note(request: Request):
    auth = request.headers.get("authorization", "")            # copy 2 of the auth code
    user = ServiceLocator.get("tokens").get(auth.removeprefix("Bearer "))
    if user is None:
        return JSONResponse({"error": "unauthorized"}, status_code=401)
    body = await request.json()
    db: Session = ServiceLocator.get("db")
    note = Note(tenant_id=user[1], title=body["title"], owner=user[0])
    db.add(note)
    db.commit()            # an IntegrityError here leaves the shared Session needing a rollback
    return {"id": note.id, "title": note.title, "owner": note.owner}

The tests pin the bugs down. Most important: one request that hits a unique-constraint violation leaves the shared session in a failed transaction, and the next, unrelated request fails with PendingRollbackError (real run).

py
"""Pins down the bugs of app/before.py (no dependency injection)."""
from fastapi.testclient import TestClient

from app import before

A = {"Authorization": "Bearer alice-token", "X-Tenant-ID": "acme"}


def test_one_session_for_every_request():
    assert before.ServiceLocator.get("db") is before.SESSION


def test_bad_page_is_a_500_not_a_422():
    c = TestClient(before.app, raise_server_exceptions=False)
    assert c.get("/notes?page=abc", headers=A).status_code == 500


def test_one_failed_request_poisons_the_shared_session():
    c = TestClient(before.app, raise_server_exceptions=False)
    assert c.get("/notes?size=1", headers=A).status_code == 200
    # duplicate (tenant_id, title): IntegrityError, nobody rolls back
    assert c.post("/notes", json={"title": "acme note 1"}, headers=A).status_code == 500
    # an unrelated, valid request now fails too: PendingRollbackError
    assert c.get("/notes?size=1", headers=A).status_code == 500
    before.SESSION.rollback()   # the manual cleanup a yield dependency would have done


def test_swapping_a_service_means_mutating_a_global():
    c = TestClient(before.app)
    saved = before.ServiceLocator.get("tokens")
    before.ServiceLocator.register("tokens", {"t": ("tess", "acme")})
    try:
        r = c.get("/notes?size=1", headers={"Authorization": "Bearer t", "X-Tenant-ID": "acme"})
        assert r.status_code == 200
    finally:
        before.ServiceLocator.register("tokens", saved)   # forget this and other tests break


def test_errors_are_ad_hoc_bodies_and_not_in_openapi():
    c = TestClient(before.app)
    r = c.get("/notes")
    assert r.status_code == 401 and r.json() == {"error": "unauthorized"}
    params = c.get("/openapi.json").json()["paths"]["/notes"]["get"].get("parameters", [])
    assert params == []   # page, size, tenant, auth: invisible to clients

After ​

The models and the engine factory. The engine is created once per process. The in-memory SQLite variant needs StaticPool and check_same_thread=False, because sync dependencies and def routes run on worker threads:

py
"""SQLAlchemy 2 models and the engine factory used by the lifespan."""
from __future__ import annotations

from sqlalchemy import ForeignKey, String, UniqueConstraint, create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.pool import StaticPool


class Base(DeclarativeBase):
    pass


class Tenant(Base):
    __tablename__ = "tenants"
    id: Mapped[str] = mapped_column(String(32), primary_key=True)
    name: Mapped[str] = mapped_column(String(100))


class Note(Base):
    __tablename__ = "notes"
    __table_args__ = (UniqueConstraint("tenant_id", "title"),)
    id: Mapped[int] = mapped_column(primary_key=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"), index=True)
    title: Mapped[str] = mapped_column(String(120))
    owner: Mapped[str] = mapped_column(String(50))


def make_engine(url: str = "sqlite://", echo: bool = False) -> Engine:
    """One engine (and its connection pool) per process: created in the lifespan, never per request.

    SQLite in memory needs StaticPool (one shared connection) and check_same_thread=False,
    because sync dependencies and `def` routes run on AnyIO worker threads.
    """
    if url.startswith("sqlite"):
        return create_engine(
            url,
            echo=echo,
            connect_args={"check_same_thread": False},
            poolclass=StaticPool,
        )
    return create_engine(url, echo=echo, pool_size=10, max_overflow=5, pool_pre_ping=True)


def create_schema_and_seed(engine: Engine) -> None:
    Base.metadata.create_all(engine)
    with Session(engine) as s:
        if s.get(Tenant, "acme") is None:
            s.add_all([Tenant(id="acme", name="Acme"), Tenant(id="globex", name="Globex")])
            s.add_all(
                [Note(tenant_id="acme", title=f"acme note {i}", owner="alice") for i in range(1, 6)]
                + [Note(tenant_id="globex", title="globex note 1", owner="carol")]
            )
            s.commit()

Every dependency in one module, the usual app/dependencies.py: the yield session, the Pagination class, the tenant header, OAuth2PasswordBearer and get_current_user with scopes, the tenant check built from two sub-dependencies, a callable class (RoleChecker), a closure factory (requires_feature), a router guard (verify_api_key) and a global dependency (request_context). The module deliberately has no from __future__ import annotations (why):

py
"""Every dependency of the After app, in one module (the usual app/dependencies.py).

No `from __future__ import annotations` here: FastAPI resolves string annotations with the
function's __globals__, and a class or a callable instance has none (see app/future_gotcha.py).
"""
import uuid
from collections.abc import Iterator
from typing import Annotated, Optional

from fastapi import Depends, Header, HTTPException, Query, Request, Response, Security, status
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
from pydantic import BaseModel
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session


# ---------- resources: engine from the lifespan, one Session per request ----------
def get_engine(request: Request) -> Engine:
    # Created once in the lifespan and stored on app.state: a process-wide singleton.
    return request.app.state.engine


def get_session(engine: Annotated[Engine, Depends(get_engine)]) -> Iterator[Session]:
    # A yield dependency: code before `yield` is setup, code after it is teardown.
    session = Session(engine)
    try:
        yield session          # the value injected into the route
    except Exception:
        session.rollback()     # an exception raised in the route arrives here
        raise                  # always re-raise (FastAPI 0.110+ does not do it for you)
    finally:
        session.close()        # runs on success and on failure


SessionDep = Annotated[Session, Depends(get_session)]   # the Annotated alias


# ---------- a class dependency: pagination ----------
class Pagination:
    def __init__(
        self,
        page: Annotated[int, Query(ge=1, description="1-based page number")] = 1,
        size: Annotated[int, Query(ge=1, le=100)] = 20,
    ) -> None:
        self.page = page
        self.size = size

    @property
    def offset(self) -> int:
        return (self.page - 1) * self.size


PageDep = Annotated[Pagination, Depends()]   # Depends() with no argument: "call the annotated class"


# ---------- tenant from a header ----------
def get_tenant(
    x_tenant_id: Annotated[str, Header(pattern=r"^[a-z][a-z0-9-]{1,31}$")],
) -> str:
    return x_tenant_id


TenantDep = Annotated[str, Depends(get_tenant)]


# ---------- authentication: OAuth2PasswordBearer + get_current_user ----------
class User(BaseModel):
    name: str
    tenant: str
    roles: list[str] = []
    scopes: list[str] = []


# Fake token store; the real token check (JWT, hashing) is the auth chapter's job.
FAKE_TOKENS = {
    "alice-token": User(name="alice", tenant="acme", roles=["admin"], scopes=["notes:read", "notes:write"]),
    "bob-token": User(name="bob", tenant="acme", roles=[], scopes=["notes:read"]),
    "carol-token": User(name="carol", tenant="globex", roles=[], scopes=["notes:read", "notes:write"]),
}

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"notes:read": "Read notes", "notes:write": "Create notes"},
)


def get_current_user(
    security_scopes: SecurityScopes,
    token: Annotated[str, Depends(oauth2_scheme)],     # sub-dependency: the bearer token
) -> User:
    user = FAKE_TOKENS.get(token)
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token",
            headers={"WWW-Authenticate": "Bearer"},
        )
    missing = [s for s in security_scopes.scopes if s not in user.scopes]
    if missing:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=f"Missing scope: {' '.join(missing)}",
            headers={"WWW-Authenticate": f'Bearer scope="{security_scopes.scope_str}"'},
        )
    return user


CurrentUser = Annotated[User, Security(get_current_user, scopes=["notes:read"])]
WriterUser = Annotated[User, Security(get_current_user, scopes=["notes:write"])]


def get_tenant_user(user: CurrentUser, tenant: TenantDep) -> User:
    # Sub-dependency graph: tenant header + authenticated user -> a user allowed in this tenant.
    if user.tenant != tenant:
        raise HTTPException(status.HTTP_403_FORBIDDEN, "User does not belong to this tenant")
    return user


TenantUser = Annotated[User, Depends(get_tenant_user)]


# ---------- parameterised dependencies ----------
class RoleChecker:
    """A callable class: __init__ takes our parameters, __call__ is what FastAPI analyses."""

    def __init__(self, role: str) -> None:
        self.role = role

    def __call__(self, user: CurrentUser) -> User:
        if self.role not in user.roles:
            raise HTTPException(status.HTTP_403_FORBIDDEN, f"Requires role {self.role}")
        return user


require_admin = RoleChecker("admin")   # module-level instance: the key for dependency_overrides


def requires_feature(flag: str):
    """A closure factory: returns a new dependency function per flag."""

    def check(request: Request) -> None:
        if not request.app.state.features.get(flag, False):
            raise HTTPException(status.HTTP_404_NOT_FOUND, "Not Found")

    check.__name__ = f"requires_feature_{flag}"
    return check


# ---------- decorator / router / global dependencies (no return value used) ----------
def verify_api_key(x_api_key: Annotated[str, Header()]) -> None:
    if x_api_key != "admin-key":
        raise HTTPException(status.HTTP_403_FORBIDDEN, "Bad API key")


def request_context(
    request: Request,
    response: Response,
    x_request_id: Annotated[Optional[str], Header()] = None,
) -> None:
    # Global dependency: Request and Response injection, request.state for per-request data.
    rid = x_request_id or uuid.uuid4().hex
    request.state.request_id = rid
    response.headers["X-Request-ID"] = rid

The application. The lifespan owns the engine and the lifespan state. Routes declare aliases. The admin router carries a router dependency, the delete route a decorator dependency, the app a global one. create_app() lets every test build a fresh app:

py
"""The After app: resources from the lifespan, per-request dependencies, router and global dependencies."""
from __future__ import annotations

import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Annotated

from fastapi import APIRouter, BackgroundTasks, Depends, FastAPI, HTTPException, Request, status
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError

from app.db import Note, create_schema_and_seed, make_engine
from app.deps import (
    PageDep, SessionDep, TenantDep, TenantUser, WriterUser,
    request_context, require_admin, requires_feature, verify_api_key,
)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[dict]:
    # Process-wide resources: created once per worker process, before the first request.
    engine = make_engine(os.environ.get("DATABASE_URL", "sqlite://"))
    create_schema_and_seed(engine)
    app.state.engine = engine
    app.state.features = {"beta": False}
    # Lifespan state: Starlette copies this dict (shallow) into every request.state.
    yield {"audit_log": []}
    engine.dispose()


class NoteIn(BaseModel):
    title: str


class NoteOut(BaseModel):
    id: int
    title: str
    owner: str


def write_audit(log: list, request_id: str, note_id: int) -> None:
    # A background task gets plain values (ids), never the request's Session.
    log.append(f"{request_id} created note {note_id}")


notes = APIRouter(prefix="/notes", tags=["notes"])


@notes.get("", response_model=list[NoteOut])
def list_notes(session: SessionDep, tenant: TenantDep, page: PageDep, user: TenantUser):
    stmt = (
        select(Note)
        .where(Note.tenant_id == tenant)
        .order_by(Note.id)
        .limit(page.size)
        .offset(page.offset)
    )
    return session.scalars(stmt).all()


@notes.post("", response_model=NoteOut, status_code=status.HTTP_201_CREATED)
def create_note(
    body: NoteIn,
    session: SessionDep,
    user: WriterUser,
    tenant_user: TenantUser,
    request: Request,
    tasks: BackgroundTasks,
):
    note = Note(tenant_id=tenant_user.tenant, title=body.title, owner=user.name)
    session.add(note)
    try:
        session.commit()   # commit inside the route: the client sees the result of the commit
    except IntegrityError:
        session.rollback()
        raise HTTPException(status.HTTP_409_CONFLICT, "A note with this title exists")
    tasks.add_task(write_audit, request.state.audit_log, request.state.request_id, note.id)
    return note


@notes.delete("/{note_id}", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(require_admin)])
def delete_note(note_id: int, session: SessionDep, user: TenantUser) -> None:
    note = session.get(Note, note_id)
    if note is None or note.tenant_id != user.tenant:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "Note not found")
    session.delete(note)
    session.commit()


admin = APIRouter(prefix="/admin", tags=["admin"], dependencies=[Depends(verify_api_key)])


@admin.get("/stats")
def stats(session: SessionDep) -> dict:
    rows = session.execute(select(Note.tenant_id, func.count()).group_by(Note.tenant_id)).all()
    return {tenant: count for tenant, count in rows}


@admin.get("/audit")
def audit(request: Request) -> list:
    return request.state.audit_log


misc = APIRouter(tags=["misc"])


@misc.get("/beta/summary", dependencies=[Depends(requires_feature("beta"))])
def beta_summary() -> dict:
    return {"beta": True}


@misc.get("/whoami")
def whoami(user: TenantUser, request: Request) -> dict:
    return {"name": user.name, "tenant": user.tenant, "request_id": request.state.request_id}


def create_app() -> FastAPI:
    """An app factory: every test can build a fresh app with its own overrides and lifespan."""
    app = FastAPI(
        title="Notes API",
        lifespan=lifespan,
        dependencies=[Depends(request_context)],   # global: runs for every matched route
    )
    app.include_router(notes)
    app.include_router(admin)
    app.include_router(misc)
    return app


app = create_app()

The fixtures build a fresh app per test and clear overrides afterwards:

py
import pytest
from fastapi.testclient import TestClient

from app.main import create_app

ALICE = {"Authorization": "Bearer alice-token", "X-Tenant-ID": "acme"}   # admin, read + write
BOB = {"Authorization": "Bearer bob-token", "X-Tenant-ID": "acme"}       # read only


@pytest.fixture
def app():
    app = create_app()
    yield app
    app.dependency_overrides.clear()   # never leak an override into the next test


@pytest.fixture
def client(app):
    with TestClient(app) as c:         # `with` runs the lifespan: engine, schema, seed
        yield c

The tests walk every dependency: pagination, 401/403, scopes, tenant, commit-in-route, the callable class, the router guard, the feature flag, the global dependency, the lost header on errors, and the cache key that includes scopes:

py
"""The After app: each dependency doing its job."""
from tests.conftest import ALICE, BOB


def test_pagination_class_dependency(client):
    r = client.get("/notes?page=2&size=2", headers=ALICE)
    assert r.status_code == 200
    assert [n["id"] for n in r.json()] == [3, 4]


def test_pagination_validation_is_a_422(client):
    r = client.get("/notes?page=0", headers=ALICE)
    assert r.status_code == 422
    assert r.json()["detail"][0]["loc"] == ["query", "page"]


def test_missing_bearer_token_is_401(client):
    r = client.get("/notes", headers={"X-Tenant-ID": "acme"})
    assert r.status_code == 401                      # OAuth2PasswordBearer: 401 since FastAPI 0.20.0
    assert r.json() == {"detail": "Not authenticated"}
    assert r.headers["www-authenticate"] == "Bearer"


def test_invalid_token_is_401_from_get_current_user(client):
    r = client.get("/notes", headers={"Authorization": "Bearer nope", "X-Tenant-ID": "acme"})
    assert (r.status_code, r.json()["detail"]) == (401, "Invalid token")


def test_missing_scope_is_403(client):
    r = client.post("/notes", json={"title": "x"}, headers=BOB)
    assert r.status_code == 403
    assert r.headers["www-authenticate"] == 'Bearer scope="notes:write"'


def test_tenant_header_validated_and_matched(client):
    assert client.get("/notes", headers={**ALICE, "X-Tenant-ID": "Bad_Tenant"}).status_code == 422
    r = client.get("/notes", headers={**ALICE, "X-Tenant-ID": "globex"})
    assert (r.status_code, r.json()["detail"]) == (403, "User does not belong to this tenant")


def test_create_commits_in_route_and_background_task_gets_ids(client):
    r = client.post("/notes", json={"title": "new"}, headers={**ALICE, "X-Request-ID": "req-1"})
    assert r.status_code == 201 and r.headers["x-request-id"] == "req-1"
    assert client.post("/notes", json={"title": "new"}, headers=ALICE).status_code == 409
    # the Session survived the IntegrityError: the next request works
    assert client.get("/notes?size=1", headers=ALICE).status_code == 200
    audit = client.get("/admin/audit", headers={"X-API-Key": "admin-key"}).json()
    assert audit == [f"req-1 created note {r.json()['id']}"]


def test_callable_class_role_checker(client):
    assert client.delete("/notes/1", headers=BOB).status_code == 403
    assert client.delete("/notes/1", headers=ALICE).status_code == 204


def test_router_dependency_guards_every_admin_route(client):
    assert client.get("/admin/stats").status_code == 422             # header missing
    assert client.get("/admin/stats", headers={"X-API-Key": "x"}).status_code == 403
    r = client.get("/admin/stats", headers={"X-API-Key": "admin-key"})
    assert r.json() == {"acme": 5, "globex": 1}


def test_closure_factory_feature_flag(client, app):
    assert client.get("/beta/summary").status_code == 404
    app.state.features["beta"] = True
    assert client.get("/beta/summary").json() == {"beta": True}


def test_global_dependency_sets_request_state_and_header(client):
    r = client.get("/whoami", headers=ALICE)
    assert r.json()["request_id"] == r.headers["x-request-id"]


def test_header_set_on_injected_response_is_lost_on_httpexception(client):
    # request_context ran and set X-Request-ID on the injected Response,
    # but the 401 is a new response built by the exception handler.
    r = client.get("/whoami", headers={"X-Tenant-ID": "acme", "X-Request-ID": "r-9"})
    assert r.status_code == 401 and "x-request-id" not in r.headers


def test_global_dependency_does_not_run_for_unmatched_paths(client):
    r = client.get("/nope")
    assert r.status_code == 404 and "x-request-id" not in r.headers


def test_lifespan_state_is_per_app(app):
    from fastapi.testclient import TestClient

    with TestClient(app) as c:
        c.post("/notes", json={"title": "one"}, headers=ALICE)
        assert len(c.get("/admin/audit", headers={"X-API-Key": "admin-key"}).json()) == 1
    with TestClient(app) as c:   # a new lifespan: new engine, new audit_log
        assert c.get("/admin/audit", headers={"X-API-Key": "admin-key"}).json() == []


class CountingTokens(dict):
    calls = 0

    def get(self, key, default=None):
        CountingTokens.calls += 1
        return super().get(key, default)


def test_cache_key_includes_security_scopes(client, monkeypatch):
    import app.deps as deps

    monkeypatch.setattr(deps, "FAKE_TOKENS", CountingTokens(deps.FAKE_TOKENS))
    CountingTokens.calls = 0
    client.delete("/notes/2", headers=ALICE)        # require_admin + TenantUser: same scopes
    assert CountingTokens.calls == 1                # get_current_user ran once
    CountingTokens.calls = 0
    client.post("/notes", json={"title": "t"}, headers=ALICE)   # notes:write and notes:read
    assert CountingTokens.calls == 2                # two cache keys -> two calls


def test_security_scheme_is_cached_per_scope_set(client, monkeypatch):
    from fastapi.security import OAuth2PasswordBearer

    seen = []
    original = OAuth2PasswordBearer.__call__

    async def counting(self, request):
        seen.append(1)
        return await original(self, request)

    monkeypatch.setattr(OAuth2PasswordBearer, "__call__", counting)
    client.get("/notes", headers=ALICE)                          # notes:read only
    assert len(seen) == 1
    seen.clear()
    client.post("/notes", json={"title": "s"}, headers=ALICE)    # notes:write branch + notes:read branch
    assert len(seen) == 2                                        # the scheme's cache key includes the scopes

Overrides, including the deep one (the engine), an override with its own parameters, and the instance-versus-class key trap:

py
"""app.dependency_overrides: replace a dependency anywhere in the graph, for one test."""
from typing import Annotated

from fastapi import Query
from fastapi.testclient import TestClient

from app.db import create_schema_and_seed, make_engine
from app.deps import (
    RoleChecker, User, get_current_user, get_engine, get_tenant,
    request_context, require_admin, verify_api_key,
)

TESTER = User(name="tester", tenant="acme", roles=[], scopes=["notes:read", "notes:write"])


def test_override_skips_the_original_and_its_sub_dependencies(app, client):
    # get_current_user normally needs oauth2_scheme -> an Authorization header.
    app.dependency_overrides[get_current_user] = lambda: TESTER
    r = client.get("/whoami", headers={"X-Tenant-ID": "acme"})
    assert r.status_code == 200 and r.json()["name"] == "tester"


def test_override_a_deep_sub_dependency_the_engine(app, tmp_path):
    engine = make_engine(f"sqlite:///{tmp_path / 'test.db'}")
    create_schema_and_seed(engine)
    app.dependency_overrides[get_engine] = lambda: engine   # get_session still runs, on our engine
    with TestClient(app) as c:
        r = c.post("/notes", json={"title": "on disk"}, headers={"Authorization": "Bearer alice-token", "X-Tenant-ID": "acme"})
        assert r.status_code == 201
    with engine.connect() as conn:
        assert conn.exec_driver_sql("SELECT count(*) FROM notes WHERE title = 'on disk'").scalar() == 1


def test_override_can_declare_its_own_parameters(app, client):
    def tenant_from_query(t: Annotated[str, Query()] = "acme") -> str:
        return t

    app.dependency_overrides[get_tenant] = tenant_from_query
    r = client.get("/notes?size=1&t=acme", headers={"Authorization": "Bearer alice-token"})
    assert r.status_code == 200   # no X-Tenant-ID header needed any more


def test_parameterised_instance_is_the_key_not_the_class(app, client):
    app.dependency_overrides[get_current_user] = lambda: TESTER       # not an admin
    assert client.delete("/notes/1", headers={"X-Tenant-ID": "acme"}).status_code == 403
    app.dependency_overrides[RoleChecker] = lambda: None              # wrong key: ignored
    assert client.delete("/notes/1", headers={"X-Tenant-ID": "acme"}).status_code == 403
    app.dependency_overrides[require_admin] = lambda: None            # the instance used in the route
    assert client.delete("/notes/1", headers={"X-Tenant-ID": "acme"}).status_code == 204


def test_router_and_global_dependencies_can_be_overridden(app, client):
    app.dependency_overrides[verify_api_key] = lambda: None
    app.dependency_overrides[request_context] = lambda: None
    r = client.get("/admin/stats")
    assert r.status_code == 200 and "x-request-id" not in r.headers


def test_clear_restores_the_real_graph(app, client):
    app.dependency_overrides[verify_api_key] = lambda: None
    assert client.get("/admin/stats").status_code == 200
    app.dependency_overrides.clear()
    assert client.get("/admin/stats").status_code == 422

A probe app records the order of events during one request, with a pure ASGI middleware that logs the moment the response status leaves the app:

py
"""A probe app that records, in order, what the dependency system does during one request."""
from __future__ import annotations

import asyncio
import threading
from collections.abc import AsyncIterator, Iterator
from typing import Annotated

from fastapi import APIRouter, BackgroundTasks, Depends, FastAPI, HTTPException, Query

EVENTS: list[str] = []
CALLS: dict[str, int] = {}


def log(event: str) -> None:
    EVENTS.append(event)


class RecordSend:
    """Pure ASGI middleware: logs the moment the response status line leaves the app."""

    def __init__(self, app) -> None:
        self.app = app

    async def __call__(self, scope, receive, send):
        async def wrapped(message):
            if message["type"] == "http.response.start":
                log(f"response.start {message['status']}")
            await send(message)

        await self.app(scope, receive, wrapped)


# ---------- resolution order: app, router, decorator, parameter ----------
def app_dep() -> None:
    log("app dependency")


def router_dep() -> None:
    log("router dependency")


def decorator_dep() -> None:
    log("decorator dependency")


def param_dep() -> str:
    log("parameter dependency")
    return "value"


app = FastAPI(dependencies=[Depends(app_dep)])
app.add_middleware(RecordSend)
router = APIRouter(dependencies=[Depends(router_dep)])


@router.get("/order", dependencies=[Depends(decorator_dep)])
def order(v: Annotated[str, Depends(param_dep)]) -> dict:
    log("route")
    return {"v": v}


# ---------- caching: one call per request unless use_cache=False ----------
def counted() -> int:
    CALLS["counted"] = CALLS.get("counted", 0) + 1
    return CALLS["counted"]


def left(n: Annotated[int, Depends(counted)]) -> int:
    return n


def right(n: Annotated[int, Depends(counted)]) -> int:
    return n


@app.get("/cache")
def cache(a: Annotated[int, Depends(left)], b: Annotated[int, Depends(right)]) -> dict:
    return {"left": a, "right": b, "calls": CALLS["counted"]}


@app.get("/nocache")
def nocache(
    a: Annotated[int, Depends(counted)],
    b: Annotated[int, Depends(counted, use_cache=False)],
) -> dict:
    return {"a": a, "b": b, "calls": CALLS["counted"]}


@app.get("/nocache-first")
def nocache_first(
    a: Annotated[int, Depends(counted, use_cache=False)],   # runs, and its result is stored in the cache
    b: Annotated[int, Depends(counted)],                     # cache hit: reuses a's value
) -> dict:
    return {"a": a, "b": b, "calls": CALLS["counted"]}


# ---------- validation errors do not stop sibling dependencies ----------
def side_effect() -> None:
    log("side effect ran")


def needs_int(n: Annotated[int, Query()]) -> int:
    return n


@app.get("/sibling")
def sibling(n: Annotated[int, Depends(needs_int)], _: Annotated[None, Depends(side_effect)]) -> dict:
    log("route")
    return {"n": n}


def guarded_side_effect(n: Annotated[int, Depends(needs_int)]) -> int:
    # Depends on the validated input: not called when that input fails validation.
    log("guarded side effect ran")
    return n


@app.get("/guarded")
def guarded(n: Annotated[int, Depends(guarded_side_effect)]) -> dict:
    return {"n": n}


# ---------- yield: setup, teardown order, response before teardown ----------
def dep_a() -> Iterator[str]:
    log("a setup")
    try:
        yield "a"
    finally:
        log("a teardown")


def dep_b(a: Annotated[str, Depends(dep_a)]) -> Iterator[str]:
    log("b setup")
    try:
        yield a + "b"
    finally:
        log("b teardown")


async def dep_c(b: Annotated[str, Depends(dep_b)]) -> AsyncIterator[str]:
    log("c setup")
    try:
        yield b + "c"
    finally:
        log("c teardown")


def task(name: str) -> None:
    log(f"background task {name}")


@app.get("/teardown")
def teardown(c: Annotated[str, Depends(dep_c)], tasks: BackgroundTasks) -> dict:
    log("route")
    tasks.add_task(task, "ran")
    return {"chain": c}


def early() -> Iterator[str]:
    log("function-scope setup")
    try:
        yield "x"
    finally:
        log("function-scope teardown")


@app.get("/function-scope")
def function_scope(x: Annotated[str, Depends(early, scope="function")]) -> dict:
    log("route")
    return {"x": x}


# ---------- exceptions inside yield dependencies ----------
class OwnerError(Exception):
    pass


def translating() -> Iterator[str]:
    try:
        yield "rick"
    except OwnerError as e:
        log("translating caught OwnerError")
        raise HTTPException(status_code=400, detail=f"Owner error: {e}")


@app.get("/translate")
def translate(user: Annotated[str, Depends(translating)]) -> dict:
    raise OwnerError(user)


def swallowing() -> Iterator[str]:
    try:
        yield "rick"
    except ValueError:
        log("swallowing caught ValueError and did not re-raise")


@app.get("/swallow")
def swallow(user: Annotated[str, Depends(swallowing)]) -> dict:
    raise ValueError("boom")


def raises_in_setup() -> str:
    raise HTTPException(status_code=403, detail="denied in dependency")


@app.get("/denied")
def denied(x: Annotated[str, Depends(raises_in_setup)]) -> dict:
    log("route must not run")
    return {}


# ---------- which thread runs what ----------
def sync_dep() -> str:
    return threading.current_thread().name


async def async_dep() -> str:
    await asyncio.sleep(0)
    return threading.current_thread().name


@app.get("/threads")
async def threads(s: Annotated[str, Depends(sync_dep)], a: Annotated[str, Depends(async_dep)]) -> dict:
    return {"sync_dependency": s, "async_dependency": a, "async_route": threading.current_thread().name}


app.include_router(router)
py
"""What the dependency system does, in order, during one request (FastAPI 0.128.8)."""
import pytest
from fastapi.testclient import TestClient

from app import lifecycle as L


@pytest.fixture
def c():
    L.EVENTS.clear()
    L.CALLS.clear()
    return TestClient(L.app, raise_server_exceptions=False)


def test_resolution_order_app_router_decorator_parameter(c):
    c.get("/order")
    assert L.EVENTS == [
        "app dependency", "router dependency", "decorator dependency",
        "parameter dependency", "route", "response.start 200",
    ]


def test_cached_per_request(c):
    assert c.get("/cache").json() == {"left": 1, "right": 1, "calls": 1}
    assert c.get("/cache").json()["calls"] == 2          # new request, new cache


def test_use_cache_false_calls_again(c):
    assert c.get("/nocache").json() == {"a": 1, "b": 2, "calls": 2}


def test_uncached_declaration_first_feeds_the_cache(c):
    # order matters: the use_cache=False call runs first and its value is cached for Depends(counted)
    assert c.get("/nocache-first").json() == {"a": 1, "b": 1, "calls": 1}


def test_validation_error_does_not_stop_a_sibling_side_effect(c):
    r = c.get("/sibling?n=abc")
    assert r.status_code == 422
    assert "side effect ran" in L.EVENTS and "route" not in L.EVENTS


def test_side_effect_that_depends_on_the_input_is_skipped(c):
    assert c.get("/guarded?n=abc").status_code == 422
    assert "guarded side effect ran" not in L.EVENTS
    assert c.get("/guarded?n=3").json() == {"n": 3}


def test_teardown_after_response_and_background_tasks_in_reverse_order(c):
    assert c.get("/teardown").json() == {"chain": "abc"}
    assert L.EVENTS == [
        "app dependency", "a setup", "b setup", "c setup", "route",
        "response.start 200", "background task ran",
        "c teardown", "b teardown", "a teardown",
    ]


def test_scope_function_tears_down_before_the_response(c):
    c.get("/function-scope")
    assert L.EVENTS[-3:] == ["route", "function-scope teardown", "response.start 200"]


def test_exception_translated_in_yield_dependency(c):
    r = c.get("/translate")
    assert (r.status_code, r.json()) == (400, {"detail": "Owner error: rick"})


def test_swallowed_exception_is_still_a_500(c):
    r = c.get("/swallow")
    assert r.status_code == 500
    assert "swallowing caught ValueError and did not re-raise" in L.EVENTS


def test_httpexception_in_setup_stops_before_the_route(c):
    r = c.get("/denied")
    assert r.status_code == 403 and "route must not run" not in L.EVENTS


def test_sync_dependency_runs_in_the_threadpool(c):
    t = c.get("/threads").json()
    assert t["sync_dependency"].startswith("AnyIO worker thread")
    assert t["async_dependency"] == t["async_route"]     # on the event loop thread

What the dependencies put into the OpenAPI schema, and one real trap pinned as a test:

py
"""Dependencies document themselves: their parameters and security schemes reach OpenAPI."""
from app.main import create_app


def schema():
    return create_app().openapi()


def test_dependency_parameters_appear_on_the_operation():
    params = {(p["in"], p["name"]) for p in schema()["paths"]["/notes"]["get"]["parameters"]}
    assert {("query", "page"), ("query", "size"), ("header", "x-tenant-id"), ("header", "x-request-id")} <= params


def test_router_dependency_header_on_every_admin_route():
    paths = schema()["paths"]
    for path in ("/admin/stats", "/admin/audit"):
        names = {p["name"] for p in paths[path]["get"]["parameters"]}
        assert "x-api-key" in names


def test_oauth2_scheme_and_scopes():
    s = schema()
    scheme = s["components"]["securitySchemes"]["OAuth2PasswordBearer"]
    assert scheme["flows"]["password"]["tokenUrl"] == "token"
    assert set(scheme["flows"]["password"]["scopes"]) == {"notes:read", "notes:write"}
    # Security(..., scopes=[...]) declarations are merged per operation
    assert s["paths"]["/notes"]["get"]["security"] == [{"OAuth2PasswordBearer": ["notes:read"]}]
    assert s["paths"]["/notes"]["post"]["security"] == [{"OAuth2PasswordBearer": ["notes:write", "notes:read"]}]
py
"""Gotcha on FastAPI 0.128.8: a class dependency in a module with postponed annotations.

FastAPI evaluates string annotations with `call.__globals__`. Functions have it; a class
(its __init__ is inspected through the class) and a callable instance do not, so the
strings stay ForwardRefs and the request fails with PydanticUserError (500).
"""
from __future__ import annotations

from typing import Annotated

from fastapi import Depends, FastAPI, Query


class Pagination:
    def __init__(self, page: Annotated[int, Query(ge=1)] = 1) -> None:
        self.page = page


app = FastAPI()


@app.get("/items")
def items(p: Annotated[Pagination, Depends()]) -> dict:
    return {"page": p.page}
py
"""Real traps, pinned on FastAPI 0.128.8."""
from typing import Annotated

import pytest
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient

from app import future_gotcha


def test_class_dependency_with_postponed_annotations_fails_at_request_time():
    c = TestClient(future_gotcha.app, raise_server_exceptions=False)
    # import and startup succeed; the first request fails (PydanticUserError -> 500)
    assert c.get("/items?page=2").status_code == 500


def test_exception_after_yield_cannot_change_a_sent_response():
    app = FastAPI()

    def commit_in_teardown():
        yield "session"
        raise RuntimeError("commit failed after the response")

    @app.get("/t")
    def t(s: Annotated[str, Depends(commit_in_teardown)]) -> dict:
        return {"ok": True}

    r = TestClient(app, raise_server_exceptions=False).get("/t")
    assert (r.status_code, r.json()) == (200, {"ok": True})     # the client saw success
    with pytest.raises(RuntimeError):                             # the failure is only server-side
        TestClient(app).get("/t")

The project file pins the stack (see the version note at the top):

toml
[project]
name = "dependency-injection-depends"
version = "0.1.0"
description = "Snippets for the Dependency Injection chapter: Depends, sub-dependencies, caching, yield, router and global dependencies, overrides"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. On 3.12+ you can move to the latest releases.
requires-python = ">=3.9"
dependencies = [
    "fastapi==0.128.8",
    # Pinned explicitly: the versions every "real run" on the page used.
    "starlette==0.49.3",
    "pydantic==2.13.5",
    "sqlalchemy==2.0.58",
    "uvicorn[standard]==0.39.0",
    # Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
    "eval-type-backport==0.4.0; python_version < '3.10'",
]

[project.optional-dependencies]
test = [
    "httpx==0.28.1",
    "pytest==8.4.2",
]

[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[tool.setuptools]
packages = ["app"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]

The Python angle ​

FastAPI's DI is made of plain Python, which is why it needs no registration step. A dependable is anything callable: a function, a class (calling it builds an instance), or an instance with __call__. FastAPI reads the parameters with inspect.signature. The "graph" is nothing more than parameters whose default or Annotated metadata is a Depends object. typing.Annotated (PEP 593) keeps the real type for the editor and mypy and carries the Depends(...) marker alongside it. Because an Annotated[...] value is an ordinary object, SessionDep = Annotated[Session, Depends(get_session)] is "just standard Python, it's called a 'type alias'", in the docs' words. Yield dependencies are generators. FastAPI wraps them with contextlib.contextmanager or asynccontextmanager and enters them on an AsyncExitStack, so teardown is ordinary finally code and runs last-in, first-out. One sharp edge comes from Python itself. FastAPI resolves string annotations (from __future__ import annotations) through the callable's __globals__. Functions have that attribute; classes and callable instances do not. On 0.128.8 a class dependency in such a module fails at request time with PydanticUserError (500, real run, app/future_gotcha.py). A callable instance fails differently: its __call__ annotation stays a string, so FastAPI treats user as a required query parameter and answers 422 missing, loc: ["query", "user"] (real run with the future import added to a scratch copy of app/deps.py, runs/future-annotations-deps.txt). On 3.9 the snippets avoid X | None in that module and use Optional[X]. Python 3.12's type SessionDep = Annotated[...] statement creates a TypeAliasType rather than a plain Annotated value; FastAPI 0.128.2 (2026-02-05, inside the snippet pin) added "support for PEP695 TypeAliasType", but the docs and the snippets use the assignment form, which works on every version since 0.95.

The concept catalogue ​

The dependency graph of POST /notes (arrows: "needs")request_context (global)Request, Response, X-Request-IDcreate_note (path operation)body: NoteIn, BackgroundTasksSessionDep = get_sessionyield: setup / teardownWriterUserget_current_user [notes:write]TenantUserget_tenant_userget_enginerequest.app.state.enginelifespan (once per process)create_engine(), dispose()CurrentUserget_current_user [notes:read]get_tenantX-Tenant-ID headeroauth2_scheme (per scope set)Authorization: Bearer ...cache key = (callable, scopes, scope)[notes:write] vs [notes:read]:oauth2_scheme and get_current_usereach run twice (real run: 2 + 2)Solved depth-first, in declaration order; each value is cached per (callable, scopes, scope) for this request.

What dependency injection is: inversion of control in one sentence Must-know ​

In plain words: Instead of a function building or looking up the things it needs, it names them, and someone else, the framework, builds them and passes them in. The function stops controlling how its collaborators are made; that control is "inverted" to the caller.

Common misunderstanding: "Dependency injection needs a container, a registry or decorators on every service." Passing a collaborator as a constructor or function argument is already dependency injection; Fowler calls that form Constructor Injection. A container only automates the wiring. FastAPI's version has no container at all: the "registration" is the function signature.

Definition: The FastAPI docs: "'Dependency Injection' means, in programming, that there is a way for your code (in this case, your path operation functions) to declare things that it requires to work and use: 'dependencies'. And then, that system (in this case FastAPI) will take care of doing whatever is needed to provide your code with those needed dependencies ('inject' the dependencies)." Fowler names three styles: "Constructor Injection, Setter Injection, and Interface Injection". He contrasts them with the Service Locator, where "every user of a service has a dependency to the locator". The Dependency Inversion Principle is the design rule behind it: high-level code depends on abstractions it owns, and the wiring decides the concrete implementation.

     Without DI (route fetches)                    With DI (route declares)
1    def list_notes(request):                      def list_notes(session: SessionDep, user: TenantUser):
2        db = ServiceLocator.get("db")    <- asks      ... uses session, user
3        user = parse_auth(request.headers)        FastAPI, per request:
4        ... uses db, user                         4  solve graph: get_engine -> get_session; oauth2_scheme -> get_current_user
5                                                  5  call list_notes(session=..., user=...)
6    test: patch ServiceLocator globals            test: app.dependency_overrides[get_current_user] = fake

Real scenario: a payments route that needs the current user, a database session and a client for the payment provider; a public route that needs only a rate-limit check; a multi-tenant SaaS where every query must be filtered by the tenant from a header; an admin router where every route needs an API key; a test suite that must never call the real identity provider.

TermMeaningFastAPI form
Inversion of controlThe framework calls your code and decides what it receivesPath operations and dependables are called by FastAPI
Dependency injectionThe collaborators are passed in, not fetchedDepends(...) parameters
Service locatorCode asks a registry for collaboratorsAnti-pattern here (see Anti-patterns)
Constructor injectionCollaborators are __init__ argumentsClass dependencies, and plain Python services
DI containerA registry that builds objects from bindingsNot built in; Laravel and fx have one
Composition rootThe one place where the graph is assembledThe signatures plus create_app()

Fix / how to use it: let routes and services receive collaborators; never import a live connection or a global client into business code; build long-lived objects in the lifespan and hand them out with a dependency.

Depends() and the dependable Must-know ​

In plain words: Depends(get_x) tells FastAPI: "before calling this function, call get_x and put its result here". get_x can declare query parameters, headers, cookies, a body, other dependencies, Request, Response and BackgroundTasks, exactly like a route.

Common misunderstanding: "Write Depends(get_x())." The docs: "You don't call it directly (don't add the parenthesis at the end), you just pass it as a parameter to Depends()." Depends(get_x()) passes the result of one call made at import time, which is not callable. The other misreading is "a dependency is a special type of function". It is "a path operation function without the 'decorator'".

Definition: The reference signature in the pinned release is Depends(dependency=None, *, use_cache=True, scope=None) (params.py in 0.128.8), and 0.163.0 adds max_concurrency. The tutorial: "Whenever a new request arrives, FastAPI will take care of: Calling your dependency ('dependable') function with the correct parameters. Get the result from your function. Assign that result to the parameter in your path operation function." The dependency's request inputs are validated and documented: "All the request declarations, validations and requirements of your dependencies (and sub-dependencies) will be integrated in the same OpenAPI schema." The snippet test asserts that page, size, x-tenant-id and x-request-id, all declared inside dependencies, are parameters of GET /notes in /openapi.json.

     def get_tenant(x_tenant_id: Annotated[str, Header(pattern=...)]) -> str
1    GET /notes  X-Tenant-ID: acme
2    FastAPI: list_notes needs tenant: TenantDep -> Depends(get_tenant)
3    read header x-tenant-id "acme", validate pattern -> ok
4    call get_tenant(x_tenant_id="acme") -> "acme"
5    list_notes(..., tenant="acme", ...)
6    X-Tenant-ID: Bad_Tenant -> 422 string_pattern_mismatch, loc ["header","x-tenant-id"] (real run)

Real scenario: shared query filters (q, skip, limit), a tenant header, an Accept-Language reader, a "current user" dependency, a feature flag check, a database session, a settings object.

Dependable declaresFastAPI reads it fromAppears in OpenAPI?
page: int = 1Query stringYes, on every route that uses it
x_tenant_id: Annotated[str, Header()]Header x-tenant-idYes
session_id: Annotated[str | None, Cookie()] = NoneCookieYes
body: SomeModelJSON body (merged with the route's body)Yes
request: Request, response: ResponseInjected objectsNo
tasks: BackgroundTasksThe request's task listNo
security_scopes: SecurityScopesScopes of all dependantsNo (scopes appear under security)
x: Annotated[X, Depends(f)]The result of ff's own inputs do

Fix / how to use it: write the dependable as a small, typed function; pass it uncalled; let it declare its own inputs with Query()/Header() so they are validated once and documented everywhere.

Class dependencies Must-know ​

In plain words: A class is callable (calling it creates an instance), so a class can be a dependency. FastAPI reads the parameters of __init__, builds the instance per request and injects it. You get attribute access and editor completion instead of a dict.

Common misunderstanding: "In Annotated[Pagination, Depends(Pagination)] the first Pagination is what FastAPI calls." The docs say the first one "doesn't have any special meaning for FastAPI"; the argument of Depends is what is called. The shortcut Annotated[Pagination, Depends()] means "call the annotated class". A second trap is real on 0.128.8. In a module with from __future__ import annotations, a class dependency's __init__ annotations stay strings. The app starts, and the first request fails with PydanticUserError: TypeAdapter[...ForwardRef(...)] is not fully defined (500, tests/test_gotchas.py).

Definition: "What FastAPI actually checks is that it is a 'callable' (function, class or anything else) and the parameters defined." The tutorial calls Depends() without arguments "just a shortcut", for the case where "the dependency is specifically a class that FastAPI will 'call' to create an instance of the class itself".

     class Pagination: __init__(self, page: Query(ge=1) = 1, size: Query(ge=1, le=100) = 20)
1    PageDep = Annotated[Pagination, Depends()]
2    GET /notes?page=2&size=2
3    FastAPI: Pagination(page=2, size=2) -> instance; .offset == 2
4    SELECT ... LIMIT 2 OFFSET 2 -> ids [3, 4] (real run)
5    GET /notes?page=0 -> 422 greater_than_equal, loc ["query","page"] (real run)

Real scenario: pagination and sorting parameters shared by every list endpoint; a filter object (status, created_after, q); a "request context" object with locale and time zone; a Pydantic model used as a query model (owned by Request Validation).

FormCalled by FastAPIInjected valueWhen to use
Depends(common_params) returning dictthe functiondictNever in new code: no completion
Annotated[Pagination, Depends(Pagination)]the classinstanceExplicit
Annotated[Pagination, Depends()]the annotated classinstanceShortcut
Annotated[Filters, Query()] with a Pydantic modelPydanticmodelMany query fields, validators
Annotated[Any, Depends(Pagination)]the classinstanceWorks, loses typing

Fix / how to use it: class dependencies for parameter groups; no from __future__ import annotations in the module that defines class or callable-instance dependencies on 0.128.8 (use Optional[X] on 3.9; on 3.10+ X | None evaluates at runtime anyway).

Annotated aliases and SessionDep Must-know ​

In plain words: Write the dependency once as a type alias, SessionDep = Annotated[Session, Depends(get_session)], and use session: SessionDep in every route. The alias carries both the type (for the editor) and the instruction (for FastAPI).

Common misunderstanding: "An alias is a FastAPI feature with its own rules." It is a plain variable holding an Annotated object. One rule does follow from that, though. Since 0.163.0, a Depends object with max_concurrency shares its limit between every route that reuses the same alias ("To share a limit, reuse the same Depends() object, for example in an Annotated alias like this one").

Definition: The tutorial: "because we are using Annotated, we can store that Annotated value in a variable and use it in multiple places", and "the type information will be preserved, which means that your editor will be able to keep providing you with autocompletion, inline errors, etc. The same for other tools like mypy." The SQLModel tutorial in the FastAPI docs defines exactly SessionDep = Annotated[Session, Depends(get_session)] and explains the goal: "We will create a FastAPI dependency with yield that will provide a new Session for each request. This is what ensures that we use a single session per request."

     SessionDep = Annotated[Session, Depends(get_session)]
1    def list_notes(session: SessionDep, ...)     -> mypy sees Session; FastAPI sees Depends(get_session)
2    def create_note(session: SessionDep, ...)    -> same object, same cache key
3    request: get_engine(request) -> engine (app.state)
4             get_session(engine) -> Session(engine), yield
5             list_notes(session=<Session>)
6             teardown: session.close() -> SQL log shows ROLLBACK of the read transaction (real run)

The SQL that list_notes sends through the injected session, captured with echo=True (real run, runs/sql-echo.txt), and the schema SQLAlchemy created for it:

sql
-- GET /notes?page=2&size=2 with X-Tenant-ID: acme (SQLAlchemy 2.0.58, SQLite)
BEGIN (implicit);
SELECT notes.id, notes.tenant_id, notes.title, notes.owner
FROM notes
WHERE notes.tenant_id = ? ORDER BY notes.id
 LIMIT ? OFFSET ?;            -- parameters ('acme', 2, 2): tenant from get_tenant, size and offset from Pagination
ROLLBACK;                     -- session.close() in get_session's finally ends the read transaction

-- the DDL create_all() emitted for app/db.py (same log); the composite unique key is what the Before app trips over
CREATE TABLE notes (
    id INTEGER NOT NULL,
    tenant_id VARCHAR(32) NOT NULL,
    title VARCHAR(120) NOT NULL,
    owner VARCHAR(50) NOT NULL,
    PRIMARY KEY (id),
    UNIQUE (tenant_id, title),
    FOREIGN KEY(tenant_id) REFERENCES tenants (id)
);
CREATE INDEX ix_notes_tenant_id ON notes (tenant_id);

Real scenario: SessionDep, CurrentUser, AdminUser, TenantDep, SettingsDep, HttpClientDep in an app/dependencies.py that every router imports; a type checker that flags session.scalar(...) misuse because the type is Session, not Any.

AliasExpands toLifetime of the value
SessionDepAnnotated[Session, Depends(get_session)]Request
PageDepAnnotated[Pagination, Depends()]Request
TenantDepAnnotated[str, Depends(get_tenant)]Request
CurrentUserAnnotated[User, Security(get_current_user, scopes=["notes:read"])]Request
WriterUserAnnotated[User, Security(get_current_user, scopes=["notes:write"])]Request (separate cache key)
TenantUserAnnotated[User, Depends(get_tenant_user)]Request

Fix / how to use it: one alias per dependency in app/dependencies.py; routes import aliases, not dependables; name aliases after what they give (SessionDep), not how (GetSessionDep).

Sub-dependencies and the dependency graph Must-know ​

In plain words: A dependency can have its own dependencies. get_tenant_user needs the current user and the tenant; the current user needs the bearer token. FastAPI follows these links into a tree (a graph, once nodes are shared) and solves it from the leaves up.

Common misunderstanding: "I must list every sub-dependency on the route." The route declares only what it uses. The docs: "Notice that we are only declaring one dependency in the path operation function, the query_or_cookie_extractor. But FastAPI will know that it has to solve query_extractor first, to pass the results of that to query_or_cookie_extractor while calling it."

Definition: "You can create dependencies that have sub-dependencies. They can be as deep as you need them to be." A function that has a dependency and is itself a dependency is "a 'dependable' itself" and "a 'dependant' too". In the 0.128.8 source, solve_dependencies loops over dependant.dependencies in declaration order. For each one it first solves that node's own sub-dependencies (recursively), then takes the value from the cache or calls it, and finally reads the node's path, query, header, cookie and body parameters.

     POST /notes, graph from the diagram above
1    request_context            (global)
2    get_engine -> get_session  (SessionDep: yield, setup now)
3    oauth2_scheme -> get_current_user[notes:write]   (WriterUser)
4    oauth2_scheme[notes:read] -> get_current_user[notes:read] -> get_tenant -> get_tenant_user   (TenantUser)
5    body NoteIn validated, Request, BackgroundTasks injected
6    create_note(...) runs; oauth2_scheme and get_current_user each ran twice (real run: 2 + 2 calls; a security
     scheme's cache key includes the scopes it is solved under, so the notes:write and notes:read branches do not share it)

Real scenario: get_current_active_user built on get_current_user built on oauth2_scheme; a tenant-aware repository built on a session and a tenant; a permission check built on the user and the resource loaded by id.

Graph propertyBehaviour (0.128.8, real or source)
DepthUnlimited
Shared nodeSolved once per request, value reused (cache)
Same callable, different Security scopesDifferent cache keys: called once per distinct scope set; this includes the security scheme below it (oauth2_scheme ran twice on POST /notes)
Validation errors in several nodesCollected: one 422 with all detail entries
HTTPException in a nodeStops the solve; later nodes and the route do not run
CyclesPython cannot express a cycle without a forward reference; do not build one

Fix / how to use it: build small dependables and compose them; keep each one's job single (read the token, load the user, check the tenant); let the route name only the top node.

Resolution order Important ​

In plain words: Global (app) dependencies run first, then the router's, then the decorator's, then the parameter dependencies in the order they appear in the signature, then your function.

Common misunderstanding: "The order of parameters does not matter for dependencies." It does not matter for where values come from, but it does decide which side effect happens first. A rate limiter declared after the session dependency opens a session for requests it then rejects.

Definition: The bigger-applications tutorial: "The router dependencies are executed first, then the dependencies in the decorator, and then the normal parameter dependencies." The snippet probe confirms the full order including the app level (real run, test_resolution_order_app_router_decorator_parameter).

     GET /order on app/lifecycle.py (real run)
1    app dependency
2    router dependency
3    decorator dependency
4    parameter dependency
5    route
6    response.start 200

Real scenario: an API-key check on the router that must reject before a database session is opened; a request-id dependency that must run before anything logs; a tenant check that must precede every tenant-filtered query.

LevelDeclared onRunsGets the value?
1FastAPI(dependencies=[...])FirstNo
2APIRouter(dependencies=[...]) / include_router(..., dependencies=[...])SecondNo
3@router.get(..., dependencies=[...])ThirdNo
4Function parameters, left to rightFourthYes
5Inside each node: its sub-dependencies firstDepth-firstYes, to the parent

Fix / how to use it: put cheap rejecting checks (API key, feature flag) at router or decorator level, expensive resources (sessions, clients) last in the signature.

Caching and use_cache: one value per request Must-know ​

In plain words: If several parts of the graph need the same dependency, FastAPI calls it once per request and gives everyone the same value. A new request gets a new call.

Common misunderstanding: "Cached means cached across requests." The cache is a dictionary created per request (dependency_cache = {} in solve_dependencies). The second misunderstanding: "the same function is always one cache entry". The cache key in 0.128.8 is (call, scopes_for_cache, computed_scope). So Security(get_current_user, scopes=["notes:write"]) and Security(get_current_user, scopes=["notes:read"]) in the same request are two entries, and the function runs twice. The snippet measured it: POST /notes called the token lookup 2 times, DELETE /notes/{id} 1 time.

Definition: The tutorial: "If one of your dependencies is declared multiple times for the same path operation, for example, multiple dependencies have a common sub-dependency, FastAPI will know to call that sub-dependency only once per request." The opt-out: "you can set the parameter use_cache=False when using Depends". The reference adds that this ensures "the dependency is called again (if declared more than once) in the same request."

     GET /cache (left and right both need counted)      GET /nocache
1    counted() -> 1, stored under key(counted)            counted() -> 1
2    left(n=1)                                            Depends(counted, use_cache=False) -> counted() -> 2
3    right(n=1)  (cache hit)                              {"a": 1, "b": 2, "calls": 2}  (real run)
4    {"left": 1, "right": 1, "calls": 1}  (real run)
5    next request: cache is new -> calls 2

Real scenario: the current user loaded once although the route, a permission check and an audit dependency all need it; a session shared by a repository dependency and the route; a "now" timestamp that must be identical for every part of one request (cached), versus a fresh UUID per use (use_cache=False).

SituationCalls per request
Same Depends(f) used by three dependants1
Depends(f) first, then Depends(f, use_cache=False)2 (real run)
Depends(f, use_cache=False) first, then Depends(f)1: the uncached call still stores its result, and the later cached declaration reuses it (real run, /nocache-first)
Security(f, scopes=["a"]) and Security(f, scopes=["b"])2 (cache key has scopes)
Security(f, scopes=["a"]) twice1
Depends(f) and Depends(f, scope="function")2 (cache key has the scope; real run, runs/probe6-output.txt)
Two different requests1 each
Overridden f1 (the override is cached under the original key)

The exact rule in the 0.128.8 loop: a declaration with use_cache=False never reads the cache, but after any call the result is stored under the key if nothing is stored there yet. So use_cache=False guarantees a fresh call for that declaration only; a later cached declaration of the same callable reuses whatever the first call produced, uncached or not (tests/test_lifecycle.py::test_uncached_declaration_first_feeds_the_cache).

Fix / how to use it: rely on the cache for expensive lookups (user, tenant, settings); know that scopes split it; use use_cache=False only for values that must be fresh per use, and put such a declaration after the cached ones if they must not see its value.

Dependencies with yield: setup and teardown Must-know ​

In plain words: A dependency that yields instead of returns gets two halves. The code before yield runs before your route; the yielded value is injected; the code after yield runs when the request is finished. Put the cleanup in finally so it runs on errors too.

Common misunderstanding: "I should decorate it with @contextmanager." The docs: "you don't have to use the decorators for FastAPI dependencies (and you shouldn't). FastAPI will do it for you internally." A second one: "yield twice for two values". The docs: "Make sure to use yield one single time per dependency."

Definition: "FastAPI supports dependencies that do some extra steps after finishing. To do this, use yield instead of return, and write the extra steps (code) after." "Any function that is valid to use with: @contextlib.contextmanager or @contextlib.asynccontextmanager would be valid to use as a FastAPI dependency." "If you use a try block in a dependency with yield, you'll receive any exception that was thrown when using the dependency... you can use finally to make sure the exit steps are executed, no matter if there was an exception or not." For trees: "FastAPI will make sure that the 'exit code' in each dependency with yield is run in the correct order." That order is the reverse of setup, because each dependency "needs the value from" its sub-dependency "to still be available" during its own exit code.

Yield dependencies: setup, response, background tasks, teardowntimescope="request" (default)a setupb setupc setuprouteresponse sent(status 200)backgroundtasksc teardownb teardowna teardownTeardown is the reverse of setup (a stack): c still has b, b still has a while they clean up.Depends(early, scope="function") (0.121.0+)setuprouteteardownresponse sentfrees the resource beforea slow or streamed responseHistory of "when does the code after yield run" (release notes)before 0.106.0: after the response (and after background tasks); exceptions after yield could not change the response0.106.0 (2023-12): before the response is sent; using yielded resources in background tasks no longer supported0.118.0 (2025-09): back to after the response (StreamingResponse needed the session) | 0.121.0 (2025-11): scope="function"
     GET /teardown: dep_c -> dep_b -> dep_a, all yield (real run, 0.128.8)
1    a setup
2    b setup
3    c setup
4    route  (adds a background task)
5    response.start 200
6    background task ran
7    c teardown -> b teardown -> a teardown

Real scenario: a database session closed in finally; a lock released; a temporary directory removed; a tracing span ended; an httpx client per request in a legacy design (better: one client in the lifespan); an async with resource wrapped by an async generator dependency.

Part of the generatorRunsSees
Before yieldBefore the route, in graph orderIts own parameters and sub-dependencies
yield valueValue injected—
except SomeErrorIf the route or a later dependency raised SomeErrorThe exception
After yield (no exception)After the response (default)Sub-dependency values still alive
finallyAlways—
A second yieldNever validRuntimeError from contextlib

Fix / how to use it: the try/yield/except: rollback; raise/finally: close shape of get_session; one resource per dependency; async generator when the cleanup awaits.

Exceptions in dependencies: HTTPException, except, re-raise Must-know ​

In plain words: A dependency can stop the request by raising HTTPException before the route runs: that is how auth works. A yield dependency also sees exceptions raised after its yield (in the route or later dependencies) and can translate them, but it must re-raise or raise something new.

Common misunderstanding: "If my dependency catches the exception, the client gets my nice answer." If you catch and do not raise, the docs say "FastAPI won't be able to notice there was an exception", and "the client will see an HTTP 500 Internal Server Error response as it should... but the server will not have any logs or any other indication of what was the error". The snippet run shows the 500 (GET /swallow). The original ValueError is lost, but 0.128.8 does not stay completely silent: with TestClient's default raise_server_exceptions=True the request raises FastAPIError: Response not awaited. There's a high chance that the application code is raising an exception and a dependency with yield has a block with a bare except, or a block with except Exception, and is not raising the exception again. That error comes from a response_awaited check in routing.py, so it points at the swallowing dependency, not at the real cause. The behaviour changed in 0.110.0. Before it, a swallowed exception "would be automatically raised/forwarded to any exception handlers".

Definition: "If you catch an exception in a dependency with yield, unless you are raising another HTTPException or similar, you should re-raise the original exception." Translation is allowed: the tutorial's get_username catches OwnerError after yield and raises HTTPException(status_code=400, ...). The client then gets the 400 (real run: {"detail": "Owner error: rick"}). This works because the route's exception is thrown into the generator before the response is built.

     /denied: raise HTTPException(403) before yield/return   /translate: route raises OwnerError
1    dependency raises 403                                   translating() yielded "rick"
2    route NOT called ("route must not run" absent)          route raises OwnerError
3    403 {"detail": "denied in dependency"}                  exception thrown into generator at yield
4                                                            except OwnerError -> raise HTTPException(400)
5                                                            400 {"detail": "Owner error: rick"} (real run)

Real scenario: 401/403 from auth dependencies; 404 from a "load resource by id or fail" dependency; a database dependency that maps IntegrityError to 409 (better done in the route or a handler); a session dependency that rolls back and re-raises.

Exception in dependency: where it is raisedWhat the client gets
HTTPException from dependency, before yield/returnThat status; the route does not run
Any exception in the route, dependency has except ...: raiseNormal handling (handler or 500), the dependency cleaned up
Route exception translated to HTTPException in exceptThe translated status (400 in the probe)
Route exception caught and not re-raised500; the original exception is lost, the server only sees FastAPIError: Response not awaited (0.128.8, real run)
Exception raised after yield on the success pathThe client already has its 200; the error only surfaces server-side (real run: TestClient re-raises RuntimeError)
Validation error in a dependency's parameters422, the route does not run

Fix / how to use it: raise HTTPException for "you may not continue"; in yield dependencies, except: rollback(); raise; map domain exceptions in exception handlers (Exceptions & Responses) rather than in dependencies.

When teardown runs: response first, background tasks, scope="function" Must-know ​

In plain words: On current FastAPI the order is response sent before teardown: the code after yield runs after the client already has the response. If you need it to run before, for example to release a database connection before a long streamed response, declare the dependency with scope="function".

Common misunderstanding: "Commit after yield, it is the natural end of the request." With the default scope the commit runs after the response is sent, so a failed commit cannot turn the 200 into an error any more. The snippet's get_session therefore only rolls back and closes, and create_note commits inside the route, where an IntegrityError becomes a 409 (real run). A second misunderstanding: "the yielded session is gone when background tasks run". In the real run on 0.128.8 the order was response start → background task → teardown. The docs still say to give background tasks their own resources, and this behaviour has changed between versions.

Definition: "Normally the exit code of dependencies with yield is executed after the response is sent to the client. But if you know that you won't need to use the dependency after returning from the path operation function, you can use Depends(scope="function")". The two values: "'function': start the dependency before the path operation function that handles the request, end the dependency after the path operation function ends, but before the response is sent back to the client" and "'request': ... but end after the response is sent back to the client". "If not specified and the dependency has yield, it will have a scope of 'request' by default." And a constraint: "When you declare a dependency with a scope='request' (the default), any sub-dependency needs to also have a scope of 'request'." The history is in the one-minute table. On background tasks, the advanced guide's section on the 0.106.0 change says: "you should create the resources for background tasks inside the background task itself... instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object".

     GET /function-scope: Depends(early, scope="function")   (real run)
1    app dependency
2    function-scope setup
3    route
4    function-scope teardown       <- before the response
5    response.start 200

Background tasks and yield dependencies interact through that order: in the pinned run the background task ran after the response and before the teardown, so the yielded session was technically still open. The reason is in routing.py of 0.128.8: the request exit stack wraps await response(scope, receive, send), and Starlette runs a response's background tasks inside that call. The docs do not promise this, and the advanced guide tells you to give background tasks their own resources.

Real scenario: a StreamingResponse that streams rows from the session (needs the default, request scope); a slow streamed file download that only needed the session to authorise the user (scope="function" frees the connection early); an audit background task that gets note.id and the request id, never the session (the snippet's write_audit).

NeedChoose
Close the session no matter whatfinally: session.close() (any scope)
Commit result must decide the status codeCommit in the route (or a service called by it)
Resource used while streaming the responseDefault scope="request"
Resource only needed to authorise, response is slowscope="function"
Background task needs dataPass ids and plain values; open its own session
Cleanup must not run twiceOne yield dependency per resource, cached per request

Fix / how to use it: commit in the route; close in the dependency; scope="function" for early release; background tasks get ids.

Dependencies in the path operation decorator Important ​

In plain words: When a dependency is there for its side effect ("check the role", "verify the key") and the route does not need its return value, list it in the decorator's dependencies=[...] instead of adding an unused parameter.

Common misunderstanding: "Decorator dependencies cannot return anything or use sub-dependencies." They can do both; the value is simply discarded. The docs: "they can return values or not, the values won't be used. So, you can reuse a normal dependency (that returns a value) you already use somewhere else". The snippet's require_admin returns the user and is used in a decorator.

Definition: "The path operation decorator receives an optional argument dependencies... These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your path operation function." The reason given: "Some editors check for unused function parameters, and show them as errors."

     @notes.delete("/{note_id}", status_code=204, dependencies=[Depends(require_admin)])
1    DELETE /notes/1  Bearer bob-token    -> require_admin: "admin" not in roles -> 403 (real run)
2    DELETE /notes/1  Bearer alice-token  -> require_admin returns user (discarded)
3                                          -> delete_note(note_id=1, session, user) -> 204 (real run)
4    the user is solved once: require_admin and TenantUser share the cache entry (1 call, real run)

Real scenario: role checks, feature flags, rate limits, idempotency-key presence checks, "maintenance mode" switches, audit logging of access to sensitive routes.

You needPut it
The value in the routeParameter
Only the checkDecorator dependencies=[...]
The check on many routesRouter dependencies=[...]
The check on all routesFastAPI(dependencies=[...])
The value and the checkParameter (the check raises)

Fix / how to use it: guards in decorators, data in parameters; and keep guards cheap, because they run before the parameter dependencies.

Router and global dependencies: APIRouter(dependencies=...) and FastAPI(dependencies=...) Must-know ​

In plain words: APIRouter dependencies, a list on APIRouter(dependencies=[...]), run for every route of that router; on the FastAPI app it runs for every route of the app. Their return values are discarded, like decorator dependencies.

Common misunderstanding: "A global dependency runs for every request, so it is a middleware." It runs only for requests that matched a route. In the real run, GET /nope (404) has no X-Request-ID header, because request_context never ran. It also cannot change a response that an HTTPException builds. The 401 from /whoami lost the header that request_context had set on the injected Response (real run). Use middleware for "every request, every response".

Definition: Global: "Similar to the way you can add dependencies to the path operation decorators, you can add them to the FastAPI application. In that case, they will be applied to all the path operations in the application". Router: "we can add a list of dependencies that will be added to all the path operations in the router and will be executed/solved for each request made to them", and "Having dependencies in the APIRouter can be used, for example, to require authentication for a whole group of path operations." The same dependencies= is accepted by app.include_router(...). The 0.137.0 release notes, after the pin, mention that routers are now kept as a tree; they list "Dependencies per router" among the "Future Features Enabled". They also record a "Non Objective": dependencies that run even for a 404 were discarded, because "Executing dependencies in the router that did not find a match would not make sense".

     admin = APIRouter(prefix="/admin", dependencies=[Depends(verify_api_key)])
1    GET /admin/stats (no header)          -> 422 missing header x-api-key   (real run)
2    GET /admin/stats  X-API-Key: x        -> 403 "Bad API key"
3    GET /admin/stats  X-API-Key: admin-key -> 200 {"acme": 5, "globex": 1}
4    /openapi.json: x-api-key is a parameter of /admin/stats and /admin/audit (test_openapi)
5    GET /nope -> 404 from the router, no global dependency ran, no X-Request-ID

Real scenario: /admin routers behind an API key or an admin role; /internal routers behind an mTLS-forwarded header check; a global tenant resolver in a multi-tenant SaaS; a global "API version is supported" check; a router per partner with its own auth.

NeedRouter/global dependencyMiddleware
Runs for unmatched paths (404/405)NoYes
Can read typed, validated headersYes, and documents themRaw headers only
Appears in OpenAPIYesNo
Can be overridden in testsYesNo (remove or configure it)
Sees and edits every responseNo (lost on HTTPException)Yes
Order relative to othersapp → router → decorator → paramsWraps everything

Fix / how to use it: auth and tenant checks as router or global dependencies (documented, overridable); request ids, timing and security headers in middleware.

Parameterised dependencies: callable classes and closure factories Important ​

In plain words: Sometimes the same check needs a setting: "require role admin" or "require role editor". Make a class whose __init__ takes the setting and whose __call__ is the dependency, and use an instance in Depends(...). A function that returns a new dependency function (a closure) does the same.

Common misunderstanding: "FastAPI reads __init__ of a callable instance." For an instance, "FastAPI won't ever touch or care about init, we will use it directly in our code"; it analyses __call__. The test trap that follows: app.dependency_overrides[RoleChecker] = ... does nothing. The key must be the instance used in the route. The snippet keeps it in a module variable, require_admin = RoleChecker("admin"), and the real run gave 403 with the class as key and 204 with the instance.

Definition: "In Python there's a way to make an instance of a class a 'callable'. Not the class itself (which is already a callable), but an instance of that class. To do that, we declare a method call". "In this case, this call is what FastAPI will use to check for additional parameters and sub-dependencies". And: "In the chapters about security, there are utility functions that are implemented in this same way." OAuth2PasswordBearer(tokenUrl=...) is such an instance.

     require_admin = RoleChecker("admin")             requires_feature("beta") -> check (a closure)
1    import time: __init__(role="admin") runs once    import time: factory runs once per decorator
2    request: FastAPI calls require_admin(user=...)   request: check(request) reads app.state.features
3    "admin" not in user.roles -> 403                 features["beta"] is False -> 404 (real run)
4    override key: require_admin (the instance)       override key: the returned function object

Real scenario: RoleChecker("admin"), ScopeChecker("billing:write"), RateLimit(times=10, seconds=60), requires_feature("beta"), ValidatedResource(model=Order) that loads by id and 404s; the security classes (OAuth2PasswordBearer, APIKeyHeader, HTTPBearer).

FormParameters live inOverride keyNotes
Callable class instanceAttributes set in __init__The instanceKeep the instance in a module variable
Closure factoryClosed-over variablesThe returned functionA new function per call: call the factory once, keep the result
functools.partial(fn, role="admin")Bound argumentsThe partial objectSupported (FastAPI 0.123.x fixed partial + wraps combinations)
Security(fn, scopes=[...])Declared scopesfnScopes collected in SecurityScopes
Plain function per variantHard-codedThe functionFine for two variants, not ten

Fix / how to use it: callable classes for configurable checks; instantiate once at module level; override by that instance; avoid creating instances inline inside Depends(RoleChecker("admin")) in many places (each is a different key and a different cache entry).

Async and sync dependencies: the event loop and the thread pool Important ​

In plain words: Same rule as for routes. An async def dependency runs on the event loop, so it must only await and never block. A plain def dependency runs in the thread pool, so blocking calls (a sync database driver, file I/O) are safe there. You can mix both freely.

Common misunderstanding: "Inside an async def route, my def dependency runs on the loop too." It does not. The real run: in an async def route, the sync dependency ran on AnyIO worker thread and the async dependency on the loop thread, the same thread as the route. Sync dependencies also use the same 40-token thread pool as def routes. A generator dependency's setup and teardown both go through it (contextmanager_in_threadpool in the 0.128.8 source).

Definition: "The same applies for dependencies. If a dependency is a standard def function instead of async def, it is run in the external threadpool." "You can have multiple dependencies and sub-dependencies requiring each other... some of them might be created with async def and some with normal def. It would still work". From Starlette: "The default thread pool size is only 40 tokens... This limit is shared with other libraries: for example FastAPI also uses anyio to run sync dependencies".

     async def threads(s = Depends(sync_dep), a = Depends(async_dep))   (real run)
1    sync_dep  -> run_in_threadpool -> "AnyIO worker thread"
2    async_dep -> awaited on the loop -> event loop thread
3    route     -> same event loop thread as async_dep
4    def get_session (generator) -> contextmanager_in_threadpool: setup and teardown in worker threads

Real scenario: get_session as def with a sync SQLAlchemy engine; async def get_async_session with AsyncSession and an async driver; an async def dependency that awaits an httpx.AsyncClient call to an identity provider; a def dependency that reads a settings file once (better: cache it in the lifespan).

Dependency doesWrite it asWhy
Awaits async I/O onlyasync defNo thread hop
Calls a blocking librarydef (sync dependency threadpool)Thread pool keeps the loop free
Pure computation, microsecondsasync defAvoids a thread hop per request
Blocking call inside async defNeverFreezes every request on the worker
Sync session in a high-concurrency appdef + pool size ≥ busy threads40 tokens shared with routes

Fix / how to use it: match the dependency to the library it calls; size the database pool for the thread pool; prefer async sessions end to end when the app is async (details in SQLAlchemy 2 & SQLModel, thread-pool mechanics in Async Python).

Request and Response injection, request.state Important ​

In plain words: Any dependency can ask for the raw Request (headers, client address, request.app, request.state) and for a Response object whose headers, cookies and status code FastAPI copies onto the real response.

Common misunderstanding: "Headers I set on the injected Response are always sent." Only when the route returns normally. If an HTTPException is raised, the error response is built by the exception handler and the injected Response is discarded (real run: the 401 had no X-Request-ID). Another: "data read from Request is validated". The docs: "if you get data from the Request object directly (for example, read the body) it won't be validated, converted or documented".

Definition: "By declaring a path operation function parameter with the type being the Request FastAPI will know to pass the Request in that parameter." Starlette on per-request storage: "If you want to store additional information on the request you can do so using request.state", and on the app: "You can store arbitrary extra state on the application instance, using the generic app.state attribute". Response as a parameter works in dependencies too (the advanced guide's "Response - Change Status Code" and "Response Headers" pages).

     request_context(request: Request, response: Response, x_request_id: Header() = None)
1    rid = x_request_id or uuid4().hex
2    request.state.request_id = rid            -> /whoami reads it back (real run)
3    response.headers["X-Request-ID"] = rid    -> copied onto the 200 response
4    route raises HTTPException(401)           -> new response, header lost (real run)

Real scenario: client IP for audit logs (request.client.host), request id propagation, request.app.state.engine for the engine, setting a refreshed cookie from an auth dependency, Cache-Control set by a caching dependency.

ObjectLifetimeUse forDo not use for
request.app.stateProcess (per worker)Engine, clients, settings, feature flagsPer-request data, counters across workers
request.stateRequestRequest id, timing, resolved tenantData that must survive the request
Lifespan state (yield {...})Process, shallow-copied into each request.stateShared clients, typed with TypedDictMutable data you expect to be per request
Injected ResponseRequest, success path onlyHeaders and cookies on normal returnsHeaders that must be on errors
Raw Request bodyRequestSignature verification (webhooks)Normal input: declare it instead

Fix / how to use it: read resources from request.app.state inside a dependency (never import them); keep per-request data on request.state; set always-present headers in middleware.

Security dependencies (scopes preview): OAuth2PasswordBearer, Security(), SecurityScopes Must-know ​

In plain words: FastAPI's security tools are dependencies. OAuth2PasswordBearer(tokenUrl="token") is a callable object that reads Authorization: Bearer ... and returns the token string or answers 401. get_current_user depends on it and turns the token into a user. Security() is Depends() plus OAuth2 scopes that show up in OpenAPI.

Common misunderstanding: "OAuth2PasswordBearer validates the token." It only extracts it. Validation (JWT signature, expiry, revocation) is your get_current_user, covered in Authentication in FastAPI. A version note: OAuth2PasswordBearer has returned 401 for a missing header since 0.20.0; the 403 → 401 change of 0.122.0 concerns the other security utilities such as HTTPBearer and the API-key classes. The pinned run returned 401 {"detail":"Not authenticated"} with WWW-Authenticate: Bearer.

Definition: "The oauth2_scheme variable is an instance of OAuth2PasswordBearer, but it is also a 'callable'." "It will go and look in the request for that Authorization header, check if the value is Bearer plus some token, and will return the token as a str. If it doesn't see an Authorization header, or the value doesn't have a Bearer token, it will respond with a 401 status code error (UNAUTHORIZED) directly." The reference: Security(dependency=None, *, scopes=None, use_cache=True); "The only difference with a regular dependency is that it can declare OAuth2 scopes that will be integrated with OpenAPI". "Because the SecurityScopes will have all the scopes declared by dependants, you can use it to verify that a token has the required scopes in a central dependency function". Authorization in depth (roles, scopes, admin routers) is the job of the authorization chapter of this section; this page only shows the dependency shape.

     POST /notes  Bearer bob-token (scopes: notes:read)        (real run)
1    oauth2_scheme -> "bob-token"
2    get_current_user(security_scopes=["notes:write"]) -> user bob
3    "notes:write" not in bob.scopes -> 403, WWW-Authenticate: Bearer scope="notes:write"
4    /openapi.json: POST /notes security [{"OAuth2PasswordBearer": ["notes:write", "notes:read"]}]
5    GET /notes security [{"OAuth2PasswordBearer": ["notes:read"]}]

Real scenario: user login with bearer tokens; machine clients with API keys (APIKeyHeader); scopes per route for third-party apps; WebSocket endpoints that authenticate with the same security dependencies (supported since 0.144.0, after the pin).

ToolReadsOn missing credentialsOpenAPI
OAuth2PasswordBearer(tokenUrl=...)Authorization: Bearer401 Not authenticated (since 0.20.0; real run)oauth2 password flow, scopes
HTTPBearer()Authorization: Bearer401 since 0.122.0 (403 before)http bearer
APIKeyHeader(name="X-API-Key")A header401 since 0.122.0 (403 before; "security classes" in the release note)apiKey in header
Security(get_current_user, scopes=[...])Your dependencyYour codeAdds scopes to the operation
SecurityScopes parameterScopes of all dependantsn/an/a
auto_error=False on the schemes—Returns None instead of raisingSame

Fix / how to use it: one get_current_user behind aliases (CurrentUser, AdminUser); scopes through Security; tests override get_current_user, never the token string.

Overriding dependencies: app.dependency_overrides Must-know ​

In plain words: app.dependency_overrides is a plain dict. Put the original dependable as the key and a replacement as the value, and FastAPI calls the replacement wherever the original appears in any graph. Clear the dict at the end of the test.

Common misunderstanding: "The original still runs and the override post-processes its result." The original does not run, nor do its sub-dependencies. The docs: "You don't want the original dependency to run (nor any of the sub-dependencies it might have)." Real run: with get_current_user overridden, /whoami returned 200 with no Authorization header at all, because oauth2_scheme was never called. And the override is a dependable in its own right: its parameters are read from the request. An override of get_tenant that declares t: Query() turned the tenant from a header into a query parameter (real run).

Definition: "your FastAPI application has an attribute app.dependency_overrides, it is a simple dict. To override a dependency for testing, you put as a key the original dependency (a function), and as the value, your dependency override (another function)." "You can set a dependency override for a dependency used anywhere in your FastAPI application. The original dependency could be used in a path operation function, a path operation decorator (when you don't use the return value), a .include_router() call, etc." The reset: "setting app.dependency_overrides to be an empty dict". Mechanically, solve_dependencies in 0.128.8 does dependency_overrides.get(original_call, original_call) for every node and builds a new dependant from the result.

app.dependency_overrides: swap a node of the graph for one testsolve_dependencies: next nodecall = original callable (the key)overrides.get(call, call)is an override set?noyesoriginal runsget_current_user -> oauth2_schemeneeds Authorization headeroverride runs insteadits own params are read (Query, Header)original's sub-dependencies never runThe key is the object in Depends(...)overrides[RoleChecker] = ... ignored (403)overrides[require_admin] = ... works (204)Reaches every kind of dependencyparameter, decorator, router, globalclear the dict after each test (fixture)
     test_override_a_deep_sub_dependency_the_engine     (real run)
1    engine = make_engine("sqlite:///<tmp>/test.db"); create_schema_and_seed(engine)
2    app.dependency_overrides[get_engine] = lambda: engine
3    POST /notes -> get_session(engine=<test engine>)  (get_session itself still runs)
4    201; the row is in the file database
5    fixture teardown: app.dependency_overrides.clear()

Real scenario: a fake user instead of the identity provider; a test database engine; a frozen clock dependency; a fake payment client; disabling the router's API-key check in tests of the admin routes; a "dry run" mailer in staging (better: configuration).

OverrideEffectSnippet test
[get_current_user] = lambda: TESTERNo token needed; oauth2_scheme skippedtest_override_skips_the_original_and_its_sub_dependencies
[get_engine] = lambda: engineReal get_session on a test enginetest_override_a_deep_sub_dependency_the_engine
[get_tenant] = tenant_from_queryThe override's own Query is readtest_override_can_declare_its_own_parameters
[RoleChecker] = ...Ignored: not the key in the graphtest_parameterised_instance_is_the_key_not_the_class
[require_admin] = ...Guard disabledsame test
[verify_api_key], [request_context]Router and global dependencies replacedtest_router_and_global_dependencies_can_be_overridden
.clear()Real graph backtest_clear_restores_the_real_graph

Fix / how to use it: for testing with overrides, an app factory and a fixture that clears overrides; override at the highest node that removes the external system (the user, not the token; the engine, not the session, when you still want the session logic); full database fixtures in Testing FastAPI.

Lifespan resources vs per-request dependencies: engine vs session, singleton vs per-request Must-know ​

In plain words: Some objects are expensive and thread-safe and should exist once per process: the SQLAlchemy Engine with its connection pool, an httpx.AsyncClient, loaded settings, an ML model. Create them in the lifespan. Other objects are cheap and must not be shared: a Session (a unit of work with its own transaction), the current user. Create those in a dependency, per request. The dependency reads the singleton; the singleton never knows about requests.

Singleton vs per-request vs per-function: who owns whatProcess (one per Uvicorn worker): lifespan before yield ... after yieldEngine + connection poolapp.state.enginehttpx.AsyncClient, settingslifespan state -> request.state4 workers = 4 engines,4 pools, 4 copies of app.stateRequest: the dependency cache lives here; yield teardown after the responseSession (SessionDep)one per request, closed in finallycurrent user, tenantcached for this request onlyrequest.state.request_idper-request scratch spaceFunction: Depends(dep, scope="function") ends when the path operation returns,before the response; a global Session or module-level mutable state belongs to no scope at all

Common misunderstanding: "One global Session is a singleton, just like the engine." A Session holds a transaction and an identity map. Sharing it couples every request's transaction. The Before app shows the result: one IntegrityError and the next unrelated request fails with PendingRollbackError (real run). The opposite mistake is creating an engine per request. That opens a new pool for each request and gains nothing.

Definition: SQLAlchemy's session guide, for web applications: "the basic pattern is create a Session at the start of a web request, call the Session.commit() method at the end of web requests that do POST, PUT, or DELETE, and then close the session at the end of web request". Starlette's lifespan state: "The lifespan has the concept of state, which is a dictionary that can be used to share the objects between the lifespan, and the requests", and "The state received on the requests is a shallow copy of the state received on the lifespan handler." The dictionary-style access request.state["http_client"] "was introduced in Starlette 0.52.0 (January 2026)"; the pin (0.49.3) uses attribute access. FastAPI: "If you provide a lifespan parameter, startup and shutdown event handlers will no longer be called."

     worker process start (Uvicorn, real log: "Application startup complete.")
1    lifespan: engine = make_engine(DATABASE_URL); create_schema_and_seed(engine)
2              app.state.engine = engine; yield {"audit_log": []}
3    request 1: get_engine(request) -> app.state.engine; get_session -> Session(engine) ... close()
4    request 2: same engine, a new Session
5    shutdown ("Application shutdown complete."): engine.dispose()
6    --workers 4: steps 1-5 happen in each of 4 processes: 4 engines, 4 pools

Real scenario: a pool of 10 connections per worker and 4 workers against a database that allows 50; one httpx.AsyncClient per worker so connections to a partner API are reused; a model loaded once per worker; tenant-specific engines in a dict on app.state, chosen by a tenant dependency.

ObjectLifetimeCreated inInjected by
Engine (pool)ProcessLifespanget_engine reading app.state
SessionRequestget_session (yield)SessionDep
httpx.AsyncClientProcessLifespan (async with)A dependency reading request.state
SettingsProcessLifespan or a cached functionSettingsDep
Current userRequestget_current_userCurrentUser
Audit list (snippet)Process, per lifespan runLifespan staterequest.state.audit_log

Fix / how to use it: "engine in the lifespan, session in a dependency" as a rule; every process-wide object reached through a dependency so it can be overridden; pool size × workers ≤ database connection limit (FastAPI in Production).

max_concurrency: limiting concurrent dependency calls (0.163.0, after the pin) Good to know ​

In plain words: Since FastAPI 0.163.0, Depends(get_session, max_concurrency=5) lets at most five calls of that dependency be active at once; the sixth request waits, without holding a worker thread, until a session is closed.

Common misunderstanding: "max_concurrency limits the database pool." FastAPI does not know the pool ("FastAPI doesn't know the size of your database connection pool"). The limit is per Depends object, per event loop and per worker process: "two worker processes with this dependency could have up to ten sessions open between them."

Definition: From the advanced-dependencies page: "Now, up to five requests can have a database session open through this dependency at the same time. If another request needs a session, it waits until one of those sessions is closed. While waiting, it doesn't occupy a worker thread". For yield dependencies "The session counts toward the limit until the exit code finishes closing it", so scope matters. A deadlock warning: a shared Depends(get_session, max_concurrency=1, use_cache=False) used twice in one request waits for itself.

     SessionDep = Annotated[Session, Depends(get_session, max_concurrency=5)]   (0.163.0+, not run)
1    requests 1-5: session opened
2    request 6: waits (no thread held)
3    request 1 finishes; teardown closes its session (after the response with scope="request")
4    request 6 proceeds

Real scenario: protecting a small database from a burst; bounding calls to a rate-limited partner API inside one worker; replacing hand-written asyncio.Semaphore dependencies.

SettingLimit shared by
One alias with max_concurrency=5 used everywhereAll those routes
Depends(get_session, max_concurrency=5) written per routeEach route separately
Two apps in one event loop reusing the aliasBoth apps
Two worker processesNobody: 5 each

Fix / how to use it: only after upgrading past 0.163.0; put the limit on the alias; size it below the pool; prefer scope="function" when the response is slow.

Anti-patterns: global mutable state, service locator, over-injection Must-know ​

In plain words: Three ways to undo the benefits. Module-level objects that hold per-request data. A registry that routes query at runtime. And a signature with fifteen dependencies, where a service object should exist.

Common misunderstanding: "A service locator is DI with a nicer name." The service locator anti-pattern looks like DI because the route does not construct anything itself. Fowler draws the line: "The key difference is that with a Service Locator every user of a service has a dependency to the locator." The routes in the Before app depend on ServiceLocator and on string keys, so nothing in their signatures says what they need. The tests have to mutate the registry and restore it.

Definition: Global mutable state is any module-level object whose contents change per request or per user: a shared Session, a dict cache without locking, a "current user" global. Service locator is Fowler's "object that knows how to get hold of all of the services that an application might need". Over-injection is a route whose signature injects every repository and client directly, so the route does orchestration that belongs in a service. The fix is to inject one service, which is itself built from dependencies.

     over-injected route                                   one service dependency
1    def checkout(s: SessionDep, u: CurrentUser,           def get_checkout(s: SessionDep, pay: PaymentDep,
2        pay: PaymentDep, stock: StockDep, mail: MailDep,      stock: StockDep, mail: MailDep) -> CheckoutService
3        tax: TaxDep, audit: AuditDep, flags: FlagsDep):   def checkout(svc: Annotated[CheckoutService, Depends(get_checkout)],
4        ... 80 lines of orchestration                              user: CurrentUser): return svc.run(user)
5    tests: override 8 dependencies                         tests: override get_checkout, or its parts

Real scenario: a module-level "current tenant" variable (a data leak between requests under concurrency); a get_service("mailer") helper that grew into a locator; a 12-parameter route that nobody can test.

Anti-patternSymptomFix
Global SessionPendingRollbackError after one failure; cross-request dataget_session yield dependency
Global "current user/tenant"Data shown to the wrong user under concurrencyrequest.state or a dependency
Service locatorHidden dependencies; tests mutate a registryDeclare with Depends
Engine per requestNew pool each request; connection stormsEngine in the lifespan
Over-injectionRoutes with 10+ dependenciesA service class built by a dependency
Dependencies with business logicLogic only testable through HTTPPlain functions/classes, injected
Depends deep in the domain layerDomain code imports FastAPIOnly the web layer uses Depends

Fix / how to use it: keep Depends at the edge (routes, dependencies.py), build domain services as plain classes that receive their collaborators in __init__ (constructor injection), and let one dependency assemble a service from the request-scoped parts. Where the dependency arrows point between layers is Clean, Hexagonal & Onion Architecture.

Three worked dependencies: pagination, auth, tenant Important ​

In plain words: Almost every service needs these three. Pagination is a class dependency with validated query parameters. Auth is a chain: bearer token, then user, then scopes. Tenant is a validated header combined with the user into "a user allowed in this tenant".

Common misunderstanding: "The tenant filter can be added in the route." Then one forgotten route leaks data. When the tenant comes from a dependency that every tenant route needs (TenantUser), the check cannot be skipped by accident. Row-level isolation in the database is the stronger second layer.

Definition: The pagination dependency example is Pagination (page ≥ 1, 1 ≤ size ≤ 100, offset property). The auth dependency example is oauth2_scheme → get_current_user(SecurityScopes) → CurrentUser/WriterUser. The tenant dependency example is get_tenant (X-Tenant-ID with a regex) → get_tenant_user (403 if the user's tenant differs).

     GET /notes  Bearer alice-token  X-Tenant-ID: globex     (real run)
1    Pagination(page=1, size=20)
2    get_tenant -> "globex"
3    oauth2_scheme -> "alice-token"; get_current_user -> alice (tenant acme)
4    get_tenant_user: acme != globex -> 403 "User does not belong to this tenant"
5    the SELECT never runs

Real scenario: a B2B SaaS with X-Tenant-ID or a subdomain; cursor pagination instead of offsets for large tables (Pagination); per-tenant rate limits keyed by the tenant dependency.

ExampleDependency kindInputsFailure
PaginationClass, Depends()page, size query422
AuthCallable instance + function + SecurityAuthorization header, scopes401 / 403
TenantFunction + sub-dependency graphX-Tenant-ID header, user422 / 403
Admin guardCallable class in decoratorUser roles403
Feature flagClosure factoryapp.state.features404
API keyRouter dependencyX-API-Key header422 / 403

Fix / how to use it: copy the shapes from app/deps.py; for production auth replace the fake token table with JWT verification (Authentication in FastAPI); for tenant isolation add a database-level guard.

Mechanics ​

What FastAPI does at import time and per request Important ​

At decoration time (@router.get(...)), FastAPI builds a Dependant for the path operation with get_dependant. It calls get_typed_signature on the function, which resolves string annotations with call.__globals__. Each parameter whose Annotated metadata or default is a Depends/Security becomes a sub-dependant, built recursively the same way. App, router and decorator dependencies=[...] are prepended as unnamed sub-dependants. Every Dependant gets a cache_key of (call, scopes_for_cache, computed_scope), where computed_scope is "request" for generator dependables unless scope= says otherwise. Per request, the route handler opens two AsyncExitStacks, one for the request and one for the function, and calls solve_dependencies:

     solve_dependencies(dependant, request, dependency_cache={})       (fastapi 0.128.8, dependencies/utils.py)
1    for sub in dependant.dependencies:                                 # declaration order: app, router, decorator, params
2        call = app.dependency_overrides.get(sub.call, sub.call)        # override lookup on every node
3        solve_dependencies(sub or its override)                        # its own sub-dependencies first (recursion)
4        if sub.use_cache and sub.cache_key in cache: value = cache[key]
5        elif generator:  value = await stack.enter_async_context(cm)   # request stack, or function stack if scope="function"
6        elif coroutine:  value = await call(**values)
7        else:            value = await run_in_threadpool(call, **values)
8        cache.setdefault(sub.cache_key, value)
9    then read path, query, header, cookie params and the body of this dependant; collect errors
10   errors -> RequestValidationError (422); else call the route; exit function stack; send; exit request stack

Two consequences you can observe. Validation errors from all dependencies are collected into one 422 before the route runs, but dependencies whose own inputs are valid have already been called by then (real run, runs/probe6-output.txt: a logging dependency ran, then the 422 for ?n=abc). Order does not help: the loop records a sub-dependency's errors and continues with the next one, so a valid side-effect dependency declared after the failing one still runs (real run, test_validation_error_does_not_stop_a_sibling_side_effect). What does stop it is a dependency link: a dependant is not called when one of its own sub-dependencies has errors, so a side effect that Depends on the validated input is skipped on a 422 (test_side_effect_that_depends_on_the_input_is_skipped). Put side effects in the route, or make the side-effect dependency depend on the inputs it must wait for. And a cached dependency is reused, but its own sub-dependencies are still visited (they are cached too, so nothing is called twice).

How a request flows through the snippet's POST /notes Good to know ​

     POST /notes  Authorization: Bearer alice-token  X-Tenant-ID: acme  X-Request-ID: req-1   (real run)
1    Uvicorn -> Starlette router -> APIRoute for POST /notes
2    request_context: request.state.request_id = "req-1"; response header X-Request-ID
3    get_engine -> app.state.engine; get_session -> Session, yield (request stack)
4    oauth2_scheme -> "alice-token"; get_current_user[notes:write] -> alice
5    get_current_user[notes:read] (second cache key) -> alice; get_tenant -> "acme"; get_tenant_user -> alice
6    body {"title": "new"} -> NoteIn; BackgroundTasks; Request
7    create_note: session.add; session.commit() -> 201 {"id": 7, ...}
8    response sent (201, X-Request-ID: req-1)
9    background task write_audit(log, "req-1", 7)
10   get_session teardown: session.close()

Exact errors, warnings and outputs Must-know ​

Every line below was printed by the snippet run (FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, SQLAlchemy 2.0.58, Uvicorn 0.39.0).

TriggerStatusExact output
No Authorization header (OAuth2PasswordBearer)401{"detail":"Not authenticated"}, www-authenticate: Bearer
Bearer nope401{"detail":"Invalid token"} (from get_current_user)
Missing scope403{"detail":"Missing scope: notes:write"}, www-authenticate: Bearer scope="notes:write"
X-Tenant-ID: Bad_Tenant422{"type":"string_pattern_mismatch","loc":["header","x-tenant-id"],"msg":"String should match pattern '^[a-z][a-z0-9-]{1,31}$'",...}
?page=0422{"type":"greater_than_equal","loc":["query","page"],"msg":"Input should be greater than or equal to 1","input":"0","ctx":{"ge":1}}
Router dependency header missing422{"type":"missing","loc":["header","x-api-key"],"msg":"Field required","input":null}
Duplicate note, committed in the route409{"detail":"A note with this title exists"}
Before app, request after a failed commit500PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush.
Class dependency + from __future__ import annotations500 at request timePydanticUserError: TypeAdapter[typing.Annotated[ForwardRef("Annotated[int, Query(ge=1, description='1-based page number')]"), ...]] is not fully defined
Callable instance (RoleChecker) + from __future__ import annotations422{"type":"missing","loc":["query","user"],"msg":"Field required","input":null}
except ValueError: without raise in a yield dependency500Internal Server Error; server side FastAPIError: Response not awaited. There's a high chance that the application code is raising an exception and a dependency with yield has a block with a bare except... (original ValueError lost)
Exception after yield, success path200 to the clientRuntimeError: commit failed after the response re-raised by TestClient
TestClient(create_app()) without with, then GET /notes—AttributeError: 'State' object has no attribute 'engine' (lifespan never ran)
Uvicorn log for a router-dependency 422—INFO: 127.0.0.1:49252 - "GET /admin/stats HTTP/1.1" 422 Unprocessable Entity
Teardown SQL of a read request—INFO sqlalchemy.engine.Engine ROLLBACK

Solving the classic problems ​

BugSymptomFixCost
Global SessionOne failure breaks every later request; data shared across requestsget_session yield dependency, SessionDep15 lines
Commit after yieldClient gets 200 although the commit failedCommit in the route; dependency only rolls back and closesMove one line
except without raise500s whose cause is lost; logs only show FastAPIError: Response not awaitedexcept: rollback(); raiseOne word
Auth copied per routeOne route forgets the checkCurrentUser alias, router dependency for groupsRefactor
Tenant filter per routeCross-tenant data leakTenantUser dependency on every tenant route; DB-level guardSmall
Headers set in a global dependencyMissing on 401/404/422Middleware for always-present headersSmall
Class or callable-instance dependency in a __future__ module500 (class) or a bogus 422 missing query parameter (instance)Drop the future import there, or use functionsNone
Override keyed by the classOverride silently ignoredKey by the instance used in the routeNone
Overrides leak between testsOrder-dependent testsApp factory + fixture that clears the dictFixture
Background task uses the request's sessionWorks on one version, breaks on anotherPass ids; open a new session in the taskSmall
Engine per requestConnection storms, slow requestsEngine in the lifespan, dependency reads app.stateSmall
Blocking call in an async def dependencyEvery request on the worker stallsdef dependency or async librarySmall
15 injected parametersUntestable orchestration in routesOne service dependencyRefactor

One session per request, cleaned up always ​

The difference between before.SESSION and get_session is the whole lesson. The yield dependency gives each request its own unit of work, rolls back on any exception and closes in finally, so the failure of one request cannot leak into the next. The route commits, so the status code reflects the commit. The test test_create_commits_in_route_and_background_task_gets_ids proves both: a 409 on the duplicate, then a clean 200 on the next request.

Auth and tenancy that cannot be forgotten ​

Make the safe path the short path. TenantUser is shorter to write than reading headers by hand, and it carries the 401, 403 and 422 behaviour with it. Admin routes get the guard from the router, so a new admin route is protected without anyone remembering. The OpenAPI test shows that the documentation stays honest too.

Tests without monkeypatching ​

Every external piece is reached through a dependency (user, engine, clock, HTTP client), so every test swaps exactly one dictionary entry. An app factory gives each test its own app, and a fixture clears the overrides. The Before app needs a try/finally around each global swap; the After app needs one line.

Releasing resources at the right time ​

Know your version's teardown timing (the table). On 0.121.0+ use scope="function" for resources that are only needed to authorise a slow or streamed response. Upgrading past 0.163.0 adds max_concurrency for protecting a small pool.

Choosing ​

SituationUseExtra techniqueReason
Route needs a valueParameter dependency via an aliasAnnotated alias in dependencies.pyTyped, cached, documented
Route needs only a checkDecorator dependencies=[...]Cheap checks firstNo unused parameters
All routes of a group need a checkAPIRouter(dependencies=...)Or include_router(..., dependencies=...)Cannot be forgotten
Every matched route needs itFastAPI(dependencies=...)Keep it cheapRuns before everything
Every request including 404sMiddlewareNot a dependencyDependencies need a matched route
Resource lives for the processLifespan + app.state / lifespan stateDependency that reads itCreated once per worker
Resource per request with cleanupYield dependencyfinallyGuaranteed teardown
Resource only for authorisingDepends(..., scope="function")0.121.0+Released before the response
Configurable checkCallable class instanceModule-level instanceOverridable by instance
Fresh value per useuse_cache=FalseRareBypasses the request cache
Limit concurrent usemax_concurrency (0.163.0+)Same alias everywhereShared limit
Domain servicesPlain classes with constructor injectionOne assembling dependencyFramework-free domain
Large object graphs, many appsA DI container libraryOnly if Depends hurtsExtra concept to learn

Depends vs a DI container (Laravel, Fx) ​

QuestionFastAPI DependsContainer (Laravel service container, Uber Fx)
Where bindings liveIn signatures and aliasesIn providers/modules (bind, fx.Provide)
Default lifetimePer request, cached per requestPer resolve (bind), singleton (singleton), per lifecycle (scoped)
SingletonsLifespan + app.statesingleton(), Fx-managed singletons
Interface → implementationBy which function you passExplicit binding of an interface
Request inputs (query, headers)Read and validated by the dependencyNot the container's job
DocumentationOpenAPI from dependency inputsNone
Test swapapp.dependency_overridesLaravel $this->app->instance(...); Fx: build the test app with fake constructors in fx.Provide
Use outside HTTP (CLI, workers)No: needs a requestYes

For background workers and CLIs, which have no request, build the same services with plain constructor injection in a small composition function and reuse them from the dependencies.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One FastAPI app, one app/dependencies.py, one engine in the lifespan, SessionDep everywhere, CurrentUser from one auth dependency. This chapter's snippet is that shape. A typical shop backend works the same way: SessionDep for the catalog and orders, CurrentUser for the account routes, an admin router behind AdminUser, httpx.AsyncClient to the payment provider in the lifespan, and a tenant or store dependency if it serves several storefronts. Tests override the user and the engine.

Modular monolith and multiple databases ​

Each module (catalog, orders, billing) owns its router, its dependencies module and its service classes. Shared dependencies (session, user, tenant) live in a core package that modules import, never the other way round. With two databases, each gets its own engine in the lifespan and its own session dependency (CatalogSessionDep, BillingSessionDep). A route that needs both opens two sessions, and there is no distributed transaction between them: use an outbox or a saga if the write must span both. Router dependencies enforce module boundaries at the edge (billing routes require the billing scope).

Microservices ​

Dependency injection stops at the process boundary. Inside each service the same patterns apply; between services the "dependency" is a network client. Give each downstream service a typed client class created once in the lifespan (connection reuse) and injected per request through a dependency. The dependency can bind request context: it forwards the request id from request.state, propagates the caller's token or swaps it for a service token, and applies a per-request deadline. Example flow: POST /orders → OrdersClientDep → PaymentsClientDep with an Idempotency-Key header derived from the order id. Tests override the client dependency with a fake; contract tests check the fake against the real API. Auth in microservices usually means validating a JWT locally in get_current_user against the issuer's keys (cached in the lifespan), not calling the identity provider per request.

Distributed data: replicas, caches, sharded databases, multi-region ​

Dependencies are where routing decisions live. A ReadSessionDep can point at a replica engine and a WriteSessionDep at the primary; a "read your writes" rule can live in the dependency, for example "use the primary for 5 seconds after this user wrote", keyed by the user. With sharded or per-tenant databases, a tenant dependency resolves the tenant and picks the engine from a dict built in the lifespan (app.state.engines[tenant.shard]). A cache client (Redis) is a process-wide resource in the lifespan; a per-request cache is the dependency cache itself. Anything kept in process memory (app.state, lifespan state, the snippet's audit list) exists once per worker and per replica, so counters and caches that must be shared belong in Redis or PostgreSQL. Isolation-level choices for those sessions are in Isolation Levels.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesDependency practice
1× (one process)Defaults workEngine in lifespan, SessionDep, auth and tenant dependencies, overrides in tests
10× (several workers or replicas)Pools multiply; per-process state divergesPool size × workers ≤ DB limit; no shared state in app.state; scope="function" for slow responses; thread pool sized for sync dependencies
100× (many services, high fan-out)Tail latency, pool exhaustion, auth costAsync sessions and clients end to end; JWT verified locally with cached keys; max_concurrency (0.163.0+) or a semaphore per downstream; read replicas chosen in the session dependency; request id propagated by middleware

Lab ​

All commands run from docs/snippets/python/dependency-injection-depends/. The outputs marked "real" were produced on CPython 3.9.6 (macOS) with the pinned versions; Python 3.12 with current FastAPI was not run (unverified): expect at least different version numbers, and the tests that pin 0.128.8 behaviour (test_gotchas.py, the event orders in test_lifecycle.py) may change with later releases.

1. Install and run the tests (real) ​

python3 -m venv ~/venvs/did                       # keep the venv outside the repo (.venv/, *.egg-info are not git-ignored)
~/venvs/did/bin/pip install -e '.[test]'
source ~/venvs/did/bin/activate
export PYTHONDONTWRITEBYTECODE=1                  # no __pycache__; pyproject sets -p no:cacheprovider
pytest
# ............................................                             [100%]
# 44 passed in 0.41s
pytest -v          # -v cancels the -q from pyproject: one line per file
# tests/test_before.py .....                                               [ 11%]
# tests/test_gotchas.py ..                                                 [ 15%]
# tests/test_lifecycle.py ............                                     [ 43%]
# tests/test_main.py ................                                      [ 79%]
# tests/test_openapi.py ...                                                [ 86%]
# tests/test_overrides.py ......                                           [100%]
# 44 passed in 0.43s

The resolved versions of that install are in the project's requirements.lock (pip install -r requirements.lock reproduces it). The pytest options include -q, so a test is a dot. With uv on Python 3.12+: uv run --extra test pytest (expected, not run: uv is not installed on the build machine).

2. Watch the order of events (real) ​

pytest tests/test_lifecycle.py -k "order or teardown or scope"
# ...                                                                      [100%]
# 3 passed, 9 deselected in 0.03s
python -c "from fastapi.testclient import TestClient; from app import lifecycle as L; TestClient(L.app).get('/teardown'); print(L.EVENTS)"
# ['app dependency', 'a setup', 'b setup', 'c setup', 'route', 'response.start 200',
#  'background task ran', 'c teardown', 'b teardown', 'a teardown']

Then, in a scratch copy, change Depends(dep_c) in teardown() to Depends(dep_c, scope="function") and rerun the python -c line (real):

# ['app dependency', 'a setup', 'b setup', 'c setup', 'route', 'c teardown',
#  'response.start 200', 'background task ran', 'b teardown', 'a teardown']

Only dep_c moved before the response; its request-scoped sub-dependencies dep_b and dep_a still close after the response and after the background task. That is the rule in the docs: "a dependency with scope of 'function' can have dependencies with scope of 'function' and scope of 'request'", while a request-scoped dependency may only depend on request-scoped ones.

3. Run the server and call it (real) ​

uvicorn app.main:app --port 18917
curl -i -H "Authorization: Bearer alice-token" -H "X-Tenant-ID: acme" "http://127.0.0.1:18917/notes?page=1&size=2"
# HTTP/1.1 200 OK
# x-request-id: d91bb7b3f7a149b9a29c901442ffd543
# [{"id":1,"title":"acme note 1","owner":"alice"},{"id":2,"title":"acme note 2","owner":"alice"}]
curl -i -H "X-Tenant-ID: acme" http://127.0.0.1:18917/whoami
# HTTP/1.1 401 Unauthorized
# www-authenticate: Bearer
# {"detail":"Not authenticated"}                 <- no x-request-id on the error response
curl -s http://127.0.0.1:18917/admin/stats
# {"detail":[{"type":"missing","loc":["header","x-api-key"],"msg":"Field required","input":null}]}
curl -s -H "X-API-Key: admin-key" http://127.0.0.1:18917/admin/stats
# {"acme":5,"globex":1}

The Uvicorn log of that run: Application startup complete. once (one lifespan), four access lines (200, 401 Unauthorized, 422 Unprocessable Entity, 200), and on Ctrl+C Application shutdown complete. (the engine was disposed). Open http://127.0.0.1:18917/docs. The Authorize button comes from OAuth2PasswordBearer, with the scopes notes:read and notes:write. page, size and X-Tenant-ID appear on GET /notes, and X-API-Key on both admin routes.

4. Break it on purpose (real) ​

pytest tests/test_before.py -k poisons          # asserts the 500 on the request after the IntegrityError
# .                                                                        [100%]
# 1 passed, 4 deselected in 0.02s
pytest tests/test_gotchas.py -rA
# PASSED tests/test_gotchas.py::test_class_dependency_with_postponed_annotations_fails_at_request_time
# PASSED tests/test_gotchas.py::test_exception_after_yield_cannot_change_a_sent_response
# 2 passed in 0.01s

Then, in a scratch copy, add from __future__ import annotations at the top of app/deps.py (after the docstring) and call the app (real, runs/future-annotations-deps.txt):

# DELETE /notes/1 (RoleChecker instance): 422 {"detail":[{"type":"missing","loc":["query","user"],"msg":"Field required","input":null}]}
# GET /notes (Pagination class): 500 Internal Server Error

The 500's traceback ends in PydanticUserError ... is not fully defined (saved as runs/forwardref-class-dependency-error.txt; this is how the trap was found).

5. Override in a REPL (real) ​

python - <<'PY'
from fastapi.testclient import TestClient
from app.main import create_app
from app.deps import User, get_current_user
app = create_app()
app.dependency_overrides[get_current_user] = lambda: User(name="test", tenant="acme")
with TestClient(app) as c:
    print(c.get("/whoami", headers={"X-Tenant-ID": "acme"}).json()["name"])
PY
# test                                           <- no Authorization header was sent; oauth2_scheme never ran

For PHP/Laravel developers ​

Laravel solves the same problem with a container, and the difference in shape is the main thing to carry over. The docs: "The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are 'injected' into the class via the constructor or, in some cases, 'setter' methods." You register bindings in a service provider: bind builds a new object per resolve, and "The singleton method binds a class or interface into the container that should only be resolved one time". "The scoped method binds a class or interface into the container that should only be resolved one time within a given Laravel request / job lifecycle", and those instances "will be flushed whenever the Laravel application starts a new 'lifecycle', such as when a Laravel Octane worker processes a new request". The closest FastAPI equivalents are the lifespan for singleton, a cached dependency for scoped, and a use_cache=False dependency for bind. Laravel resolves type-hinted constructor and method parameters automatically ("zero configuration resolution"), and contextual binding (when(...)->needs(...)->give(...)) chooses an implementation per consumer. FastAPI chooses by which callable you pass to Depends. FastAPI has no interface-to-implementation bindings. What Laravel has no counterpart for is a dependency that reads and validates request input, which FastAPI then documents in OpenAPI. In Laravel that is a Form Request or the controller's job. Under PHP-FPM each request builds a fresh container, so a "singleton" lives one request; under Octane it lives for the worker, which is exactly FastAPI's lifespan model.

php
// app/Providers/AppServiceProvider.php (Laravel 13), the snippet's dependencies in container terms
public function register(): void
{
    $this->app->singleton(ConnectionPool::class, fn () => new ConnectionPool(config('database.url'))); // lifespan engine
    $this->app->scoped(UnitOfWork::class, fn ($app) => new UnitOfWork($app->make(ConnectionPool::class))); // SessionDep: once per request
    $this->app->bind(RequestId::class, fn () => new RequestId((string) Str::uuid()));                 // use_cache=False: new per resolve
    $this->app->when(AdminStatsController::class)                                                    // contextual binding: no FastAPI twin
              ->needs(NotesRepository::class)
              ->give(fn ($app) => new ReadReplicaNotesRepository($app->make(ConnectionPool::class)));
}

// app/Http/Controllers/NoteController.php: constructor injection + method injection
class NoteController extends Controller
{
    public function __construct(private UnitOfWork $uow) {}                       // session: SessionDep
    public function index(Request $request, Pagination $page) { /* ... */ }      // page: PageDep (method injection)
}

// routes/api.php: route-group middleware is Laravel's router dependency
Route::middleware(['auth:sanctum', 'tenant'])->group(fn () => Route::get('/notes', [NoteController::class, 'index']));

// tests/Feature/NotesTest.php: swap a binding, like app.dependency_overrides
$this->app->instance(IdentityProvider::class, new FakeIdentityProvider(user: 'tester'));
Laravel / PHPFastAPI
Service containerNo container; the dependency graph from signatures
$this->app->bind(...)A dependency with use_cache=False (new per use)
$this->app->singleton(...)Lifespan resource on app.state + a dependency that returns it
$this->app->scoped(...)A normal dependency (cached per request)
Contextual binding when()->needs()->give()Pass a different callable to Depends
Constructor injection in controllersParameters of the path operation
Method injection, App::call(...)Every path operation and dependable
Route middleware groups (auth, tenant)APIRouter(dependencies=[...])
Global middlewareFastAPI(dependencies=[...]) for matched routes; middleware for all
abort(403) in a policyraise HTTPException(403) in a dependency
$this->app->instance(...), $this->mock(...)app.dependency_overrides[...] = ...
Auth::user() (a locator)user: CurrentUser (injected)
Octane: singletons survive requestsLifespan: resources survive requests, per worker

The Go angle ​

Go has no framework that injects into handlers. The idiom is constructor injection by hand. A handler is a method on a struct whose fields are its dependencies, and main is the composition root that builds everything once and wires it together. This is the Go twin of this page, Mocking with Interfaces, Dependency Injection for Testability. Request-scoped values (the user, the tenant, a request id) do not go into constructors; middleware resolves them and puts them into context.Context, so they arrive on r.Context(). Two libraries automate the wiring. Google's Wire is "a code generation tool that automates connecting components using dependency injection", in which "Dependencies between components are represented in Wire as function parameters". Its README now opens with "This project is no longer maintained", and its project-status section still reads "As of version v0.3.0, Wire is beta and is considered feature complete." Uber's Fx "is a dependency injection system for Go" that works at runtime with fx.Provide (constructors, which "are not called until they are needed") and fx.Invoke. Its lifecycle hooks (OnStart, OnStop) play the role of FastAPI's lifespan, and the docs promise "Fx-managed singletons" to "eliminate global state". Neither has a per-request cache or anything like OpenAPI from the wiring. In Go the per-request part is middleware plus context.

go
// Go: the snippet's notes API with constructor injection (the composition root is main)
type NotesStore interface {
	List(ctx context.Context, tenant string, limit, offset int) ([]Note, error)
}

type NotesHandler struct { // dependencies are fields, set once (singletons)
	store NotesStore
	auth  Authenticator
}

func NewNotesHandler(store NotesStore, auth Authenticator) *NotesHandler { // constructor injection
	return &NotesHandler{store: store, auth: auth}
}

func (h *NotesHandler) List(w http.ResponseWriter, r *http.Request) {
	user := UserFrom(r.Context())                 // request-scoped: put there by the auth middleware (CurrentUser)
	page, size, err := parsePage(r.URL.Query())   // Pagination: hand-written validation, no automatic 422
	if err != nil {
		http.Error(w, err.Error(), http.StatusUnprocessableEntity)
		return
	}
	notes, err := h.store.List(r.Context(), user.Tenant, size, (page-1)*size)
	if err != nil {
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}
	writeJSON(w, notes)
}

func main() {
	db, err := sql.Open(os.Getenv("DB_DRIVER"), os.Getenv("DATABASE_URL")) // lifespan: one *sql.DB (a pool) per process
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	h := NewNotesHandler(NewSQLNotesStore(db), NewJWTAuth(keys))
	mux := http.NewServeMux()
	mux.Handle("GET /notes", RequireTenantUser(h.auth, http.HandlerFunc(h.List))) // router dependency = middleware
	log.Fatal(http.ListenAndServe(":8000", mux))
}
// tests: NewNotesHandler(fakeStore{}, fakeAuth{}) -- the Go form of dependency_overrides
ConcernFastAPIGo
Where dependencies are declaredRoute and dependable signaturesStruct fields and constructor parameters
Composition rootSignatures + create_app()main() (or Wire/Fx)
SingletonsLifespan, app.stateBuilt once in main, passed down
Request-scoped valuesDependencies, cached per requestMiddleware + context.Context
CleanupYield dependencies, lifespandefer, fx OnStop, Wire cleanup functions
Validation of inputsIn the dependency, automatic 422Hand-written
Test swapapp.dependency_overridesPass a fake implementation of the interface
Codegen DInoneWire (unmaintained)
Runtime containernoneFx (fx.Provide, fx.Invoke)

Common misconceptions ​

BeliefReality
Depends keeps singletonsIt keeps nothing between requests; singletons live in the lifespan
Cached means across requestsCached per request only
The same function is always one cache entryThe key includes Security scopes and scope; POST /notes called get_current_user twice
Code after yield runs before the responseSince 0.118.0 it runs after the response (and after background tasks in the real run)
Commit after yield is safeA failed commit there cannot change the 200 the client already has
A caught exception in a yield dependency gives a nice responseWithout raise it is a 500 and the original error is lost; 0.128.8 only reports FastAPIError: Response not awaited
Overrides wrap the originalThe original and its sub-dependencies do not run
Override the class of a parameterised dependencyThe key is the instance used in Depends(...)
Global dependencies run for every requestOnly for matched routes; not for 404/405
Headers set on the injected Response always arriveLost when an HTTPException builds the response
A def dependency in an async def route runs on the loopIt runs in the thread pool
OAuth2PasswordBearer validates tokensIt only extracts them; a missing header is a 401 (since 0.20.0)
from __future__ import annotations is always harmlessOn 0.128.8 it breaks class dependencies (500 PydanticUserError) and callable-instance dependencies (422: the __call__ parameter is read as a query parameter)
One global session is fine for SQLiteOne failure poisons it for every later request (PendingRollbackError)
max_concurrency sizes the DB poolIt limits calls per Depends object, per event loop, per worker
app.state is shared by all workersEach worker process has its own
DI needs a containerConstructor and parameter injection are DI; a container only automates wiring

Cheat sheet ​

TopicRemember
Declarex: Annotated[T, Depends(fn)]; pass fn uncalled
AliasSessionDep = Annotated[Session, Depends(get_session)] in dependencies.py
ClassAnnotated[Pagination, Depends()]; no __future__ annotations in that module (0.128.8)
GraphSub-dependencies solved depth-first; the route names only the top node
Orderapp → router → decorator → parameters (left to right) → route
CacheOnce per request; key = (callable, scopes, scope); use_cache=False skips the read, not the write
Yieldtry: yield x / except: rollback; raise / finally: close
TimingTeardown after the response (0.118.0+); scope="function" before it (0.121.0+)
Background tasksPass ids, open their own resources
Side-effect depsdependencies=[Depends(check)] on decorator, APIRouter, FastAPI
ParameterisedCallable instance RoleChecker("admin") at module level; closure factories
async/syncdef → thread pool (40 tokens); async def → event loop, must not block
Request/Responserequest.app.state (process), request.state (request); Response headers lost on errors
SecurityOAuth2PasswordBearer extracts; get_current_user validates; Security(..., scopes=[...])
Testsapp.dependency_overrides[original] = fake; clear after each test; key by the exact object
LifetimesEngine/client in lifespan; Session/user per request; never a global Session

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What does FastAPI do with session: Annotated[Session, Depends(get_session)] on every request? Must-know ​

Answer

Answer: At import time it recorded get_session as a sub-dependant of the route, and get_engine as a sub-dependant of get_session. Per request it solves get_engine (reading app.state.engine), then enters get_session as a context manager: setup runs up to yield in the thread pool, because it is a def generator. It caches the yielded Session for the rest of the request, passes it to the route, and after the response runs the code after yield (finally: session.close()). See Dependencies with yield.

2 — Two dependencies both need get_current_user. How many times does it run, and when could it run twice? Must-know ​

Answer

Answer: Once per request, because FastAPI caches dependency values per request under the key (callable, security scopes, scope). It runs twice when the declarations differ in that key: Security(get_current_user, scopes=["notes:write"]) and Security(..., scopes=["notes:read"]) in the same request (measured: 2 calls on POST /notes), or when one declaration has use_cache=False or a different scope. A new request always starts with an empty cache. See Caching.

3 — Where should session.commit() go: after yield in the dependency or in the route? Why? Must-know ​

Answer

Answer: In the route (or a service the route calls). Since 0.118.0 the code after yield runs after the response has been sent, so a commit that fails there cannot change the status code: the client already has its 200 (the snippet's test_exception_after_yield_cannot_change_a_sent_response). The dependency should only rollback() on exceptions, re-raise, and close() in finally. scope="function" would also move teardown before the response, but committing in the route keeps the success path explicit. See When teardown runs.

4 — What is the difference between a parameter dependency, a decorator dependency, a router dependency and a global dependency? Must-know ​

Answer

Answer: A parameter dependency's value is passed to the function. Decorator (@router.get(..., dependencies=[...])), router (APIRouter(dependencies=[...])) and global (FastAPI(dependencies=[...])) dependencies run for their side effect and their value is discarded; they differ in reach: one route, every route of a router, every matched route of the app. Order: app → router → decorator → parameters. None of them runs for an unmatched path (404). See Router and global dependencies.

5 — How do you replace the real user lookup in a test, and what exactly stops running? Must-know ​

Answer

Answer: app.dependency_overrides[get_current_user] = lambda: User(...), and clear the dict after the test (a fixture). For every node in every graph FastAPI looks up the original callable in that dict; the override runs instead of the original, and the original's sub-dependencies (here oauth2_scheme) do not run, so no Authorization header is needed. The override's own parameters are read from the request like any dependency's. See Overriding dependencies.

6 — You override RoleChecker but the admin check still returns 403. Why? Important ​

Answer

Answer: The route uses Depends(require_admin), where require_admin = RoleChecker("admin") is an instance; FastAPI calls the instance's __call__ and uses the instance as the override key. The class RoleChecker never appears in the graph, so dependency_overrides[RoleChecker] is ignored. Override dependency_overrides[require_admin] (real run: 403 with the class key, 204 with the instance). See Parameterised dependencies.

7 — A yield dependency catches ValueError and does not re-raise. What does the client see, and what is logged? Important ​

Answer

Answer: A 500 Internal Server Error, and the original ValueError is lost. Since 0.110.0 FastAPI no longer forwards an exception that a dependency swallowed, matching normal Python semantics. On 0.128.8 the server side only sees FastAPIError: Response not awaited..., which names the bare except as the likely cause but not the real error (real run). The rule is: in except, either raise a new exception (for example HTTPException(400), which the client then gets) or re-raise with raise. See Exceptions in dependencies.

8 — What belongs in the lifespan and what in a dependency? Give the engine/session example. Important ​

Answer

Answer: Process-wide, reusable, thread-safe resources belong in the lifespan: the SQLAlchemy Engine and its pool, an httpx.AsyncClient, settings, models. They are created once per worker and stored on app.state or yielded as lifespan state. Per-request, stateful objects belong in dependencies: a Session (its own transaction), the current user, the tenant. The session dependency reads the engine (request.app.state.engine). A global Session shares one transaction across requests; in the Before app one failure made the next request fail with PendingRollbackError. See Lifespan resources.

9 — When does the code after yield run on current FastAPI, and how has that changed? Important ​

Answer

Answer: After the response is sent. The real run on 0.128.8 showed: response start, then background tasks, then teardown in reverse order of setup. History: before 0.106.0 it ran after the response; 0.106.0 moved it before the response (and dropped support for yielded resources in background tasks); 0.118.0 moved it back after the response so StreamingResponse can use the session; 0.121.0 added Depends(scope="function") to tear down before the response. See When teardown runs.

10 — Your global dependency sets X-Request-ID on the injected Response, but 401 and 404 responses lack it. Why, and what is the fix? Important ​

Answer

Answer: For a 404 the router found no route, so no dependency ran at all. For a 401, an HTTPException was raised and the exception handler built a new response, so the injected Response's headers were discarded (both observed in the snippet tests). Headers that must be on every response belong in middleware; the dependency can still put the id on request.state for logging. See Request and Response injection.

11 — How do Laravel's bind, singleton and scoped map to FastAPI? Good to know ​

Answer

Answer: singleton (resolved once) maps to a lifespan resource on app.state handed out by a dependency. scoped (once per request/job lifecycle) maps to an ordinary FastAPI dependency, cached per request. bind (new instance per resolve) maps to Depends(..., use_cache=False). Contextual binding has no twin: you choose the implementation by passing a different callable to Depends. Swapping a binding in tests ($this->app->instance) is app.dependency_overrides. See For PHP/Laravel developers.

12 — How does a Go service do the same without a framework, and what are wire and fx? Good to know ​

Answer

Answer: By constructor injection: handlers are methods on structs whose fields (interfaces) are set by a constructor, and main wires the graph once. Request-scoped values travel in context.Context, put there by middleware. Google Wire generates that wiring code at compile time; its README now says it is no longer maintained. Uber Fx builds the graph at runtime (fx.Provide, fx.Invoke) with OnStart/OnStop hooks. Tests pass fakes to the constructor. See The Go angle.

Glossary ​

TermMeaning
Dependency injectionCode declares the collaborators it needs; something else builds and passes them in
Inversion of controlThe framework calls your code and decides what it receives; the general idea DI is a case of
Service locatorA registry code asks for collaborators; Fowler's alternative to DI, an anti-pattern here
Constructor injectionCollaborators passed as __init__/constructor arguments; the Go idiom
Composition rootThe one place where the object graph is assembled (main, create_app())
Depends()FastAPI marker: "solve this callable and inject the result"
DependableThe callable passed to Depends
DependantA function that declares dependencies (routes, and dependables with sub-dependencies)
Callable dependencyAny callable: function, class, instance with __call__
Class dependencyA class used as a dependable; __init__ parameters are read from the request
Annotated aliasX = Annotated[T, Depends(fn)], reusable type plus marker (PEP 593)
SessionDepThe conventional alias for a per-request database session
Sub-dependencyA dependency of a dependency
Dependency graphAll dependables of one path operation, solved depth-first
Dependency resolution orderapp → router → decorator → parameters, each node's sub-dependencies first
Dependency cachePer-request dict of solved values, keyed by (callable, scopes, scope)
use_cacheDepends flag; False calls the dependable again in the same request
Yield dependencyA generator dependable: setup, yield value, teardown
Setup / teardownThe code before / after yield
scopeDepends(..., scope="function" or "request"), when yield teardown runs (0.121.0+)
Decorator dependenciesdependencies=[...] on a path operation decorator; value discarded
Router dependenciesAPIRouter(dependencies=[...]), run for every route of the router
Global dependenciesFastAPI(dependencies=[...]), run for every matched route
Parameterised dependencyA dependency configured by arguments: callable class instance or closure factory
Closure factoryA function returning a new dependency function that closes over its arguments
Request injectionDeclaring request: Request to get the Starlette request
Response injectionDeclaring response: Response to set headers, cookies, status on success
app.statePer-process attribute bag on the app (Starlette)
request.statePer-request attribute bag; also receives a shallow copy of lifespan state
Lifespan stateThe dict a lifespan yields, copied into each request.state
LifespanAsync context manager around the app's life: startup before yield, shutdown after
EngineSQLAlchemy object owning the connection pool; one per process
SessionSQLAlchemy unit of work with one transaction at a time; one per request
OAuth2PasswordBearerSecurity dependency that extracts a bearer token (401 if missing, since 0.20.0)
Security()Depends() plus OAuth2 scopes documented in OpenAPI
SecurityScopesInjected object listing the scopes required by all dependants
dependency_overridesapp dict mapping original dependables to replacements
max_concurrencyDepends option (0.163.0+) limiting concurrent calls per Depends object
Thread poolAnyIO worker threads (40 tokens) that run def dependencies and routes
AsyncExitStackStdlib stack FastAPI enters yield dependencies on; exits last-in, first-out
Laravel service containerLaravel's DI container: bind, singleton, scoped, contextual binding
Wire / FxGo DI tools: compile-time code generation (Wire, unmaintained) / runtime container (Fx)
PydanticValidates every dependency input and the injected models
SQLAlchemy / SQLModel / AlembicORM, Pydantic-flavoured ORM layer and migration tool used in the data chapters
pytest / httpx / Uvicorn / StarletteTest runner, the client under TestClient, the ASGI server, the toolkit FastAPI subclasses

References ​

Built by Morteza Negahi