Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 50 ยท Dependency injection

Dependencies

Learn FastAPI dependency injection: write functions with Depends, share query parameters, chain sub-dependencies, understand caching and swap them in tests.

Almost every endpoint needs something that is not part of its own business logic: the current user, a database session, pagination settings, a check that a header is present. If you copy that code into every function, your API turns into a pile of repetition. FastAPI solves this with dependency injection: you write the shared piece once as a plain function, and the endpoint simply declares that it needs it.

Think of a dependency as an ingredient that FastAPI prepares before your function runs. You say what you need with Depends(...), and FastAPI calls the dependency, validates its inputs exactly like it does for endpoint parameters, and hands you the result. In this lesson you will write your first dependencies, chain them together, see how results are cached within a request, and replace them in tests with dependency_overrides.

All examples on this site use async def for dependencies and endpoints, because the in-browser runner has no threads. In a normal project, plain def dependencies work too: FastAPI runs them in a worker thread. See async def vs def endpoints for the details.

What Depends does

A dependency is any callable: usually a function, sometimes a class (you will meet those in Class and yield dependencies). The recipe has three steps:

  1. Write a function. Its parameters can be anything an endpoint accepts: path, query, header, cookie or body parameters.
  2. In the endpoint, add a parameter whose default (or Annotated metadata) is Depends(that_function).
  3. FastAPI calls your function for each request and passes the return value into the endpoint.

One function, many endpoints

Write it once A plain function holds the shared logic.
Declare it The endpoint adds Depends(function).
FastAPI calls it Inputs are parsed and validated for you.
You get the result The return value arrives as a parameter.
1 / 2

The modern spelling uses Annotated, which keeps the type and the dependency side by side:

Python
from typing import Annotated
from fastapi import Depends

async def endpoint(value: Annotated[int, Depends(my_dependency)]): ...

The older style value: int = Depends(my_dependency) still works, but Annotated is the recommended form, and it lets you reuse the whole annotation as an alias (more on that in Router-level and global dependencies).

Sharing parameters, chaining dependencies

The first example has two jobs. paging is the classic case: several list endpoints need page and size query parameters with the same defaults and the same upper limit. Written as a dependency, the parameters appear in the OpenAPI documentation of every endpoint that uses it, with validation included.

The second job is a chain. get_badge depends on get_user, which depends on get_token, which reads the X-Token header. Dependencies that depend on other dependencies are called sub-dependencies, and FastAPI resolves the whole tree for you. A dependency may also stop the request by raising HTTPException; the endpoint is never called in that case.

Python Shared paging parameters and a dependency chain

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.

Read the output from the top. /items uses the defaults, and size=500 is clamped to 50 by the dependency, so page 3 starts at offset 100. The bad page=x produces a normal 422 whose loc points at the query parameter page: dependency parameters are validated just like endpoint parameters.

Now look at the CALLS list. The request without a header stopped inside get_token (the first entry). The successful request produced get_token, get_user, get_badge. Even though both get_user and get_badge ask for the token, get_token ran only once for that request. That is the caching rule, explained next.

Per-request caching

If the same dependency appears several times in one request, whether directly or deep inside the tree, FastAPI calls it once and reuses the result. This matters when the dependency does something expensive, such as decoding a token or opening a database session: every part of the request sees the same object.

The cache lives only for a single request. The next request calls everything again, so there is no stale data shared between users.

Sometimes you want a fresh call every time, for instance a dependency that returns a new random id. Pass use_cache=False:

Python
async def new_id() -> str:
    return uuid4().hex

async def endpoint(
    first: Annotated[str, Depends(new_id)],
    second: Annotated[str, Depends(new_id)],                    # same value as first
    third: Annotated[str, Depends(new_id, use_cache=False)],    # fresh call
): ...

Two different functions that return similar things are different dependencies and never share a cache entry. The cache key is the dependency callable itself (plus its security scopes, which you will meet in Roles, scopes and permissions).

flowchart TD
    R["Request /me"] --> B["get_badge"]
    B --> U["get_user"]
    B --> T["get_token"]
    U --> T
    T --> H["X-Token header"]

Both get_user and get_badge need get_token, but FastAPI runs it only once per request.

Replacing dependencies in tests

Because the endpoint never builds its own helpers, you can swap them from the outside. Every FastAPI app has a dictionary called dependency_overrides. Put the original function as the key and a replacement as the value. From then on, FastAPI calls the replacement wherever the original was requested.

This is the standard way to test endpoints without a real database, real clock or real login: override the dependency with a fake that returns fixed data. The replacement may even have different parameters of its own, because it is resolved like any other dependency.

Python Overriding a dependency with dependency_overrides

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 same endpoint gives three different answers without a single change to its code. Always clean up afterwards (clear() or pop(original, None)), otherwise the fake leaks into later tests. Testing FastAPI apps turns this into a reusable fixture pattern.

Design tips

  • Keep dependencies small and named for what they provide: get_current_user, paging, get_session. A name like common hides intent.
  • Return values, not responses. A dependency hands data to the endpoint, or raises HTTPException to stop. It should not build the final response.
  • Do not hide business logic here. Dependencies are for plumbing: parsing, authentication, resources. Rules about orders or prices belong in service functions you can call from anywhere.
  • Dependencies are visible in the docs. Parameters they declare (query, headers) show up in /openapi.json for every endpoint that uses them, so the documentation stays truthful.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an endpoint receive when it declares user: Annotated[dict, Depends(get_user)]?

    FastAPI calls the dependency for each request, resolves its own parameters, and passes the return value into the endpoint.
  2. 2. A request needs get_token through two different sub-dependencies. How many times does FastAPI call get_token for that request by default?

    Within one request the result is cached per callable. Depends(get_token, use_cache=False) turns that off. The cache never survives into the next request.
  3. 3. How do you replace a dependency with a fake during a test?

    dependency_overrides maps the original callable to its replacement. Clear it afterwards so other tests see the real dependency.
  4. 4. What happens when a dependency raises HTTPException(status_code=401)?

    An HTTPException raised in a dependency is handled like one raised in the endpoint, so the request ends there with that status code.

Summary

  • A dependency is a callable; the endpoint asks for it with Annotated[T, Depends(fn)] and receives its return value.
  • Dependency parameters (query, header, cookie, body) are parsed, validated and documented like endpoint parameters.
  • Dependencies can depend on other dependencies; FastAPI resolves the whole tree.
  • Results are cached per request; use use_cache=False for a fresh call each time.
  • A dependency can end the request early by raising HTTPException.
  • app.dependency_overrides swaps dependencies for tests; clear it afterwards.

Next: Class and yield dependencies shows dependencies that are classes and dependencies that clean up after themselves.