How does FastAPI dependency injection actually work?

Depends is a request-scoped resolution mechanism, not a container. When you declare a parameter as Depends(get_db), FastAPI inspects the signature of get_db, finds its own parameters, including other Depends declarations, path and query parameters, headers, and the request, and records the whole tree when the route is registered. On each request, it walks that tree, resolves the sub-dependencies first, and passes their results upward until the endpoint has every argument.

Within a single request, each dependency is resolved once by default. If get_current_user and get_permissions both depend on get_db, the two share one session because FastAPI caches the result for the duration of that request. Pass use_cache=False when you need a fresh value at each use site. Nothing persists between requests unless you put it somewhere longer-lived yourself.

Aspect FastAPI Depends Long-lived DI container
Unit of scope One HTTP request Application, plus custom scopes
Lifetimes Per-request, cached or uncached Singleton, transient, scoped
Wiring Function signatures Registrations or bindings
Resolution trigger Incoming request Explicit lookup or injection anywhere
Usable outside HTTP Not directly Yes

Execution model matters too. FastAPI runs a plain def dependency in a threadpool, so blocking I/O there is tolerable. An async def dependency runs directly on the event loop. A blocking call inside it, such as a synchronous database driver or time.sleep, stalls every concurrent request on that worker until the call returns.

import itertools
from fastapi import Depends, FastAPI

app = FastAPI()
counter = itertools.count(1)  # module-level: outlives requests


def get_db():
    # Plain def: FastAPI runs this in a threadpool, so blocking I/O is tolerable.
    session_id = next(counter)
    print(f"open session {session_id}")
    return {"session": session_id}


def get_current_user(db: dict = Depends(get_db)):
    return {"user": "alice", "db": db["session"]}


def get_permissions(db: dict = Depends(get_db)):
    return {"perms": ["read"], "db": db["session"]}


def get_fresh_db(db: dict = Depends(get_db, use_cache=False)):
    # use_cache=False forces a new call to get_db at this use site.
    return db["session"]


@app.get("/me")
async def me(
    user: dict = Depends(get_current_user),
    perms: dict = Depends(get_permissions),
    fresh: int = Depends(get_fresh_db),
):
    # user["db"] == perms["db"]: get_db is cached once per request.
    # fresh differs: it bypassed the cache.
    # The next request starts with an empty cache and gets new sessions.
    return {"user_db": user["db"], "perms_db": perms["db"], "fresh_db": fresh}

Two dependencies share one cached get_db result within a request, while use_cache=False forces a separate call, and nothing is reused across requests.

Why keep Depends as a thin wiring layer at the edge?

FastAPI's resolver is flexible, which is a reason to give it as little work as possible. A layout that holds up as a service grows has three layers. The route function handles HTTP concerns: reading the request, choosing a status code, shaping the response. It declares a provider with Depends, such as get_order_service, whose only job is assembly. The provider takes a session or client from its own dependencies, passes them to a constructor, and returns the result. The third layer is a plain class, OrderService, whose __init__ accepts an OrderRepository and a PaymentClient. That class never imports FastAPI.

The payoff comes from that last rule. The service knows nothing about requests or Depends, so a unit test can construct it directly with an in-memory fake repository and a stub client, call a method, and assert on the return value. There is no TestClient, no app startup, no HTTP round trip, and no override bookkeeping. For backend and platform teams with growing services, most business-logic coverage then runs at plain-Python speed on every commit. The same class also works unchanged from a CLI command, a queue worker, or a migration script.

Keep the provider graph shallow, ideally one or two levels. Each additional layer of sub-dependencies makes it harder to see where a value comes from. FastAPI also collects parameters from the entire graph. A header or query parameter declared three providers deep becomes part of the endpoint's contract, so a missing value returns a 422 validation error naming a field the route itself never mentions.

# services/orders.py: business logic, no FastAPI import
from typing import Protocol

class OrderRepository(Protocol):
    def get_total_cents(self, order_id: int) -> int: ...

class PaymentClient(Protocol):
    def charge(self, amount_cents: int) -> str: ...

class OrderService:
    def __init__(self, repo: OrderRepository, payments: PaymentClient) -> None:
        self.repo, self.payments = repo, payments

    def checkout(self, order_id: int) -> str:
        return self.payments.charge(self.repo.get_total_cents(order_id))

# api/orders.py: the only layer that knows about Depends
# get_session, get_payment_client and SqlOrderRepository are defined elsewhere in the app.
from fastapi import APIRouter, Depends
router = APIRouter()

def get_order_service(session=Depends(get_session),
                      client=Depends(get_payment_client)) -> OrderService:
    # Assembly only. Each dependency is one level below this provider.
    return OrderService(SqlOrderRepository(session), client)

@router.post("/orders/{order_id}/checkout", status_code=201)
def checkout(order_id: int, service: OrderService = Depends(get_order_service)) -> dict:
    return {"charge_id": service.checkout(order_id)}

# tests/test_orders.py: construct directly with fakes, no TestClient or app startup
class FakeRepo:
    def get_total_cents(self, order_id: int) -> int: return 2500

class StubPayments:
    def __init__(self) -> None: self.charged: list[int] = []
    def charge(self, amount_cents: int) -> str:
        self.charged.append(amount_cents); return "ch_test_123"

def test_checkout_charges_order_total() -> None:
    payments = StubPayments()
    assert OrderService(FakeRepo(), payments).checkout(42) == "ch_test_123"
    assert payments.charged == [2500]

This example shows the three layers: a route, a one-level provider declared with Depends, and a FastAPI-free OrderService. Because the service does not depend on FastAPI, it can be unit tested by constructing it with a fake repository and a stub payment client.

How should you manage resource lifetimes with yield dependencies and lifespan?

Request-scoped resources belong in yield dependencies. Code before yield acquires the resource, the yielded value is injected, and code after yield is teardown. A database session opens, the handler uses it, and the session closes or returns to the pool. Transactions use the same shape: commit after yield, roll back in an except block, close in finally. If you catch an exception there, re-raise it. Swallowing it hides the failure from FastAPI's exception handlers and can leave the client with a misleading response.

The exact timing of teardown is version-dependent. FastAPI has changed, across releases, whether post-yield code runs before or after the response is sent and what an exception raised there can still affect. Check the dependencies documentation for the version you run before you rely on, for example, a commit failure turning into a 500.

Expensive, long-lived objects such as connection pools and SDK clients should not be built per request. Create them once in the application lifespan, store them on app.state, and close them on shutdown. Expose each one through a small provider that reads request.app.state, so handlers depend on the provider and tests can override it.

Concern yield dependency Lifespan + app.state
Lifetime One request Whole process
Typical objects Sessions, transactions Pools, SDK clients
Teardown After yield, version-dependent timing On shutdown

There are two caveats. First, FastAPI caches dependency results per request. If two parameters depend on the same provider, both receive the same instance. Use use_cache=False when they need separate sessions. Second, sync dependencies run in a threadpool, so a shared client reached from them must be thread-safe.

from contextlib import asynccontextmanager
from typing import AsyncIterator

import httpx
from fastapi import Depends, FastAPI, Request
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Built once per process. The pool and HTTP client are shared across requests.
    app.state.engine = create_async_engine("postgresql+asyncpg://app:change-me@db:5432/app")
    app.state.sessionmaker = async_sessionmaker(app.state.engine, expire_on_commit=False)
    app.state.http = httpx.AsyncClient(base_url="", timeout=5.0)
    yield
    await app.state.http.aclose()   # shutdown teardown
    await app.state.engine.dispose()

app = FastAPI(lifespan=lifespan)

def get_http(request: Request) -> httpx.AsyncClient:
    # Small provider. Handlers depend on this, and tests override it.
    return request.app.state.http

async def get_session(request: Request) -> AsyncIterator[AsyncSession]:
    async with request.app.state.sessionmaker() as session:  # closes on exit
        try:
            yield session
            await session.commit()  # teardown; when this runs vs. the response is version-dependent
        except Exception:
            await session.rollback()
            raise  # never swallow: let FastAPI's exception handling see it

@app.post("/orders")
async def create_order(
    session: AsyncSession = Depends(get_session),
    # Without use_cache=False this would be the SAME session as above (per-request cache).
    audit: AsyncSession = Depends(get_session, use_cache=False),
    http: httpx.AsyncClient = Depends(get_http),
):
    resp = await http.post("/charges", json={"amount": 1000})
    return {"status": resp.status_code}

Shows a lifespan that creates a connection pool and an HTTP client once and stores them on app.state, a provider that reads them from request.app.state, and a yield session dependency that commits, rolls back, and re-raises. It also shows use_cache=False giving a second parameter its own session.

Which Depends patterns keep signatures readable and dependencies configurable?

Name your dependencies with Annotated aliases

Writing session: Session = Depends(get_session) in every endpoint repeats the same wiring and makes the provider hard to change. Define the alias once, SessionDep = Annotated[Session, Depends(get_session)], and endpoints declare session: SessionDep. The signature now states what the handler needs, not how it is built. When the provider changes, you edit one line. Type checkers also see a plain Session instead of a default value they cannot interpret.

Parameterize with classes and callable instances

Depends accepts any callable. A class works directly: FastAPI resolves its __init__ parameters from the request, which suits grouped inputs such as pagination. For configuration fixed at declaration time, use a callable instance. A RequireScope class takes the required scope in __init__ and checks it in __call__, and __call__ declares its own dependencies. Depends(RequireScope("orders:write")) reads as policy at the route, and the check is a normal object you can unit test without HTTP.

Layer the user resolver on the security scheme

Have get_current_user depend on the security scheme dependency that extracts the token, and have RequireScope depend on get_current_user. In tests, override only get_current_user with a fake user that holds specific scopes. Token parsing is skipped, but the scope check still runs. A test for a missing scope then exercises real authorization logic.

Attach value-less checks at the route or router

Rate limits and audit hooks return nothing the handler uses. Pass them through dependencies=[...] on the path decorator, on APIRouter, or on include_router. They run on every matching request, FastAPI discards their return values, and handler signatures stay clean.

from typing import Annotated
from fastapi import APIRouter, Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

class User(BaseModel):
    name: str
    scopes: set[str] = set()

# Layer 1: the security scheme extracts the bearer token from the request.
# Layer 2: the user resolver turns that token into a User.
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> User:
    if token != "example-token":  # placeholder for real token verification
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail="invalid token")
    return User(name="alice", scopes={"orders:write"})

CurrentUser = Annotated[User, Depends(get_current_user)]  # one alias, reused everywhere

# Layer 3: the policy is configured at declaration time and checked per request.
class RequireScope:
    def __init__(self, scope: str):
        self.scope = scope

    def __call__(self, user: CurrentUser) -> User:
        if self.scope not in user.scopes:
            raise HTTPException(status.HTTP_403_FORBIDDEN, detail=f"missing {self.scope}")
        return user

def rate_limit() -> None:
    ...  # value-less check: raise HTTPException(429) when over the limit

router = APIRouter(prefix="/orders", dependencies=[Depends(rate_limit)])

@router.post("/")
def create_order(user: Annotated[User, Depends(RequireScope("orders:write"))]):
    return {"created_by": user.name}

app = FastAPI()
app.include_router(router)
# In tests: skip token parsing but keep the scope check running.
# app.dependency_overrides[get_current_user] = lambda: User(name="t", scopes={"orders:read"})

This example shows a CurrentUser Annotated alias built on the OAuth2 scheme, a RequireScope callable instance that is configured per route, and a router-level rate-limit dependency, with a test override that replaces only the user resolver so the scope check still runs.

How do you test FastAPI apps with dependency overrides?

app.dependency_overrides is a plain dict on the application. The key is the original callable you passed to Depends, and the value is the replacement. Because FastAPI resolves dependencies by that identity, you never patch the module where something is defined or imported. The dict applies to every route on that app instance, so an override left behind leaks into the next test. Use a pytest fixture that assigns the overrides, constructs a TestClient, yields it, and calls app.dependency_overrides.clear() in teardown. That way cleanup runs even when the test fails.

Override the collaborators at the edge of your code:

  • the repository
  • the external API client
  • the clock
  • the ID generator
  • the current-user resolver

Do not override the service under test. If you replace it, the test checks only the wiring and none of your logic.

Approach Targets Breaks when
dependency_overrides The dependency callable The dependency itself is renamed or removed
unittest.mock.patch A dotted import path string Imports move, are aliased, or are bound before patching

patch replaces a name in one specific module namespace. If you refactor from x import y into another file, the patch target silently stops matching, and the real dependency runs during the test.

Integration tests against a real database

Fakes can't reproduce unique constraints, foreign keys, isolation levels, or how your ORM actually translates a query. For those, override only the session provider. Make it yield a session bound to a connection whose outer transaction is rolled back after each test, or one pointed at an isolated test database. The rest of the dependency graph stays real, so constraint violations, transaction boundaries, and query semantics fail in the test rather than in production.

When should you avoid relying on FastAPI Depends?

Depends is resolved only for path operations, their sub-dependencies, and router- or app-level dependency lists. Code outside a request handler gets no resolution. Middleware, background task functions, CLI scripts, queue workers, and scheduled jobs all run outside that machinery. A provider written as get_db(settings = Depends(get_settings)) therefore can't be reused there without reaching into framework internals. Write providers as plain functions or factories that take their inputs as ordinary arguments, and treat the Depends signature as a thin adapter over them. A worker can then call build_repository(settings) directly, and a background task can receive the already-built object as an argument.

Overrides have their own failure modes. app.dependency_overrides is a mutable dictionary on a shared object, which makes it global state:

  • Leaked overrides. If one test forgets to clear an override, later tests inherit it. They then pass or fail depending on execution order.
  • Concurrent tests. Tests that run concurrently in the same process against one module-level app can overwrite each other's entries.
  • Silent no-ops. The dictionary is keyed by the exact function object. If a provider is wrapped by a decorator, built dynamically with functools.partial or a closure, or imported through a path that yields a different object, the override never matches. The real dependency runs and nothing reports the mismatch.

Building a fresh app from a factory per test removes the shared state, but it adds setup time to every test, and that cost grows with the size of the app.

Even with isolated overrides, fakes still have a gap. A fake encodes your assumptions about the real service, and those assumptions go stale over time. Without integration tests that exercise the real provider, the suite keeps passing after a schema change or a changed error contract would break production.

What are the alternatives to FastAPI Depends, and what do they cost?

That brittleness comes from how tests replace collaborators. The wiring mechanism has its own costs, and Depends is only one of three reasonable options.

Option Lifetime support Injection outside requests Testing style Development cost
Depends + lifespan + app.state Per-request via yield dependencies; app-wide via lifespan No. Workers, CLIs and scripts must build objects themselves app.dependency_overrides Nothing beyond FastAPI
Manual composition (constructors, factory functions) Whatever you write; you own creation and shutdown order Yes. Every entry point calls the same factories Pass fakes into constructors; no app required Boilerplate grows with the size of the object graph
Separate DI library Declared scopes such as singleton, factory and per-request Yes. The container works anywhere Container-level overrides An extra dependency to pin and upgrade, a second wiring style next to Depends, and more indirection when debugging

The library's real cost is that second wiring style. Engineers must learn which objects come from Depends and which come from the container, and request-scoped lifetimes still need glue to work with FastAPI's request cycle.

Which option fits depends on team size and service complexity:

  • Plain Depends suits a small team with one service that has an HTTP entry point and nothing else.
  • Manual composition helps once workers or scheduled jobs share the same services. Keep one composition module, and have Depends providers call into it.
  • A library earns its overhead when many services share a large graph with several distinct scopes.

The thin-edge pattern keeps this choice reversible. Services take collaborators through constructors and never import FastAPI, so moving between options only rewrites the provider functions. Route signatures, business logic and the unit tests for that logic stay unchanged.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to fastapi dependency injection, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.