On this page

FastAPI Dependency Injection – Mastering Depends()

Published on August 10, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

FastAPI Dependency Injection: Mastering Depends()

Dependency injection is the mechanism FastAPI uses to share logic, resources, and validation across multiple routes without duplicating code. A route declares what it needs — a database session, a verified user, a pagination object — and FastAPI resolves and provides it automatically before the route handler ever runs. This article covers every form the Depends() system takes: function dependencies, the Annotated syntax, classes as dependencies, nested dependencies, parameterized factories, router-level and global guards, and how to override dependencies in tests.


What Dependency Injection Solves​

Without dependency injection, shared logic ends up living in one of two places: duplicated inline in every route handler, or in a helper function every handler calls manually. Both break down as a codebase grows — duplicated code drifts out of sync over time, and a manually called helper is one missed line away from being forgotten entirely in a new route. Authentication is the clearest example: without dependency injection, every protected route has to decode a token, look up the user, check is_active, and raise a 401 — four steps repeated across dozens of routes. With dependency injection, those four steps live in a single function FastAPI calls automatically, injecting the result directly into whichever route declared it.

Dependency injection isn't a FastAPI invention — it's a general software design pattern. What makes FastAPI's version of it clean is that a dependency is just an ordinary Python function: no decorators, no registration step, no framework-specific base class required.


How Depends() Works​

Depends(some_function) tells FastAPI: before calling this route handler, call some_function, and pass whatever it returns into this parameter. FastAPI inspects some_function's own parameters exactly the way it inspects a route handler's — if that function declares query parameters, path parameters, headers, or further dependencies of its own, FastAPI resolves all of those from the incoming request before calling it.

For a request to a route with a dependency, the order is fixed: FastAPI receives the request, calls the dependency function with parameters extracted from that request, the dependency runs and returns a value, that value gets passed into the route handler as the declared parameter, and the handler runs. If the dependency used yield rather than return, FastAPI resumes it for cleanup after the response has already been sent.


Basic Dependency: Shared Query Parameters​

A dependency that extracts common pagination parameters and makes them available to any route that needs them:


from typing import Annotated

from fastapi import Depends, FastAPI, APIRouter



app = FastAPI()



async def common_pagination(skip: int = 0, limit: int = 20) -> dict:

    return {"skip": skip, "limit": limit}



@app.get("/items/")

async def read_items(pagination: Annotated[dict, Depends(common_pagination)]):

    return pagination



@app.get("/users/")

async def read_users(pagination: Annotated[dict, Depends(common_pagination)]):

    return pagination

Both routes share the exact same pagination logic — changing the rule, say, capping limit at 100, means changing one function, with every route using it benefiting automatically.

The Annotated syntax​

Annotated[dict, Depends(common_pagination)] is the modern, preferred syntax, introduced in FastAPI 0.95.0. It separates the type annotation (dict) from the dependency declaration (Depends(...)) in a way editors fully understand — autocomplete, type checking, and inline error detection all work correctly against it. The older form, pagination: dict = Depends(common_pagination), still works and behaves identically, but Annotated is what current official documentation recommends. Storing an Annotated dependency as a type alias removes repetition entirely when the same dependency shows up across many routes:


from typing import Annotated

from fastapi import Depends



CommonPagination = Annotated[dict, Depends(common_pagination)]



@app.get("/items/")

async def read_items(pagination: CommonPagination):

    return pagination



@app.get("/users/")

async def read_users(pagination: CommonPagination):

    return pagination

CommonPagination is a standard Python type alias, carrying the full type information and dependency declaration together under one reusable name.


Generator Dependencies: Resources with Cleanup​

When a dependency needs to acquire a resource before a route runs and release it afterward — a database session, a file handle, an HTTP client — yield replaces return, and FastAPI resumes the generator once the response has been sent:

db.py:


from sqlmodel import SQLModel, Session, create_engine



DATABASE_URL = "sqlite:///database.db"



engine = create_engine(

    DATABASE_URL,

    connect_args={"check_same_thread": False},

    echo=False,

)



def get_session():

    with Session(engine) as session:

        yield session  # FastAPI injects the session into the route handler

        # Session is closed when the with block exits

routers/tasks.py:


from typing import Annotated

from fastapi import APIRouter, Depends

from sqlmodel import Session, select

from db import get_session

from models.task import Task



router = APIRouter(prefix="/tasks", tags=["Tasks"])



SessionDep = Annotated[Session, Depends(get_session)]



@router.get("/")

def get_all_tasks(session: SessionDep):

    return session.exec(select(Task)).all()



@router.post("/", status_code=201)

def create_task(task: Task, session: SessionDep):

    session.add(task)

    session.commit()

    session.refresh(task)

    return task

with Session(engine) as session: guarantees the session closes whether the route handler returns normally or raises an exception — which is exactly why this generator-plus-with pattern is correct, and return Session(engine), which never closes anything, is not. For dependencies where cleanup needs to run even if an exception happens inside the dependency itself, an explicit try/finally covers that case directly:


def get_resource():

    resource = acquire_resource()

    try:

        yield resource

    finally:

        resource.close()  # Always runs, even if the route raised an exception

Classes as Dependencies​

A class can be used as a dependency directly — FastAPI calls its __init__ method the same way it calls any other callable, and injects the resulting instance. This is particularly useful when a dependency needs configurable parameters or more than one method:


from typing import Annotated

from fastapi import Depends, Query, APIRouter



router = APIRouter()



class PaginationParams:

    def __init__(

        self,

        skip: int = Query(default=0, ge=0),

        limit: int = Query(default=20, ge=1, le=100),

    ):

        self.skip = skip

        self.limit = limit



PaginationDep = Annotated[PaginationParams, Depends(PaginationParams)]



@router.get("/items/")

def read_items(pagination: PaginationDep):

    return {"skip": pagination.skip, "limit": pagination.limit}

Depends(PaginationParams) — note, no parentheses after PaginationParams. FastAPI receives the class itself and calls it with the parameters resolved from the request, producing a PaginationParams instance with skip and limit already populated from the query string. Classes are also a natural fit for dependencies that need internal state or helper methods of their own:


class TaskService:

    def __init__(self, session: Annotated[Session, Depends(get_session)]):

        self.session = session



    def get_by_id(self, task_id: int) -> Task:

        task = self.session.get(Task, task_id)

        if not task:

            raise HTTPException(status_code=404, detail="Task not found")

        return task



TaskServiceDep = Annotated[TaskService, Depends(TaskService)]



@router.get("/{task_id}")

def get_task(task_id: int, service: TaskServiceDep):

    return service.get_by_id(task_id)

TaskService declares its own dependency, get_session, right inside __init__ — FastAPI resolves that full chain automatically, with no extra wiring needed anywhere else.


Nested Dependencies​

Dependencies can depend on other dependencies, and FastAPI resolves the entire tree, calling each one in the correct order before the route handler runs:


from typing import Annotated

from fastapi import Depends, HTTPException, Header, APIRouter

from sqlmodel import Session, select

from models.user import User



router = APIRouter()



# Layer 1 — extract and decode the token

def get_token(authorization: str = Header(...)) -> str:

    if not authorization.startswith("Bearer "):

        raise HTTPException(status_code=401, detail="Invalid token format")

    return authorization.removeprefix("Bearer ")



# Layer 2 — use the token to look up the user (depends on Layer 1)

def get_current_user(

    token: Annotated[str, Depends(get_token)],

    session: Annotated[Session, Depends(get_session)],

) -> User:

    user = session.exec(select(User).where(User.username == token)).first()

    if not user:

        raise HTTPException(status_code=401, detail="User not found")

    return user



# Layer 3 — require an active user (depends on Layer 2)

def require_active_user(

    user: Annotated[User, Depends(get_current_user)],

) -> User:

    if not user.is_active:

        raise HTTPException(status_code=403, detail="Account is disabled")

    return user



CurrentUser = Annotated[User, Depends(require_active_user)]



@router.get("/me")

def get_profile(user: CurrentUser):

    return {"username": user.username, "email": user.email}

FastAPI resolves this as get_token → get_current_user → require_active_user → route handler, with each layer receiving the output of the one below it.

Dependency caching within a request​

If the same dependency is required by more than one dependency in the same request, FastAPI calls it exactly once and reuses the result — if both get_current_user and a separate permissions dependency each depend on get_token, get_token still only runs once per request. This caching applies within a single request only; across separate requests, each call is fully independent. Depends(fn, use_cache=False) opts a specific dependency out of this caching, forcing it to run fresh every time it's required within the same request.


Parameterized Dependency Factories​

When the same logic needs to vary by a parameter — different roles, different permission levels — a factory function that returns a dependency covers it:


from typing import Annotated, Callable

from fastapi import Depends, HTTPException

from models.user import User



def require_role(required_role: str) -> Callable:

    def role_guard(user: Annotated[User, Depends(get_current_user)]) -> User:

        if user.role != required_role:

            raise HTTPException(

                status_code=403,

                detail=f"Role '{required_role}' required",

            )

        return user

    return role_guard



@router.get("/admin/users", dependencies=[Depends(require_role("admin"))])

def list_users(session: Annotated[Session, Depends(get_session)]):

    return session.exec(select(User)).all()



@router.get("/reports", dependencies=[Depends(require_role("editor"))])

def get_reports():

    return {"reports": []}

require_role("admin") runs at route definition time and returns role_guard — a new function FastAPI calls at request time — with required_role captured in its closure. A single implementation like this one produces any number of distinct role guards.


Route-Level vs Router-Level vs Global Dependencies​

Dependencies apply at three scopes, from narrowest to widest.

Route-level, applied to one specific endpoint:


@router.get("/secure", dependencies=[Depends(require_active_user)])

def secure_endpoint():

    return {"message": "Access granted"}

dependencies=[...] on the route decorator runs the dependency purely as a guard — it has to pass, but its return value is never injected into the handler. This fits cases where the side effect (validation, raising 401/403) is what matters, not the value returned.

Router-level, applied to every route on a specific router:


from fastapi import APIRouter, Depends



protected_router = APIRouter(

    prefix="/admin",

    tags=["Admin"],

    dependencies=[Depends(require_role("admin"))],

)



@protected_router.get("/users")

def list_users():

    ...  # require_role("admin") runs before this for every route on the router



@protected_router.delete("/users/{user_id}")

def delete_user(user_id: int):

    ...  # require_role("admin") runs here too — automatically

Every route added to protected_router runs the declared dependency automatically — the cleanest way to protect an entire group of admin or internal routes without decorating each one individually.

Global, applied to every route in the application:


from fastapi import FastAPI, Depends



app = FastAPI(dependencies=[Depends(verify_api_key)])

verify_api_key runs before every single route handler in the application — the right scope for cross-cutting concerns like API key validation, request logging, or universal rate limiting.


Overriding Dependencies for Testing​

app.dependency_overrides swaps a dependency for a test double for the duration of a test — the mechanism for substituting a real database session with an in-memory test session, or replacing get_current_user with a hardcoded mock user:


from fastapi.testclient import TestClient

from main import app

from db import get_session

from core.dependencies import get_current_user

from models.user import User



client = TestClient(app)



def override_get_session():

    ...  # yields a test session connected to sqlite://



def override_get_current_user():

    return User(id=1, username="testuser", role="user", is_active=True)



def test_get_profile():

    app.dependency_overrides[get_session] = override_get_session

    app.dependency_overrides[get_current_user] = override_get_current_user



    response = client.get("/me")

    assert response.status_code == 200

    assert response.json()["username"] == "testuser"



    app.dependency_overrides.clear()

app.dependency_overrides is a dictionary keyed by the original dependency function — FastAPI checks it before calling any dependency, and calls the override instead if that function is present as a key. Clearing the dictionary after each test, or in a fixture's teardown, prevents an override from leaking into a later test that never asked for it.


How Dependencies Appear in Swagger UI​

FastAPI reads every parameter declared across a route's full dependency chain and includes them in the generated OpenAPI schema. A dependency reading an Authorization header causes that header to show up as a required input in Swagger UI for every route using it, automatically, with nothing configured by hand for it to appear there — query parameters, headers, and request bodies declared inside a dependency show up alongside whatever the route handler declares directly.


Dependency Scopes: Quick Reference​

Where declaredScopeSyntaxRoute function signatureThat one routeparam: Annotated[T, Depends(fn)]Route decoratorThat one route (guard only)@router.get("/", dependencies=[Depends(fn)])Router constructorAll routes on that routerAPIRouter(dependencies=[Depends(fn)])App constructorEvery route in the appFastAPI(dependencies=[Depends(fn)])


Common Mistakes to Avoid​

Calling the dependency function directly inside Depends() — Depends(get_session()) — calls get_session immediately at import time and passes its return value into Depends, producing one single session shared across the entire application rather than a fresh one per request. Depends(get_session), without the parentheses, passes the function itself, and FastAPI calls it fresh for every request — the parentheses should never appear directly after the function name inside Depends. Using return instead of yield in a cleanup dependency, as covered earlier, leaves the resource open indefinitely. Forgetting to clear dependency_overrides between tests lets one test's override leak silently into the next one, unless app.dependency_overrides.clear() runs in a teardown step. Applying a guard through dependencies=[] when the route handler actually needs the dependency's return value discards that value entirely — declaring it in the function signature instead (user: CurrentUser) is what's needed whenever the handler uses the result, not just whenever it needs the check to pass. Nesting a blocking, synchronous dependency inside an async def route is a subtler mistake: a plain def dependency called from an async def route runs correctly in a thread pool, but a dependency declared async def that internally calls something blocking — time.sleep, a synchronous database driver — blocks the entire event loop instead. Matching async/def to whether a dependency performs actual async I/O or blocking I/O is what avoids this.


Building the Full Authentication Chain​

Putting every layer covered above together into one shared module, core/deps.py:


from typing import Annotated

from fastapi import Depends, HTTPException, Header

from sqlmodel import Session, select

from db import get_session

from models.user import User



SessionDep = Annotated[Session, Depends(get_session)]



def get_token(authorization: str = Header(...)) -> str:

    if not authorization.startswith("Bearer "):

        raise HTTPException(status_code=401, detail="Invalid token format")

    return authorization.removeprefix("Bearer ")



def get_current_user(

    token: Annotated[str, Depends(get_token)],

    session: SessionDep,

) -> User:

    # In a real application, this decodes the JWT to extract the username

    user = session.exec(select(User).where(User.username == token)).first()

    if not user:

        raise HTTPException(status_code=401, detail="User not found")

    return user



def require_active_user(

    user: Annotated[User, Depends(get_current_user)],

) -> User:

    if not user.is_active:

        raise HTTPException(status_code=403, detail="Account is disabled")

    return user



CurrentUser = Annotated[User, Depends(require_active_user)]



def require_role(required_role: str):

    def role_guard(user: CurrentUser) -> User:

        if user.role != required_role:

            raise HTTPException(status_code=403, detail=f"Role '{required_role}' required")

        return user

    return role_guard

SessionDep and CurrentUser are the two aliases every other router imports going forward, so the full chain — token extraction, user lookup, active-account check — never needs re-declaring anywhere else. Applying require_role("admin") at the router level protects an entire group of admin routes in one place:


from fastapi import APIRouter, Depends

from sqlmodel import select

from core.deps import require_role, SessionDep

from models.user import User



admin_router = APIRouter(

    prefix="/admin",

    tags=["Admin"],

    dependencies=[Depends(require_role("admin"))],

)



@admin_router.get("/users")

def list_users(session: SessionDep):

    return session.exec(select(User)).all()

Every route added to admin_router from this point on requires a valid token, an active account, and the "admin" role — all three enforced automatically, before any route-specific code runs, with nothing repeated per route.

Key Takeaways​

Depends() turns shared logic — pagination, database sessions, authentication — into a function or class FastAPI resolves automatically before a route handler runs, with the Annotated syntax as the current recommended way to declare it and a yield-based generator as the correct pattern for anything needing cleanup afterward. Dependencies can nest arbitrarily deep, with FastAPI resolving the full chain in order and caching any dependency shared across multiple branches of that chain within a single request. Scope — route, router, or app-wide — controls how broadly a dependency applies without needing to be repeated, and dependency_overrides is what makes any of this testable, by substituting a real dependency for a controlled stand-in for the duration of a test and nothing beyond it.

Frequently Asked Questions​

What is dependency injection in FastAPI?

Dependency injection is a design pattern where a route handler declares what it needs — a database session, a verified user, pagination parameters — and FastAPI resolves and provides those things automatically before the handler runs. Instead of duplicating shared logic inside every route or calling helper functions manually, you declare dependencies once and FastAPI calls them, injects their return values, and handles cleanup after the request.

What does Depends() do in FastAPI?

Depends(some_function) tells FastAPI to call some_function before the route handler runs and inject its return value into the parameter where Depends() is declared. FastAPI inspects the dependency function's own parameters and resolves them from the incoming request — query parameters, headers, path parameters, and other dependencies — before calling the function. The route handler receives the fully resolved result.

What is the difference between Depends(fn) and Depends(fn())?

Depends(fn) passes the function itself to FastAPI, which calls it fresh for every request. Depends(fn()) calls the function immediately at import time and passes its return value to Depends — meaning a single result is shared across the entire application for its entire lifetime. For resources like database sessions that must be created per request, Depends(fn()) is a critical bug. Always pass the function reference without parentheses inside Depends.

What is the Annotated syntax for FastAPI dependencies and why is it recommended?

The Annotated syntax wraps the type and the Depends declaration together: param: Annotated[Session, Depends(get_session)]. It is the preferred form since FastAPI 0.95.0 because it separates the type annotation from the dependency declaration in a way editors understand fully, providing correct autocomplete, type checking, and inline error detection. The older form param: Session = Depends(get_session) still works but Annotated is what the official documentation now recommends.

How do I create a reusable dependency alias in FastAPI?

Assign the Annotated type to a variable: SessionDep = Annotated[Session, Depends(get_session)]. Then use that alias as the type annotation in any route that needs the dependency: def create_task(session: SessionDep). The alias carries the full type and dependency declaration in one reusable name. When the dependency changes, updating the alias updates every route that uses it.

What is a generator dependency in FastAPI and when should I use it?

A generator dependency uses yield instead of return. FastAPI calls the function, receives the yielded value, injects it into the route handler, and then resumes the generator after the response is sent to handle cleanup. Use generator dependencies for any resource that must be opened before the request and closed after it — database sessions, file handles, HTTP clients. The with Session(engine) as session: yield session pattern guarantees the session is closed whether the handler succeeds or raises an exception.

What is the difference between return and yield in a FastAPI dependency?

A dependency that uses return gives FastAPI the value and is done — no cleanup occurs after the request. A dependency that uses yield gives FastAPI the value and then pauses. After the route handler returns and the response is sent, FastAPI resumes the generator after the yield, allowing cleanup code to run. For resources like database sessions that must be closed after each request, yield is mandatory. Using return means cleanup never happens.

How do I guarantee cleanup in a FastAPI dependency even if an exception occurs?

Wrap the yield in a try/finally block inside the dependency function. Code in the finally block runs regardless of whether the route handler raised an exception: resource = acquire_resource() then try: yield resource then finally: resource.close(). The with statement achieves the same guarantee for context managers — with Session(engine) as session: yield session closes the session in all cases.

How do I use a class as a FastAPI dependency?

Pass the class itself to Depends without parentheses: Depends(PaginationParams). FastAPI calls the class constructor with parameters resolved from the request — query parameters, headers, other dependencies declared in __init__ — and injects the resulting instance into the route handler. Classes are useful when a dependency needs configurable parameters, multiple methods, or internal state that a plain function cannot hold cleanly.

What are nested dependencies in FastAPI?

Nested dependencies are dependencies that declare their own dependencies. FastAPI resolves the entire tree automatically, calling each function in the correct order before the route handler runs. For example, require_active_user depends on get_current_user, which depends on get_token and get_session. FastAPI resolves get_token and get_session first, passes their results to get_current_user, then passes that result to require_active_user, then calls the route handler.

Does FastAPI call the same dependency multiple times if several dependencies require it?

No. By default, FastAPI caches dependency results within a single request. If get_token is required by both get_current_user and a separate permissions dependency in the same request, get_token is called only once and its result is reused. This caching applies within one request only — across different requests, each call is independent. To force a dependency to run fresh every time it is required within the same request, use Depends(fn, use_cache=False).

What is a dependency factory in FastAPI?

A dependency factory is a function that accepts configuration parameters and returns a dependency function. This allows the same logic to be applied with different settings: def require_role(required_role: str): def role_guard(user: ...): ... return role_guard. Calling require_role('admin') returns a dependency that checks for the admin role, while require_role('editor') returns one that checks for the editor role. The factory is called at route definition time; the returned function is called at request time.

What is the difference between declaring a dependency in the function signature versus in dependencies=[]?

Declaring a dependency in the function signature — user: Annotated[User, Depends(get_current_user)] — runs the dependency and injects its return value into the handler so the handler can use it. Declaring it in the route decorator — dependencies=[Depends(require_active_user)] — runs the dependency for its side effects only, such as raising 401 or 403, but discards the return value. Use the function signature when the handler needs the result. Use dependencies=[] when only the guard behaviour is needed.

How do I apply a dependency to all routes on a FastAPI router?

Pass the dependency in the APIRouter constructor: APIRouter(prefix='/admin', dependencies=[Depends(require_role('admin'))]). Every route added to that router automatically runs the declared dependency before its handler executes. This is the correct approach for protecting an entire group of routes — admin endpoints, internal APIs — without decorating each route individually.

How do I apply a dependency to every route in a FastAPI application?

Pass the dependency in the FastAPI constructor: app = FastAPI(dependencies=[Depends(verify_api_key)]). The dependency runs before every single route handler in the application. This is appropriate for cross-cutting concerns that must apply universally, such as API key validation, request logging, or global rate limiting.

How do I override a FastAPI dependency in tests?

Use app.dependency_overrides — a dictionary on the FastAPI instance that maps original dependency functions to replacement functions. Set app.dependency_overrides[get_session] = override_get_session before the test runs. FastAPI checks this dictionary before calling any dependency and calls the override instead of the original. Clear all overrides after each test with app.dependency_overrides.clear() to prevent them from leaking into subsequent tests.

Why do FastAPI dependencies appear automatically in Swagger UI?

FastAPI reads the parameters declared in every dependency in the chain and includes them in the OpenAPI schema. A dependency that reads an Authorization header causes that header to appear as a required input in Swagger UI for every route that uses the dependency, with no manual configuration. Query parameters, headers, and request bodies declared in dependencies are documented alongside those declared directly on the route handler.

What happens if I declare an async def dependency and call blocking code inside it?

A blocking call inside an async def dependency — time.sleep(), a synchronous database driver, synchronous file I/O — blocks the entire event loop for its duration. Every other concurrent request queues up and waits during that time. If the dependency performs blocking I/O, declare it as def instead of async def. FastAPI runs def dependencies in a thread pool executor, keeping the event loop free. Only use async def for dependencies that use await with genuinely async operations.

How does FastAPI dependency injection improve testability?

Because dependencies are declared as function parameters rather than created internally, they can be replaced with test doubles using app.dependency_overrides without modifying any application code. A route that depends on get_session can be tested with an in-memory SQLite session by overriding get_session. A route that depends on get_current_user can be tested with a hardcoded mock user by overriding get_current_user. The application code is unchanged — only the dependency resolution is redirected during the test.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Dependency Injection

Next

Reusable Components and Services