How do FastAPI dependency overrides work?

In FastAPI, dependency injection means a path operation declares what it needs, and the framework calls the right functions to supply it. Each Depends(get_db) in a signature becomes a node in a graph that FastAPI resolves for every request. It calls sub-dependencies first, feeds their results into their parents, and then calls the endpoint. By default, if two nodes in the same request depend on the same callable, FastAPI calls it once and shares the result. Passing use_cache=False to Depends turns this off.

app.dependency_overrides is a plain dict. While resolving the graph, FastAPI checks whether the dependency callable is a key in that dict. If it is, FastAPI calls the mapped value instead. The lookup uses the function object itself, not its name or behavior, which is the source of most silent failures:

  • Wrapper: a key built with a decorator, even one using functools.wraps, is a different object from the one the route references, so it never matches.
  • Lambda: a key like lambda: get_db() is a new function that no route declared.
  • Duplicate import: if the same module loads under two import paths, for example app.deps and src.app.deps because of sys.path configuration, Python creates two distinct get_db objects. Overriding one leaves the other untouched. An ordinary aliased import of the same module object works correctly.

In every case nothing raises an error. The real dependency simply runs.

Caching also applies to overrides. If an override returns a fresh object on each call, every consumer within one request still receives the same instance. Each new request gets a new one.

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

app = FastAPI()

def get_db():
    return {"name": "real-db"}

def get_repo(db=Depends(get_db)):
    return db

@app.get("/check")
def check(db=Depends(get_db), repo_db=Depends(get_repo)):
    # get_db is reached twice in this graph; the per-request cache calls it once.
    return {"name": db["name"], "same_instance": db is repo_db}

client = TestClient(app)

def fake_db():
    return {"name": "fake-db"}  # builds a fresh dict on every call

# Wrong keys: neither is the function object the routes declared.
@functools.wraps(get_db)
def wrapped_get_db():
    return get_db()

app.dependency_overrides[wrapped_get_db] = fake_db
app.dependency_overrides[lambda: get_db()] = fake_db
assert client.get("/check").json()["name"] == "real-db"  # no error, real dependency ran

# Right key: the exact object referenced in Depends(get_db).
app.dependency_overrides.clear()
app.dependency_overrides[get_db] = fake_db
body = client.get("/check").json()
# The override replaced get_db, and its fresh dict was shared within the request.
assert body == {"name": "fake-db", "same_instance": True}

Overrides keyed by a wrapper or a lambda are silently ignored, while one keyed by the original get_db takes effect, and the per-request cache makes both consumers receive the same fresh object.

Why put resources in the lifespan and reach them through dependencies?

Shared resources such as an HTTP client, a database pool, or a cache connection are expensive to build and must be closed cleanly. The lifespan async context manager gives them a clear lifetime. Code before yield runs once at startup and creates the resources. You attach them to app.state, and code after yield closes them on shutdown. Nothing connects at import time, so importing the app module during test collection does not open sockets or require credentials.

Routes should not read app.state directly. Instead, wrap each resource in a small dependency function, such as get_db_pool(request), that returns request.app.state.db_pool. Routes declare that function with Depends. This keeps one named function per resource, and that function is the key you replace in app.dependency_overrides.

 lifespan (startup)              app.state            dependencies         routes
 ┌──────────────────┐   set    ┌─────────────┐  read  ┌──────────────┐ Depends ┌──────────┐
 │ create pool      │ ───────► │ .db_pool    │ ─────► │ get_db_pool  │ ──────► │ /orders  │
 │ create client    │ ───────► │ .http       │ ─────► │ get_http     │ ──────► │ /quotes  │
 └──────────────────┘          └─────────────┘        └──────▲───────┘         └──────────┘
 lifespan (shutdown): close                                  │
                                         dependency_overrides[get_db_pool] = fake

The alternative is module-level globals, which are harder to replace. With unittest.mock.patch, you must patch the name where it is looked up, not where it is defined. A from db import pool copies the binding into every importing module, so each one needs its own patch, and a missed patch fails silently against the real resource. An override replaces one function and covers every route that depends on it.

from contextlib import asynccontextmanager

import asyncpg
import httpx
from fastapi import Depends, FastAPI, Request


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: build expensive resources once. Nothing connects at import time.
    app.state.db_pool = await asyncpg.create_pool(dsn="postgresql://app:change-me@localhost:5432/orders")
    app.state.http = httpx.AsyncClient(base_url="", timeout=5.0)
    try:
        yield
    finally:
        # Shutdown: close in reverse order of creation.
        await app.state.http.aclose()
        await app.state.db_pool.close()


app = FastAPI(lifespan=lifespan)


# One small function per resource. Each one is the key a test puts in app.dependency_overrides.
def get_db_pool(request: Request) -> asyncpg.Pool:
    return request.app.state.db_pool


def get_http(request: Request) -> httpx.AsyncClient:
    return request.app.state.http


# Routes never touch app.state directly. They only declare the dependency.
@app.get("/orders/{order_id}")
async def read_order(order_id: int, pool: asyncpg.Pool = Depends(get_db_pool)):
    row = await pool.fetchrow("SELECT id, status FROM orders WHERE id = $1", order_id)
    return dict(row) if row else {"id": order_id, "status": "missing"}


@app.get("/quotes/{symbol}")
async def read_quote(symbol: str, http: httpx.AsyncClient = Depends(get_http)):
    resp = await http.get(f"/v1/quotes/{symbol}")
    return resp.json()

The lifespan creates the database pool and HTTP client on app.state and closes them on shutdown, and the get_db_pool and get_http dependencies expose them to routes as the single seam that tests override.

How do you write yield dependencies for per-request resources?

A yield dependency puts setup and teardown in one function. For get_db_session, everything before yield runs before the endpoint: open a session from the engine the lifespan created. The yielded session is injected into the endpoint. Everything after yield runs once the endpoint is done: commit, then close.

Wrap the yield in try/except/finally. If the endpoint raises, FastAPI throws that exception back into the dependency at the yield statement. The except block can then roll back the session, and finally closes it whether the request succeeded or failed. Re-raise after rolling back. If you swallow the exception, FastAPI loses the error your exception handlers need to build the response. This structure also makes the dependency easy to replace. A test override can yield a session bound to a transaction that is always rolled back, and endpoint code never knows the difference.

Settings follow the same rule. Build them in a get_settings dependency, usually decorated with functools.lru_cache so the environment is parsed once per process. In tests, override get_settings with a function that returns a Settings object built from explicit arguments. Don't mutate os.environ mid-test. A cached instance has already read the old values, so the change is ignored, and it can leak into other tests.

Overrides avoid the cache because FastAPI calls your replacement instead of the cached function. The cache does matter wherever code calls get_settings() directly, such as in the lifespan or at module import. Those calls go through lru_cache, outside the DI system. Call get_settings.cache_clear() in fixture teardown so the next test doesn't receive a stale instance.

import os
from dataclasses import dataclass
from functools import lru_cache

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

@dataclass
class Settings:
    database_url: str

@lru_cache  # parse the environment once per process
def get_settings() -> Settings:
    return Settings(database_url=os.environ.get("DATABASE_URL", "postgresql://app:changeme@localhost/app"))

app = FastAPI()

def get_db_session(request: Request):
    session = request.app.state.session_factory()  # factory built in lifespan
    try:
        yield session             # endpoint runs here; its exception is thrown back in at this line
        session.commit()
    except Exception:
        session.rollback()
        raise                     # re-raise so exception handlers still see the error
    finally:
        session.close()           # runs on success and failure

@app.get("/config")
def read_config(settings: Settings = Depends(get_settings)):
    return {"database_url": settings.database_url}

@pytest.fixture
def client():
    # Override the dependency instead of mutating os.environ mid-test
    app.dependency_overrides[get_settings] = lambda: Settings(database_url="sqlite:///./test.db")
    with TestClient(app) as c:
        yield c
    app.dependency_overrides.clear()
    get_settings.cache_clear()    # direct calls (lifespan, imports) go through lru_cache

def test_config_uses_override(client):
    assert client.get("/config").json() == {"database_url": "sqlite:///./test.db"}

A get_db_session yield dependency that commits, rolls back and re-raises, or closes around the endpoint, alongside an lru_cache-backed get_settings that tests override through dependency_overrides and clear with cache_clear() in fixture teardown.

How do you set up pytest fixtures and an app factory for FastAPI tests?

A factory instead of a global app

When main.py builds app = FastAPI() at import time, every test shares one object. Overrides, cached state, and anything the lifespan stored on app.state carry over from one test to the next. A create_app(settings, lifespan=None) factory fixes this. It builds the app, registers routers, and attaches whichever lifespan you pass in, falling back to the production one when you pass None. A function-scoped fixture then gives each test its own app. If construction is expensive, a module-scoped fixture shares one app per module. Production code calls the same factory, so tests use the real wiring rather than a copy of it.

Overrides that always clean up

Set app.dependency_overrides inside a yield fixture and clear it after the yield. Pytest runs teardown even when the test fails, so a failing assertion can't leave a fake dependency in place for later tests. If another fixture already added overrides, save a copy of the dict before you change it and restore that copy in teardown. A blanket clear() would remove the other fixture's entries. Parallel workers run in separate processes, so they don't share an app. The real risk is test order within a single worker, where a leaked override makes results depend on which test ran first.

Transactional database fixture

Open a connection, begin a transaction, and bind a session to that connection. Override get_db_session with a function that yields the session. In teardown, close the session, roll back the transaction, and close the connection. Every test starts with clean tables, and nothing needs truncating. If the code under test calls commit(), configure the session to use savepoints. Otherwise that commit ends the outer transaction, and the rollback has nothing left to undo.

The factory and fixtures add setup code up front. In return, tests no longer fail or pass depending on the order they run in, and those failures are slow to trace.

# conftest.py
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import Session

from myapp.main import create_app, Settings
from myapp.db import get_db_session

engine = create_engine("postgresql+psycopg://app_test:changeme@localhost:5432/app_test")

@pytest.fixture
def app():
    # Fresh app per test: no overrides or app.state carried over from earlier tests
    return create_app(Settings(environment="test"))

@pytest.fixture
def db_session(app):
    connection = engine.connect()
    transaction = connection.begin()
    # commit() in app code releases a SAVEPOINT instead of ending the outer transaction
    session = Session(bind=connection, join_transaction_mode="create_savepoint")

    def override_get_db_session():
        yield session

    saved = app.dependency_overrides.copy()  # keep entries other fixtures added
    app.dependency_overrides[get_db_session] = override_get_db_session
    yield session
    # Teardown runs even if the test fails
    app.dependency_overrides.clear()
    app.dependency_overrides.update(saved)
    session.close()
    transaction.rollback()  # discard everything the test wrote
    connection.close()

@pytest.fixture
def client(app, db_session):
    # The context manager runs the app's lifespan startup and shutdown
    with TestClient(app) as c:
        yield c

A conftest.py that builds a fresh app per test from create_app, overrides get_db_session with a session bound to a per-test transaction, and restores the overrides and rolls back in teardown.

Does TestClient run the FastAPI lifespan, and what about async clients?

The lifespan only runs when something drives the ASGI lifespan protocol, and the test clients differ on whether they do that. When nothing drives it, app.state stays empty, and every dependency that reads from it fails. That failure usually shows up as an AttributeError far from its real cause.

Client setup Startup/shutdown run? Notes
TestClient(app) as a plain instance No Requests work until a dependency touches app.state
with TestClient(app) as client Yes, on enter and exit Put it in a fixture so each test gets a fresh lifespan
httpx AsyncClient with ASGITransport No The transport sends only HTTP requests, never lifespan events
AsyncClient inside async with app.router.lifespan_context(app) Yes You enter the app's lifespan yourself in an async fixture

With the async client you have two choices. You can enter the lifespan context in the fixture before yielding the client. Or you can skip the lifespan entirely and build app.state by hand with test doubles, which suits tests that override those dependencies anyway.

Mixing sync and async

TestClient runs the app on its own event loop in a background thread. If an async fixture creates an async database engine or connection pool on the pytest plugin's loop, the app then uses that resource from a different loop. That fails with errors about futures or connections attached to another loop.

Running both pytest-asyncio and the anyio plugin adds a second source of confusion over which one owns the loop. The fix is to choose one model per test module. Use either sync TestClient with sync fixtures, or AsyncClient with async fixtures on a single plugin.

When should you avoid dependency overrides, and what are the alternatives?

Override the narrowest dependency that touches the outside world, such as get_db_session or get_payment_client, not the whole lifespan. A narrow override replaces one seam and leaves routing, validation and the rest of the dependency graph running as they do in production. Replace the lifespan only when startup connects to infrastructure CI cannot reach, such as a message broker or a secrets service. Even then, keep the test lifespan small, so that it builds the same app.state shape with fakes.

Each approach has limits you should plan for:

  • Overriding the lifespan leaves startup code untested. Migrations, pool sizing and connection retries never run, so a broken startup reaches staging first.
  • Fakes drift from real services. They rarely reproduce timeouts, partial failures, error payloads or serialization quirks such as decimals and timezone-aware datetimes.
  • Rollback isolation breaks in several cases. It fails when the code under test commits itself, opens its own connections, or relies on deferred constraints or triggers that only fire at commit.
  • Over-granular dependencies make route signatures noisy. If every client gets its own Depends, the signatures fill up with test plumbing.
Approach Suits Maintenance cost
Dependency overrides Route and business-logic tests that need one external seam replaced Low, but fakes must be updated as real APIs change
Test lifespan CI without access to startup infrastructure Medium, because it must mirror the real app.state layout
unittest.mock patching Module-level calls that are not exposed as dependencies High, because patch targets break when imports move
Containerized integration tests Commit behavior, constraints, triggers and startup code High, because tests are slower and need container tooling in CI

How can you verify that an override actually took effect?

A dependency override fails silently when it misses. If the key in app.dependency_overrides is not the exact callable the route declares, FastAPI resolves the real dependency instead, and the test may still pass against a live service. That can happen after a refactor, a wrapper function, or a re-export from a different module. The defenses below turn that silent miss into a test failure.

Make the fake record its calls

Give the fake a list or counter that it appends to on each call, and assert on it after the request: it was called, the expected number of times, with the arguments you expect. A green status code only shows that something answered. A recorded call shows that your fake answered.

Make the real dependency refuse to run in tests

Have the real provider check a setting, such as an environment flag your test configuration sets, and raise an exception when that flag indicates a test run. Any route that reaches the real implementation during the suite then errors out instead of opening a network connection.

Check that override keys are actually used

Add one test that collects every dependency callable reachable from the app's routes and asserts that each key in dependency_overrides appears among them. Walking each route's dependency tree relies on FastAPI internals, so keep this logic in a single helper that you can fix if those internals change. A stale key then fails this test, and you don't have to notice a missing call by hand.

Keep a small full-lifespan suite

Overrides only prove the wiring that tests touch. Keep a handful of tests that run the real lifespan against real or containerized dependencies, with no overrides. They catch drift between fakes and the services they stand in for, which no assertion on a fake can detect.

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 overrides, 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.