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

How to use class-based dependencies in FastAPI

class as dependency, __call__ method, parameterized dependencies, dependency instances, stateful dependencies, reusable filters

Class-Based Dependencies

Any callable works as a FastAPI dependency — including class instances. Classes are useful when a dependency needs configuration or when you want to group related query parameters together.

Class with __call__

from fastapi import Depends, FastAPI

app = FastAPI()

class Pagination:
    def __init__(self, max_limit: int = 100):
        self.max_limit = max_limit

    def __call__(self, skip: int = 0, limit: int = 10) -> dict:
        limit = min(limit, self.max_limit)
        return {"skip": skip, "limit": limit}

pagination = Pagination(max_limit=50)

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

The pagination instance is created once. FastAPI calls its __call__ method on every request, resolving skip and limit from query parameters each time.

Using the class directly (without an instance)

class CommonParams:
    def __init__(self, q: str | None = None, skip: int = 0, limit: int = 10):
        self.q = q
        self.skip = skip
        self.limit = limit

@app.get("/search/")
def search(params: CommonParams = Depends()):
    return {"q": params.q, "skip": params.skip}

Passing Depends() without arguments — and typing the parameter with the class — tells FastAPI to instantiate the class itself as the dependency. FastAPI resolves constructor arguments from the request the same way it does for function dependencies.

Class-based dependencies are ideal when multiple routes share the same parameter group and you want a typed object instead of a dict.

Up next

How to use yield dependencies for resource management in FastAPI

Sign in to track progress