skip to content

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%

answer

  1. run, but value thrown away
  2. app, router, decorator, parameters
  3. raise to reject the request
  4. same per-request cache

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.

solid answer

~40 s

`dependencies=[Depends(check_tenant)]` asks FastAPI to resolve `check_tenant` for every matching request without injecting its value, which suits checks whose job is to raise `HTTPException` or record something. You can attach the list at three levels: `FastAPI(dependencies=[...])` for every path operation, `APIRouter(dependencies=[...])` or `include_router(..., dependencies=[...])` for a group, and `@router.get(..., dependencies=[...])` for one operation. FastAPI prepends them to the endpoint's own dependency list in that order (app, router, decorator), then resolves the parameter dependencies, and if one raises the rest never run. They take part in validation, the generated docs and the per-request cache exactly like parameter dependencies, so a check declared on the router and needed again by a parameter runs once.

code

python · 42 lines
python
from typing import Annotated

from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient

order: list[str] = []


def log_request():
    order.append("app")


def check_tenant(x_tenant: Annotated[str, Header()]):
    order.append("router")
    if x_tenant != "acme":
        raise HTTPException(status_code=404)


def audit():
    order.append("decorator")
    return "ignored"


def paging(skip: int = 0):
    order.append("parameter")
    return skip


app = FastAPI(dependencies=[Depends(log_request)])
router = APIRouter(prefix="/reports", dependencies=[Depends(check_tenant)])


@router.get("/", dependencies=[Depends(audit)])
def list_reports(skip: Annotated[int, Depends(paging)]):
    return {"order": order, "skip": skip}


app.include_router(router)
client = TestClient(app)
print(client.get("/reports/", headers={"x-tenant": "acme"}).json())
order.clear()
print(client.get("/reports/", headers={"x-tenant": "other"}).status_code, order)

go deeper

for a junior

Remember that dependencies=[...] runs a dependency without giving its value to the endpoint, and that it can be set on the app, a router or one decorator.

for a middle

Explain the additive app, router, decorator, parameter order, that a raise stops the rest, and that list dependencies share validation, docs and the per-request cache.

for a senior

Use the order deliberately so cheap rejections happen before expensive dependencies, and audit which routes inherit an app-level or router-level check.

for a principal

Decide which checks a team enforces at app or router level versus per operation, weighing safety by default against how visible each check stays to readers.

## Two ways to attach a dependency A dependency can reach a path operation in two ways: - As a **parameter**: `user: Annotated[User, Depends(get_current_user)]`. FastAPI resolves it and injects the return value. - In a **`dependencies` list**: `dependencies=[Depends(check_tenant)]`. FastAPI resolves it exactly the same way but **discards the return value**. The list form exists for dependencies whose effect matters and whose value does not: a check that raises `HTTPException`, a header that must be present, an audit hook. It also avoids an unused parameter that linters flag and new readers delete. ## The three levels | Where | Applies to | Spelling | |---|---|---| | Application | every path operation in the app | `FastAPI(dependencies=[Depends(f)])` | | Router | every path operation in that router | `APIRouter(dependencies=[...])` or `app.include_router(router, dependencies=[...])` | | Decorator | one path operation | `@router.get("/", dependencies=[Depends(f)])` | They are **additive**, not overriding: a route inside a router with its own list and inside an app with a list gets all three. ## Execution order When FastAPI builds a route it puts the list dependencies in front of the endpoint's parameter dependencies. For one request the order is: 1. App-level dependencies, in list order. 2. Router-level dependencies (including those passed to `include_router`), outer router first. 3. Decorator-level dependencies, in list order. 4. The endpoint's parameter dependencies, in signature order, each with its own sub-dependencies first. The example prints `['app', 'router', 'decorator', 'parameter']`. If a dependency raises, the remaining ones and the endpoint never run: with a wrong `X-Tenant` header the router check raises a 404 and only `app` and `router` were recorded. That ordering is a design tool. Put cheap, broad checks at the app or router level so they reject a request before expensive parameter dependencies, such as a database lookup, start. ## What stays the same List dependencies are full dependencies: - Their own parameters are read from the request and validated, so a router-level `x_tenant: Annotated[str, Header()]` makes the header required on every route in that router, appears in `/docs`, and a missing header gets a 422. - They can have sub-dependencies. - They share the **per-request cache** with parameter dependencies. If the router lists `Depends(get_current_user)` and an endpoint also declares `user: CurrentUser`, `get_current_user` runs once and the endpoint gets the value cached by the router-level run. ## What changes - The return value is thrown away. If the endpoint needs the value, declare it as a parameter instead; thanks to the cache this costs nothing extra. - Nothing about them shows in the endpoint's signature, so reading the function alone no longer tells you every check that applies. Document router-level checks where the router is created. ## Parameter or list? A quick decision rule: - The endpoint **uses the value** (the current user, a paging object, a settings object): declare a parameter. - The endpoint **only needs the check to have passed**: put it in the decorator's `dependencies`. - **Every route in a group** needs the check: put it on the `APIRouter`, or pass it to `include_router` when the same router is mounted in several places with different rules. - **Every route in the app** needs it, with no exceptions you can foresee: put it on `FastAPI(...)`. Mixing is normal. A router can list `Depends(get_current_user)` so that no route in it is reachable anonymously, while individual endpoints still declare `user: CurrentUser` to read the user. The per-request cache makes that combination free: the user is loaded once, by the router-level declaration, and handed to the endpoint. ## Typical uses - An app-wide dependency that requires an API version header. - A router-level tenant or permission check for an admin router. - A decorator-level check for one sensitive operation. ## Pitfalls - Expecting a decorator dependency's return value to reach the endpoint. - Assuming a decorator list replaces the router's list; they combine. - Hiding an authorization check at app level and then mounting a public route that should not have it: every path operation in the app gets app-level dependencies.

  • In FastAPI, a router lists Depends(get_current_user) and an endpoint in it also declares user: CurrentUser. How many times does get_current_user run?
    Once. Router-level dependencies join the same per-request cache as parameter dependencies, and they resolve first, so the endpoint's declaration finds the stored value and reuses it. That is why a common pattern lists a check at router level and still reads the value where an endpoint needs it.
  • In FastAPI, does a header declared in a router-level dependency appear in the generated OpenAPI schema?
    Yes. Every dependency, whether declared as a parameter or in a `dependencies` list, contributes its parameters to each affected operation's schema and validation, so the header shows in `/docs` for every route in that router and a missing one produces a 422.

  • Expects the return value of a decorator dependency to be passed to the endpoint.
  • Thinks a path operation's dependencies list replaces the router's list.
  • Believes list dependencies skip validation and the generated docs.
  • Says parameter dependencies run before app-level dependencies.
  • Assumes router dependencies run once at startup rather than per request.