Script Valley
FastAPI: Build Production Python APIs
Async Programming and DependenciesLesson 2.2

How FastAPI dependency injection works with Depends

Depends function, dependency declaration, shared logic, dependency chaining, dependency caching, use_cache parameter, function dependencies

Dependency Injection with Depends

FastAPI's Depends system lets you declare reusable logic โ€” database sessions, auth checks, pagination โ€” once and inject it into any route. Dependencies run before the route handler and can raise HTTPException to abort the request.

Basic dependency

from fastapi import Depends, FastAPI

app = FastAPI()

def get_pagination(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

@app.get("/items/")
def list_items(pagination: dict = Depends(get_pagination)):
    return pagination

FastAPI calls get_pagination, resolves its own parameters from the request, and injects the return value. The route handler never deals with skip or limit directly.

Chaining dependencies

def verify_token(token: str):
    if token != "secret":
        raise HTTPException(status_code=401, detail="Invalid token")
    return token

def get_current_user(token: str = Depends(verify_token)):
    return {"user": "alice", "token": token}

@app.get("/profile")
def profile(user: dict = Depends(get_current_user)):
    return user

FastAPI resolves the dependency tree automatically. get_current_user depends on verify_token, and the framework calls them in the right order.

Caching

By default, FastAPI calls a dependency once per request and caches the result. Pass use_cache=False to Depends if you need a fresh call every time it appears.

Up next

How to use class-based dependencies in FastAPI

Sign in to track progress

How FastAPI dependency injection works with Depends โ€” Async Programming and Dependencies โ€” FastAPI: Build Production Python APIs โ€” Script Valley โ€” Script Valley