In FastAPI, what exactly must the key of app.dependency_overrides be, and why can a registered override silently never apply?
answer
- a dict lookup, not a name match
- the object Depends received
- an Annotated alias is a type
- no error for a missed key
basics
~20 sThe key must be the exact callable given to Depends: the function, class, callable instance or lru_cache wrapper. FastAPI does a plain dict lookup, so an alias, a name or a look-alike never matches and raises no error.
solid answer
~40 sWhile resolving each sub-dependency, FastAPI runs `app.dependency_overrides.get(original_call, original_call)`, where `original_call` is the object the declaration passed to `Depends`. So the key must be that exact object: the function `get_payment_client`, the class for a `Depends()` class dependency, the instance for a callable-instance dependency, or the `@lru_cache` wrapper if that is what was passed. An `Annotated[PaymentClient, Depends(get_payment_client)]` alias is a typing object, not the callable, so using it as a key does nothing. The same goes for a test-local function with the same name, or a module loaded twice under two import paths. Nothing validates keys, so a wrong one fails silently and the real dependency runs; a test should assert something only the fake can produce.
code
python · 36 linesfrom typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
class PaymentClient:
name = "live"
def get_payment_client() -> PaymentClient:
return PaymentClient()
PaymentDep = Annotated[PaymentClient, Depends(get_payment_client)]
app = FastAPI()
@app.post("/checkout")
def checkout(payments: PaymentDep):
return {"client": payments.name}
class FakePaymentClient:
name = "fake"
client = TestClient(app)
app.dependency_overrides[PaymentDep] = FakePaymentClient # the alias: never looked up
print(client.post("/checkout").json())
app.dependency_overrides = {get_payment_client: FakePaymentClient} # the original callable
print(client.post("/checkout").json())
app.dependency_overrides.clear()go deeper
Remember that the key is the function you passed to Depends, not the alias and not a string.
Explain the dict.get lookup during dependency resolution and list which object is the key for functions, classes, callable instances and lru_cache wrappers.
Show how a wrong key fails silently and which assertions and loud-failing real clients turn that into a visible test failure.
Argue for one canonical import path and shared override helpers so keys cannot drift between the application and the test suite.
## How FastAPI uses the dict `app.dependency_overrides` is a plain `dict` on the `FastAPI` object. FastAPI's dependency solver walks the dependency graph of each request and, for every dependency, checks whether the dict is non-empty; if it is, it does this (simplified from `fastapi/dependencies/utils.py`): ```python original_call = sub_dependant.call call = app.dependency_overrides.get(original_call, original_call) ``` `sub_dependant.call` is whatever object the declaration handed to `Depends(...)`. That one line explains every rule below: the override applies **only** when the key is equal to that object, and for functions and most classes equality means identity. ## What counts as the right key | Declaration | Key to use | |---|---| | `Depends(get_payment_client)` | the function `get_payment_client` | | `Annotated[PaymentClient, Depends()]` | the class `PaymentClient` (FastAPI calls the annotation) | | `Depends(checker)` where `checker` is an instance with `__call__` | that same instance `checker` | | `Depends(get_settings)` where `get_settings` is decorated with `@lru_cache` | the decorated `get_settings`, the wrapper object | | `SessionDep = Annotated[Session, Depends(get_session)]` | `get_session`, never `SessionDep` | The value can be any callable FastAPI can treat as a dependency: a function, a `yield` function, a lambda, or a class such as `FakePaymentClient`, which FastAPI then instantiates per request. ## How an override silently misses Because the lookup is a `dict.get` with the original as default, a key that matches nothing is not an error. Common ways to get there: - **Keying by the `Annotated` alias.** `SessionDep` or `PaymentDep` is a typing construct that only *carries* a `Depends`. FastAPI never looks it up. - **Keying by a look-alike.** A test file that defines its own `get_payment_client` creates a different function object; the name is irrelevant. - **A module imported twice.** If the test's import path lets the same file load as two modules (for example `app.deps` and `deps`), each load creates its own function objects, and an override keyed by one copy misses routes declared with the other. - **Keying by a call result.** `app.dependency_overrides[get_payment_client()]` uses the returned object as the key, not the function. - **An anonymous callable.** `Depends(lambda: PaymentClient())` or a `functools.partial` built inside the declaration is an object the test has no clean way to name, so in practice it cannot serve as a key. Declare dependencies as named, importable callables if tests are meant to replace them. - **The wrong application object.** A FastAPI sub-application attached with `app.mount` has its own `dependency_overrides`; entries on the parent do not reach its routes. Routers added with `include_router` do share the parent's dict. ## Why the failure is quiet Nothing in FastAPI checks that a key corresponds to a declared dependency, and the generated OpenAPI schema is identical either way. A test that only asserts `status_code == 200` will often pass against the real dependency too, or fail far from the cause with a network error from the real payment client. Defensive habits: 1. Import the dependency from the same module path the application uses. 2. Assert on something only the fake can produce, such as a sentinel value or a recorded call on the fake. 3. Make the real outbound client fail loudly in tests (for example, no credentials configured), so a missed override surfaces as an obvious error rather than a slow external call. ## What the override inherits The override replaces the callable, not the declaration around it. FastAPI builds the replacement's own parameters by inspecting the override (so its parameters become request inputs or sub-dependencies), but it keeps the original declaration's place in the graph: the per-request cache entry is still keyed by the original callable, and the original declaration's settings such as `use_cache` and a yield dependency's `scope` are carried over. That is why one override is enough for every place the original appears. ## Summary Think of the key as "the object between the parentheses of `Depends`". If that object is a function, use the function; if `Depends()` is empty, use the annotated class; if it is an alias, unwrap it to the function inside. Anything else is a key FastAPI will never ask for, and it will tell you nothing.
- How do you override a class dependency declared as Annotated[PaymentClient, Depends()]?With an empty `Depends()`, FastAPI uses the annotated class itself as the callable, so the key is `PaymentClient`. The value can be a fake class or a function returning a fake instance; FastAPI calls it per request just as it would have called `PaymentClient()`.
- Why does an override on the main app not reach routes of a FastAPI app attached with app.mount?A mounted sub-application is a separate `FastAPI` object whose routes resolve dependencies against its own `dependency_overrides`. Register the override on the sub-app as well. Routers added with `include_router` are different: their routes use the including app's dict.
- Overriding the Annotated alias SessionDep replaces the session everywhere it is used.
- FastAPI matches override keys by function name, so a same-named test function works.
- FastAPI raises an error when an override key matches no declared dependency.
- A @lru_cache-decorated dependency cannot be overridden because the cache answers first.
- Overrides on the main app also apply to sub-applications attached with app.mount.