FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

FastAPI Dependency Injection

Request-scoped dependencies, yield cleanup generators, and test overrides.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Build hierarchical dependency DAGs
  • ✓Manage connection lifespans and mocks
Full Technical Reference Document

Mental model

FastAPI's dependency injection engine compiles declared route requirements (Depends(...) and Security(...)) into a per-request Directed Acyclic Graph (DAG) executed automatically by the framework before and after your path operation runs. Each dependency node can recursively depend on sub-dependencies—such as decoding bearer headers, fetching a database session, or checking RBAC scopes—while sharing computed results within the same request tick (use_cache=True by default) and running post-yield resource cleanup deterministically even when an endpoint raises an exception. Paired with @asynccontextmanager app lifespan hooks for process-wide connection pools, this model eliminates global mutable state and makes swapping live integrations with deterministic fakes trivial via app.dependency_overrides.

Incoming HTTP Request
Resolve Dependency DAG
Execute Yield Setup
Inject Resource into Endpoint
Teardown Yield Cleanup
Conceptual teaching model synthesized from:fastapi-docs,pydantic-v2-paper

Theory

Dependency injection in FastAPI cleanly separates process-scoped infrastructure from request-scoped resources:

Scope LevelMechanismAllocation TimingCleanup BoundaryCanonical Examples
Process Lifespan@asynccontextmanager def lifespan(app)Once at ASGI worker startupOnce at graceful worker shutdownSQLAlchemy AsyncEngine, Redis client pool, httpx.AsyncClient, ML tokenizers
Per-Request (return)Depends(fn) or Annotated[..., Depends(fn)]Once per DAG key per request (use_cache=True)Garbage collection after responseParsed auth claims, tenant context, query pagination DTOs
Per-Request (yield)async def get_db(): try: yield s finally: ...Before route body executesImmediately after response generation completesAsyncSession transaction commit/rollback, temp directory lock release
Uncached Fresh InstanceDepends(fn, use_cache=False)Every call site inside the same requestEnd of dependency stackFresh UUID nonce generator, independent sub-transaction handles

Execution Order, Exception Propagation, and Modern Annotated Composition

When a route declares multiple overlapping sub-dependencies (for instance, both get_current_user and get_audit_logger depend on get_db), FastAPI solves the DAG topologically and executes get_db only once per request (use_cache=True), caching its yielded value across both downstream consumers. Crucially, the post-yield teardown block executes inside a coroutine finally wrapper after FastAPI finishes serializing the HTTP response (or handling an HTTP error) and receives any unhandled route exception via generator.throw(...), making it safe to rollback dirty database transactions on errors and commit cleanly on success. Note, however, that any HTTPException raised inside post-yield cleanup after headers are already sent cannot rewrite the status code—always perform commit/validation checks inside the route or an explicit dependency boundary before response serialization starts.

python
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, Request, status
​
class TelemetryPool:
async def close(self) -> None: ...
​
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
# Process-level singletons initialized once per ASGI worker
app.state.pool = TelemetryPool()
yield
await app.state.pool.close()
​
app = FastAPI(lifespan=lifespan)
​
async def get_db_session(request: Request) -> AsyncIterator[dict]:
session = {"pool": request.app.state.pool, "committed": False}
try:
yield session
session["committed"] = True
except Exception:
# Roll back partial transaction writes on application errors
session["committed"] = False
raise
​
DbSessionDep = Annotated[dict, Depends(get_db_session)]
​
def get_tenant_id(
session: DbSessionDep,
x_tenant_id: Annotated[str | None, Header()] = None,
) -> str:
if not x_tenant_id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Missing X-Tenant-ID")
return x_tenant_id
​
TenantDep = Annotated[str, Depends(get_tenant_id)]
​
@app.post("/v1/events")
async def ingest_event(tenant: TenantDep, session: DbSessionDep) -> dict[str, object]:
# get_db_session executes once per request even though both route and get_tenant_id depend on it
return {"tenant": tenant, "reused_session": id(session)}

Using Python typing.Annotated (DbSessionDep = Annotated[dict, Depends(get_db_session)]) decouples endpoint signatures from concrete wiring while preserving full static type inference in Pyright/mypy and reusing the same dependency signature across multiple routers cleanly.

Alternatives and trade-offs

  • FastAPI Built-In Depends DAG: Zero extra packages, native OpenAPI schema generation for headers/query/security parameters, automatic async/sync threadpool dispatch, and built-in app.dependency_overrides testing hooks; bound strictly to HTTP/WebSocket request lifecycles (not standalone CLI scripts or Celery tasks).
  • Explicit Service Constructor Injection / Containers (dishka, dependency-injector): Useful when clean-architecture business services span FastAPI HTTP handlers, Kafka workers, and CLI commands outside ASGI request scopes, at the expense of boilerplate container bindings and maintaining bridge adapters into FastAPI routes.
  • Global Module Singletons (db = Database()): Fast to prototype, but fragile under pytest parallel workers, ASGI lifespan reloaders, and multi-event-loop test runners (Event loop is closed errors when global AsyncEngine objects bind to stale loops).

Failure modes and misconceptions

  1. Swallowing Exceptions in yield Dependencies Without Re-Raising: Writing try: yield db except Exception: await db.rollback() without raise causes FastAPI to treat the error as handled while simultaneously leaving the route's HTTP exception ambiguous or returning a broken 500. Always clean up inside except/finally and re-raise or raise a specific HTTPException.
  2. Blocking Sync Generators in High-Throughput Routes: FastAPI silently runs regular def dependencies (including def get_sync_db()) in an AnyIO worker threadpool (40 default threads). Running slow external I/O inside synchronous dependencies starves FastAPI's threadpool across concurrent requests; prefer async def dependencies paired with non-blocking drivers.
  3. Leaving Test app.dependency_overrides Mutated Across Tests: Mutating app.dependency_overrides[get_current_user] = mock_user without clearing app.dependency_overrides.clear() in a pytest fixture finally block leaks mocked auth bypasses into subsequent integration tests.
  4. Streaming Response Timing Mismatch with yield Teardown: Starting a StreamingResponse that reads lazily from an injected database cursor fails if FastAPI completes the dependency context in Starlette/FastAPI versions or scopes before the stream exhausts—verify generator ownership (AsyncExitStack or explicit stream cleanup) whenever streaming database results.
Reflect before revealing the guide

Decision scenario

Your team runs multi-tenant AI API endpoints requiring request authentication, per-tenant database session scoping, OpenTelemetry trace tagging, and reliable pytest isolation without hitting live PostgreSQL or OAuth JWKS servers in CI. Define process-wide AsyncEngine and httpx.AsyncClient pools inside an @asynccontextmanager def lifespan(app) hook attached to app.state, compose reusable Annotated[..., Depends(...)] aliases (DbDep, CurrentUserDep) using yield teardown for transactional rollback safety, and install an autouse pytest fixture that swaps app.dependency_overrides cleanly per test and invokes app.dependency_overrides.clear() on teardown.

Learning outcomes

  • Trace topological resolution and per-request caching (use_cache=True) across nested Depends DAGs.
  • Separate process-wide singletons (lifespan + app.state) from request-scoped yield dependencies to avoid stale event-loop leaks.
  • Author reusable Annotated dependency aliases that preserve static type safety and OpenAPI documentation.
  • Isolate integration tests cleanly via app.dependency_overrides without leaking overrides across test modules.

Trade-offs

FastAPI's declarative Depends graph removes manual boilerplate for request validation, OpenAPI security docs, and deterministic cleanup while supporting zero-friction test mocks, though non-HTTP background workers must resolve dependencies separately outside ASGI lifecycles.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next