FastAPI Dependency Injection Explained with Examples

How FastAPI dependency injection works: Depends, sub-dependencies, yield for cleanup, class dependencies, and overriding dependencies in tests.

FastAPI dependency injection lets a route declare what it needs with Depends, and FastAPI builds those things for each request and passes them in. It is how you share pagination parameters, database sessions, authentication and configuration without global variables.

Every example below was run with FastAPI 0.165.0 (Starlette 1.10.0) on Python 3.14 on 21 November 2026, using FastAPI’s TestClient, and the output shown is real.

At a glance

You want to Use
Share parameters or logic between routes A function passed to Depends
Open a resource and close it afterwards A dependency with yield
Build on another dependency A sub-dependency: a dependency that itself takes Depends
Run a check but not use its value dependencies=[Depends(...)] on a route, router or the app
Replace a dependency in tests app.dependency_overrides
Call a dependency again within one request Depends(func, use_cache=False)

A first dependency

from typing import Annotated
from fastapi import Depends, FastAPI

app = FastAPI()

def pagination(skip: int = 0, limit: int = 10) -> dict:
    return {"skip": skip, "limit": limit}

@app.get("/items")
def list_items(page: Annotated[dict, Depends(pagination)]):
    return {"page": page}

A dependency is a function that takes the same kinds of parameters a path operation function can, as the FastAPI documentation puts it. FastAPI reads skip and limit from the query string, calls pagination, and passes the result in. GET /items returns {"page":{"skip":0,"limit":10}} and GET /items?skip=5&limit=2 returns {"page":{"skip":5,"limit":2}}. Nothing is registered anywhere else.

Cleanup with yield

Use yield when a dependency has exit steps. This example uses a stand-in session class that records what happens:

events = []

class FakeSession:
    def __init__(self):
        events.append("open")

    def close(self):
        events.append("close")

    def all_users(self):
        return ["ada", "bo"]

def get_db():
    db = FakeSession()
    try:
        yield db
    finally:
        db.close()

DbDep = Annotated[FakeSession, Depends(get_db)]

@app.get("/users")
def users(db: DbDep):
    events.append("handler")
    return db.all_users()

After GET /users, events is ['open', 'handler', 'close']. The documentation says only the code up to and including yield runs before the response is created, and the code after it runs after the response is sent. A test that recorded events together with the moment the response started and finished confirmed this on 0.165.0: the default order was enter, handler, response start, response end, exit. Use try with finally so cleanup runs whether or not an exception occurred. Two rules from the same page: use yield once per dependency, and if you catch an exception in such a dependency with except, re-raise it (or raise an HTTPException), otherwise the client gets a 500 error and the server logs nothing about the cause.

To close a dependency sooner, pass scope="function":

@app.get("/early")
def early(db: Annotated[FakeSession, Depends(get_db, scope="function")]):
    ...

With scope="function" the exit code runs after the path operation function returns but before the response is sent to the client; the same test gave enter, handler, exit, response start, response end. The default, scope="request", ends after the response. Scopes were added in FastAPI 0.121.0. See SQLAlchemy vs Django ORM for the session side.

Sub-dependencies

Dependencies can depend on other dependencies:

from fastapi import Header, HTTPException

def get_current_user(x_token: Annotated[str, Header()]) -> dict:
    if x_token != "secret":
        raise HTTPException(status_code=401, detail="Invalid token")
    return {"name": "ada", "is_admin": True}

def require_admin(user: Annotated[dict, Depends(get_current_user)]) -> dict:
    if not user["is_admin"]:
        raise HTTPException(status_code=403)
    return user

@app.get("/admin")
def admin(user: Annotated[dict, Depends(require_admin)]):
    return {"hello": user["name"]}

Without the header the response is 422 (the required x-token header is missing), with a wrong token it is 401 {"detail":"Invalid token"}, and with X-Token: secret it is {"hello":"ada"}. FastAPI resolves the whole chain for each request. For real authentication, FastAPI’s documentation points to its security utilities rather than a hand-rolled header.

Called once per request

If the same dependency is needed in several places in one request, FastAPI calls it once and reuses the value. With a counter:

calls = {"n": 0}

def get_value() -> int:
    calls["n"] += 1
    return calls["n"]

def dep_a(v: Annotated[int, Depends(get_value)]) -> int:
    return v

def dep_b(v: Annotated[int, Depends(get_value)]) -> int:
    return v

def dep_b_fresh(v: Annotated[int, Depends(get_value, use_cache=False)]) -> int:
    return v

A route that depends on dep_a and dep_b returns {"a":1,"b":1} and get_value ran once. A route that depends on dep_a and dep_b_fresh returns {"a":1,"b":2} and get_value ran twice.

Class dependencies and reusable aliases

Anything callable works as a dependency, including a class:

class Pagination:
    def __init__(self, skip: int = 0, limit: int = 10):
        self.skip = skip
        self.limit = limit

@app.get("/class")
def with_class(page: Annotated[Pagination, Depends()]):
    return {"skip": page.skip, "limit": page.limit}

GET /class?skip=3 returns {"skip":3,"limit":10}. When the annotation is the class itself, Depends() needs no argument. To avoid repeating Annotated[..., Depends(...)], define an alias once, as DbDep above.

Dependencies you do not need the value of

If a dependency only checks something, such as an API key, add it to the decorator instead of the function signature:

def require_key(x_key: Annotated[str, Header()]) -> None:
    if x_key != "k":
        raise HTTPException(status_code=400, detail="X-Key header invalid")

@app.get("/protected", dependencies=[Depends(require_key)])
def protected():
    return {"ok": True}

The same dependencies=[...] argument works on APIRouter(...) and on FastAPI(...), applying the check to every route in the router or the whole application. In the test app, all three returned 422 without the X-Key header, 400 with a wrong one and the normal response with X-Key: k.

Overriding dependencies in tests

The most useful side effect of dependency injection is easy testing. The documentation describes app.dependency_overrides as a plain dictionary whose keys are the original dependencies and whose values are the replacements:

from fastapi.testclient import TestClient

class OtherSession(FakeSession):
    def all_users(self):
        return ["test-user"]

def fake_db():
    yield OtherSession()

client = TestClient(app)
app.dependency_overrides[get_db] = fake_db
print(client.get("/users").json())   # ['test-user']
app.dependency_overrides = {}        # reset
print(client.get("/users").json())   # ['ada', 'bo']

The override works wherever the original is used, including in a route decorator or an include_router() call. If you only want it for some tests, set it at the start of the test and reset it at the end. A pytest fixture is a tidy way to do that.

TestClient needs an HTTP client package installed. FastAPI’s testing tutorial says to install httpx, and that worked. Starlette 1.10.0, which FastAPI 0.165.0 resolved to here, printed Using httpx with starlette.testclient is deprecated; install httpx2 instead, and the same test ran without the warning once httpx2 was installed. Check the current recommendation when you set up a project.

Settings as a dependency

A common use is configuration: a function that returns a cached settings object, backed by pydantic-settings.

from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="APP_")
    app_name: str = "demo"
    debug: bool = False

@lru_cache
def get_settings() -> Settings:
    return Settings()

@app.get("/info")
def info(settings: Annotated[Settings, Depends(get_settings)]):
    return {"app_name": settings.app_name, "debug": settings.debug}

With APP_DEBUG=true and APP_APP_NAME=shop set, GET /info returns {"app_name":"shop","debug":true}. The @lru_cache means the Settings object is created once. Because it is a dependency, a test can override get_settings like any other.

FastAPI builds on Pydantic and Starlette; see FastAPI vs Starlette and Django vs FastAPI vs Flask for where it fits. Models migrate from v1 as described in Pydantic v1 to v2. Run it with Uvicorn.

Frequently Asked Questions

What is dependency injection in FastAPI?

A way for a route to declare what it needs, such as pagination parameters, a database session or the current user, using Depends. FastAPI calls the dependency for each request and passes the result into your path operation function.

How do I use Depends in FastAPI?

Write a function that returns what you need, then add a parameter to your route typed Annotated[Type, Depends(function)]. FastAPI added support for Annotated, and began recommending it, in version 0.95.0.

How do I clean up a dependency, such as closing a database session?

Use yield in the dependency, ideally inside try and finally. Code before the yield runs before the route and the yielded value is injected. By default the code after the yield runs after the response has been sent. Depends(scope=‘function’) runs it after the path operation function returns but before the response is sent.

How do I test a FastAPI app with dependencies?

Replace dependencies in tests with app.dependency_overrides, a dictionary that maps the original dependency function to a replacement. Reset it afterwards by setting app.dependency_overrides to an empty dict. The override works wherever the dependency is used.

Are dependencies called once per request?

A dependency declared several times for the same request, for example as a common sub-dependency, is called once and its value cached for that request. Pass use_cache=False to Depends to run it again each time.