In FastAPI, what does Depends() do with a function, and how does an Annotated alias let several endpoints share it?
answer
- pass the callable, not its result
- signature read like an endpoint's
- parameters land in the docs
- type plus Depends in one alias
basics
~20 sfastapi.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 linesfrom 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
Recall that Depends takes the callable uncalled, that its parameters become request inputs, and that the endpoint receives the return value.
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.
Show how shared Annotated aliases keep defaults, types and wiring from drifting across many endpoints, and where a dependable's parameters become public contract.
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.