tezvyn:

FastAPI: Using Classes as Dependencies

AI-drafted, machine-checkedSource: fastapi.tiangolo.combeginner
FastAPI: Using Classes as Dependencies

Bundle related request parameters into a class instead of repeating them in every endpoint. FastAPI automatically creates an instance for you, cleaning up your code. This is ideal for shared logic like pagination. The footgun: FastAPI injects into `__init__`.

WHY IT EXISTS When multiple API endpoints need the same set of parameters, like for pagination or filtering, repeating them in each function signature leads to code duplication. While a function returning a dictionary works, using a class provides better structure, type safety, and editor autocompletion.

THE MENTAL MODEL Think of a class dependency as a pre-configured 'toolkit' for your endpoint. Instead of asking for a hammer, a screwdriver, and a wrench individually (e.g., skip, limit, q), you ask for the 'pagination toolkit'. FastAPI assembles this toolkit for you by creating an instance of your class on each request.

HOW IT WORKS You define a standard Python class with an __init__ method. The parameters of this __init__ method are defined just like regular endpoint parameters (e.g., q: str | None = None). In your path operation function, you declare a parameter and type-hint it with your class, using Depends(). For each request, FastAPI will inspect the __init__ signature, resolve its parameters from the request (query, header, etc.), create an instance of your class, and pass that object to your endpoint.

WHEN TO USE IT Use a class dependency when a group of parameters are logically related and reused across multiple endpoints. This is a perfect pattern for implementing shared functionality like pagination (skip, limit), complex filtering, or common search criteria. It keeps your endpoint signatures clean and centralizes the parameter logic.

WHEN NOT TO USE IT For a single, simple dependency that is not shared across endpoints, a class is overkill. A direct parameter in the path operation function (e.g., q: str | None = None) is more direct and readable. Using a class for just one parameter adds unnecessary boilerplate code.

ONE CANONICAL EXAMPLE First, define a class to hold common query parameters. The __init__ method defines the dependencies FastAPI will resolve.

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

Next, use this class in an endpoint with Depends. FastAPI will create an instance of CommonQueryParams and pass it as the commons argument.

@app.get("/items/") async def read_items(commons: Annotated[CommonQueryParams, Depends()]): return {"query": commons.q, "items_slice": items[commons.skip : commons.skip + commons.limit]}

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.