Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 50 ยท Dependency injection

Router-level and global dependencies

Apply FastAPI dependencies to a single decorator, a whole APIRouter or the entire app, build auth guards, and shorten signatures with Annotated aliases.

So far each endpoint asked for its dependencies one parameter at a time. That is perfect when the endpoint uses the value. But often a rule must apply to a whole group of endpoints and the endpoint itself does not care about the result: "every admin route needs a valid API key", "every route must log the request". Repeating the parameter on thirty functions invites the one mistake that leaves a door open.

FastAPI lets you attach dependencies at three higher levels: the decorator, the router and the app. In this lesson you will use all three, see the exact order in which they run, build a reusable authentication guard, and tidy your signatures with Annotated aliases.

Dependencies that return nothing useful

Sometimes you want a dependency purely for its side effect: it checks something and raises an error, or it records something. There is nothing to receive, so an unused parameter would only be noise. Instead, pass a list to the dependencies argument of the decorator:

Python
@app.get("/reports", dependencies=[Depends(require_key)])
async def reports():
    return [...]

The dependency runs before the endpoint, its parameters are validated and documented, and if it raises, the endpoint never runs. Its return value is simply thrown away.

Three levels

The same dependencies=[...] list exists in three places:

Where can you attach a dependency?

One endpoint @app.get(..., dependencies=[...])
One router APIRouter(dependencies=[...])
The whole app FastAPI(dependencies=[...])

Wider levels run first; narrower levels run after them.

1 / 2

You can also add dependencies when you plug a router in: app.include_router(router, dependencies=[...]). That is handy when the same router is mounted twice with different rules, or when the router comes from another package that you cannot edit.

The order of execution

The next example puts one logging dependency on each level, plus an API-key guard on the router. Run it and read the order in which they fire.

Python App, router, decorator and parameter dependencies in order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first line shows the order: app, router, require_key, decorator, param. Wider scopes run first, parameters of the endpoint last. The second request has no key: the chain stops at require_key, so decorator and param never run and the client gets 401. The third request hits /public, which is outside the router, so only the app-level dependency ran.

The require_key guard is written once and protects every route added to that router later, including routes you add next year. That is the strength of router-level dependencies: new endpoints are protected by default and cannot be forgotten.

An authentication guard

Most guards follow a pattern with two layers:

  1. get_current_user reads credentials (a header, a cookie, a token), finds the user, and raises 401 if it cannot.
  2. A second dependency builds on it and enforces a rule, such as "must be an admin", raising 403 if the rule fails.

Endpoints that need the user as a value take it as a parameter; routers that only need the check put it in dependencies=. The two status codes mean different things: 401 says "I don't know who you are", 403 says "I know you, and the answer is no". Roles, scopes and permissions goes much deeper; here is the skeleton.

flowchart TD
    A["Request"] --> B{"Valid credentials?"}
    B -->|"no"| C["401 Not authenticated"]
    B -->|"yes"| D{"Allowed to do this?"}
    D -->|"no"| E["403 Forbidden"]
    D -->|"yes"| F["Endpoint runs"]

A guard ends the request early with 401 or 403, otherwise the endpoint runs.

Annotated aliases keep signatures short

Writing Annotated[User, Depends(get_current_user)] in every endpoint is long and easy to get slightly wrong. Because Annotated[...] is just a Python expression, you can give it a name once and reuse it everywhere:

Python
CurrentUser = Annotated[User, Depends(get_current_user)]
AdminUser = Annotated[User, Depends(require_admin)]

async def profile(user: CurrentUser): ...

The alias carries both the type (for your editor) and the dependency (for FastAPI). Changing how authentication works means editing one line. Put aliases next to the dependency they wrap, and import them where needed, as the next lesson's layout does.

Python get_current_user, require_admin and Annotated aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Follow the five requests: no header and a bad token both give 401; Bob is authenticated, so /profile works, but deleting a user gives him 403; Ada, an admin, succeeds. Because require_admin depends on get_current_user, authentication always happens first, and the token is looked up only once per request thanks to caching.

Dependencies listed on a router protect only the routes on that router. A route you register directly on app is not covered, and a router you forget to include is not protected either. For rules that must hold everywhere, such as "log every request", use an app-level dependency. For security, also write a test that calls each protected URL without credentials and expects 401.

Choosing the level

  • Decorator level for one-off checks on a single endpoint.
  • Router level for an area with one policy: /admin, /internal, /v2.
  • App level for cross-cutting behavior that has no exceptions: audit logging, request counting, a global feature flag.
  • Parameter when the endpoint needs the value, such as the current user.

Not everything belongs in a dependency. Behavior that must wrap the whole request, including routing errors and responses (timing, CORS, compression), is middleware, which you will meet in Middleware and CORS.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which argument attaches a dependency to a route without receiving its return value?

    The dependencies list runs each dependency before the endpoint and discards what it returns. The same argument exists on APIRouter, FastAPI and include_router.
  2. 2. An app has an app-level dependency, a router-level dependency and a decorator-level dependency. In what order do they run for a route on that router?

    Wider scopes run first: app, then router, then the decorator's list, and finally the endpoint's own parameter dependencies.
  3. 3. Which status code should a guard raise for a request with a valid token whose user lacks the required role?

    401 means the caller could not be identified; 403 means they are known but not allowed.
  4. 4. What is the main benefit of CurrentUser = Annotated[User, Depends(get_current_user)]?

    An alias is only a reusable annotation. It shortens signatures and gives you one place to change, but you still have to use it (or a router-level dependency) on each route that needs it.

Summary

  • dependencies=[Depends(...)] runs a dependency for its side effect or check; the return value is ignored.
  • The list exists on the decorator, on APIRouter, on include_router and on FastAPI(...).
  • Order: app, router, decorator, then the endpoint's parameters; a raised error stops the chain.
  • Build guards in layers: get_current_user (401), then require_admin (403).
  • Annotated aliases such as CurrentUser keep signatures short and changes local.
  • Router dependencies only cover routes on that router; test protected URLs without credentials.

Next: Routers and project layout shows how to split a growing API into modules.