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]}Interview question
What is the primary benefit of using a class as a dependency in FastAPI?
- a.To implement authentication and authorization logic for API routes.
- b.To group logically related request parameters for reuse across multiple endpoints.Correct
- c.To define custom data models for request bodies or responses.
- d.To automatically convert complex JSON payloads into Python objects.
Why? this is the answer
The card emphasizes that class dependencies are used to bundle related request parameters, like for pagination, to avoid duplication and improve code structure across multiple endpoints. Options A and C describe the use of Pydantic models for data validation and serialization, which is a different FastAPI feature, while option A refers to authentication, another distinct use case for dependencies.
Just read this? Test yourself on what you have been reading.
Read the original → fastapi.tiangolo.com
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.
See open roles