skip to content

Sub-Dependency Reuse

Depends() resolves a tree of functions and classes once per request and caches repeated ones. Interviewers ask why a dependency used twice runs once, and how use_cache=False changes that.

on this pageshow

explore

questions

6

In FastAPI, what does Depends() do with a function, and how does an Annotated alias let several endpoints share it?

level: juniorimportance: must knowfreq 75%

answer

  1. pass the callable, not its result
  2. signature read like an endpoint's
  3. parameters land in the docs
  4. type plus Depends in one alias

basics

~20 s

fastapi.Depends(func) tells FastAPI to call func for each request, reading func's own parameters as request inputs, and inject its return value. An alias such as Paging = Annotated[dict, Depends(paging)] bundles the type and the Depends so every endpoint reuses one declaration.

solid answer

~40 s

`Depends` takes a callable, a *dependable*, and you pass it uncalled: `Depends(paging)`, not `Depends(paging())`. FastAPI inspects that callable's signature exactly as it inspects a path operation's, so `skip: int = 0` becomes a validated query parameter, shows up in `/docs`, and a bad value produces the usual 422 before your endpoint runs. On each request FastAPI calls the dependable and passes its return value into the parameter. Writing `Paging = Annotated[dict[str, int], Depends(paging)]` once lets every listing endpoint declare `page: Paging`; the type checker sees a `dict`, FastAPI sees the `Depends`. A `def` dependable runs in the thread pool and an `async def` one is awaited, and either kind works with either kind of endpoint.

code

python · 28 lines
python
from typing import Annotated

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

app = FastAPI()


def paging(skip: int = 0, limit: int = 20) -> dict[str, int]:
    return {"skip": skip, "limit": limit}


Paging = Annotated[dict[str, int], Depends(paging)]


@app.get("/orders")
def list_orders(page: Paging):
    return {"orders": [], **page}


@app.get("/invoices")
async def list_invoices(page: Paging):
    return {"invoices": [], **page}


client = TestClient(app)
print(client.get("/orders?skip=40").json())
print(client.get("/invoices?limit=abc").status_code)

go deeper

for a junior

Recall that Depends takes the callable uncalled, that its parameters become request inputs, and that the endpoint receives the return value.

for a middle

Explain that FastAPI analyses a dependable's signature like an endpoint's, merging its parameters into validation and OpenAPI, and how def and async def dependables are scheduled.

for a senior

Show how shared Annotated aliases keep defaults, types and wiring from drifting across many endpoints, and where a dependable's parameters become public contract.

for a principal

Weigh how much of a team's request contract should live in shared aliases versus explicit endpoint parameters, given that every dependable input is published in the schema.

## What `Depends` is In FastAPI a **dependency** is any callable whose result a path operation needs: a function, a class, or an object with a `__call__` method. The FastAPI docs call that callable a **dependable**. You declare the need with `fastapi.Depends`, usually inside `Annotated`: - `page: Annotated[dict, Depends(paging)]` means "call `paging` for this request and give me what it returns". - You pass the callable itself. `Depends(paging())` calls `paging` once at import time and hands FastAPI a `dict`; the route registration fails with a `TypeError` saying the value is not a callable object. - The older default-value spelling, `page: dict = Depends(paging)`, still works, but the docs recommend the `Annotated` form. ## FastAPI reads the dependable's signature The point of `Depends` is that the dependable is analysed with the same machinery as an endpoint. Its parameters are not passed by you; FastAPI fills them: 1. A plain parameter such as `skip: int = 0` becomes a **query parameter**, converted and validated. 2. `Header()`, `Cookie()`, `Path()` and `Body()` markers work there too, as do `Request` and `BackgroundTasks`. 3. A parameter that is itself `Annotated[..., Depends(other)]` makes `other` a **sub-dependency**, resolved first. Because of this, everything the dependable declares is merged into the endpoint's **OpenAPI** operation. In the example below `/orders` lists `skip` and `limit` in `/docs` even though `list_orders` never names them, and `?limit=abc` gets the standard 422 validation body before the endpoint body runs. ## Sharing it with an `Annotated` alias `Annotated[T, Depends(f)]` is an ordinary Python object, so you can bind it to a name and reuse it: ```python Paging = Annotated[dict[str, int], Depends(paging)] @app.get("/orders") def list_orders(page: Paging): ... ``` That one line removes three kinds of drift across a codebase: - **Type drift**: the type checker and the editor see `dict[str, int]` everywhere the alias is used. - **Wiring drift**: nobody can attach the type to the wrong dependable by hand. - **Default drift**: the paging defaults live in `paging` and nowhere else; change `limit: int = 20` once and every listing endpoint follows. Aliases compose. A `CurrentUser = Annotated[User, Depends(get_current_user)]` alias can be used both by endpoints and inside other dependables, which is how dependency trees are usually built in FastAPI codebases. ## `def` or `async def` FastAPI decides how to call a dependable from its definition, not from the endpoint that uses it: | Dependable | How FastAPI calls it | |---|---| | `async def` function | awaited on the event loop | | `def` function | run in the thread pool through `run_in_threadpool` | | class | the class is called (in the thread pool) to build an instance | | instance with `async def __call__` | `__call__` awaited | Mixing is allowed in every direction: an `async def` endpoint may depend on a `def` dependable and vice versa. Pick `async def` when the dependable awaits I/O, and `def` when it calls blocking code. ## What the endpoint sees The endpoint receives only the dependable's **return value**. It never sees the query parameters that fed it unless it declares them itself, which keeps listing endpoints short: `list_orders(page: Paging)` reads as "an orders listing with standard paging". If the dependable raises `HTTPException`, the endpoint is never called and the client gets that error. ## One request, step by step For `GET /orders?skip=40` against the example below, FastAPI does this: 1. Matches the route and finds one dependency, `paging`, behind the `Paging` alias. 2. Reads `skip` and `limit` from the query string, converting `"40"` to `40` and filling `limit` from its default. 3. If any value fails validation, it collects the error and answers 422 without calling `paging` or the endpoint. 4. Otherwise it calls `paging(skip=40, limit=20)`; because `paging` is a plain `def`, the call goes through the thread pool. 5. It calls `list_orders(page={"skip": 40, "limit": 20})` and serializes the result. The same steps run for `/invoices`; only the endpoint differs. That is the whole contract of a dependency: the endpoint states *what* it needs, and FastAPI works out *how* to produce it from the request. ## Common mistakes - Calling the function inside `Depends`, which fails at route registration. - Copying `skip: int = 0, limit: int = 20` into every endpoint instead of one dependable, so the defaults diverge. - Expecting the dependable's parameters to be hidden from `/docs`: they are part of the endpoint's public contract.

  • In FastAPI, can a dependable declare a request body or headers, not only query parameters?
    Yes. A dependable's signature accepts the same markers as an endpoint: `Header()`, `Cookie()`, `Path()`, `Body()`, a Pydantic model body, `Request`. FastAPI merges all of them into the operation and validates them together, so a missing header declared in a dependable produces the same 422 as one declared on the endpoint.
  • Why does Paging = Annotated[dict, Depends(paging)] work as a type alias at all?
    `Annotated` attaches metadata to a type without changing it. Type checkers read only `dict`; FastAPI reads the metadata and finds the `Depends`. Because the whole `Annotated[...]` expression is a value, binding it to a name and reusing it is ordinary Python, and FastAPI treats each use exactly like the spelled-out form.

  • Writes Depends(paging()) and expects FastAPI to call it per request.
  • Thinks a dependable's query parameters stay hidden from the generated docs.
  • Believes an async def endpoint can only use async def dependencies.
  • Copies the same paging parameters into every endpoint instead of one dependable.
  • Says the Annotated alias changes the runtime type the endpoint receives.
open as a page

In FastAPI, why does a dependency used by both a sub-dependency and the endpoint run once per request, and what does use_cache=False change?

level: middleimportance: must knowfreq 65%

basics

~20 s

FastAPI keeps a cache for each request, keyed by the dependable callable, so a dependency declared in several places in one request is called once and every consumer receives the same returned object. Depends(f, use_cache=False) makes that declaration call f again.

open as a page

In FastAPI, how do Depends(RateLimiter) and Depends(RateLimiter(limit=10)) differ when RateLimiter is a class with __init__ and __call__?

level: middleimportance: should knowfreq 45%

basics

~10 s

Depends(RateLimiter) makes FastAPI call the class per request, so init's limit becomes a client-supplied query parameter. Depends(RateLimiter(limit=10)) passes a configured instance; FastAPI reads and calls call and never touches init.

open as a page

In FastAPI, how do dependencies=[...] on a path operation decorator, an APIRouter and the FastAPI app differ from a Depends parameter?

level: middleimportance: should knowfreq 45%

basics

~10 s

Dependencies listed in dependencies=[...] run for the request like parameter dependencies, but their return values are discarded. FastAPI runs app-level ones first, then router-level, then decorator-level, then the endpoint's parameter dependencies.

open as a page

After a refactor, a FastAPI rate-limit dependency declared on an APIRouter and again inside a permission sub-dependency counts every request twice; what causes it, and how do you fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

FastAPI's per-request cache is keyed by the dependable object, and each RateLimiter(limit=10) expression builds a different instance, so the two declarations never share an entry and both run. Create one instance and reuse it, ideally through an Annotated alias.

open as a page

As a lead, would you have FastAPI endpoints declare authentication one by one, or make it the default through router- or app-level dependencies, and where would public routes go?

level: principalimportance: should knowfreq 35%

basics

~20 s

Make it the default: attach the auth dependency to each protected APIRouter so new routes are covered without anyone remembering, keep public routes on one separate router, and inject the user as a parameter only where a handler needs it.

open as a page