0
0
FastAPIframework~10 mins

Class-based dependencies in FastAPI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Class-based dependencies
Define class with __init__
Create instance per request
Call __call__ method
Return dependency data
Inject into path operation function
Use data in endpoint
FastAPI creates an instance of the class for each request, calls its __call__ method to get data, and injects that data into the endpoint.
Execution Sample
FastAPI
from fastapi import FastAPI, Depends
from typing import Optional

class QueryParams:
    def __init__(self, q: Optional[str] = None):
        self.q = q
    def __call__(self):
        return self.q

app = FastAPI()

@app.get("/items/")
async def read_items(q: str = Depends(QueryParams)):
    return {"q": q}
This code defines a class-based dependency that extracts a query parameter and injects it into the endpoint.
Execution Table
StepActionClass Instance StateMethod CalledReturned ValueEndpoint Output
1Request received with query ?q=helloNot createdNoneNoneNone
2FastAPI creates QueryParams instanceQueryParams(q='hello')__init__NoneNone
3FastAPI calls __call__ on instanceQueryParams(q='hello')__call__'hello'None
4Dependency injects 'hello' into read_itemsQueryParams(q='hello')NoneNoneNone
5read_items returns {'q': 'hello'}QueryParams(q='hello')NoneNone{"q": "hello"}
6Response sent to clientQueryParams(q='hello')NoneNone{"q": "hello"}
💡 Request handled and response sent; dependency instance discarded after request.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
qNone'hello''hello''hello'
QueryParams instanceNot createdCreated with q='hello'Same instanceDiscarded after request
Key Moments - 3 Insights
Why does FastAPI create a new class instance for each request?
FastAPI creates a new instance per request to keep data isolated and avoid sharing state between requests, as shown in execution_table step 2.
How does FastAPI get the value to inject into the endpoint?
FastAPI calls the __call__ method of the class instance to get the value, as seen in execution_table step 3.
What happens if the class does not have a __call__ method?
FastAPI will raise an error because it expects the dependency to be callable; this is implied by the flow where __call__ is invoked.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3. What method does FastAPI call on the class instance?
A__call__
B__init__
Cread_items
DDepends
💡 Hint
Check the 'Method Called' column at step 3 in the execution_table.
At which step does FastAPI inject the dependency value into the endpoint function?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column describing injection in the execution_table.
If the query parameter q was missing, what would be the value of q after step 3?
A'hello'
BNone
C'' (empty string)
DError
💡 Hint
Refer to variable_tracker for q's initial and after step 3 values.
Concept Snapshot
Class-based dependencies in FastAPI:
- Define a class with __init__ to accept parameters.
- Implement __call__ to return the dependency value.
- FastAPI creates a new instance per request.
- Calls __call__ to get data.
- Injects data into endpoint parameters via Depends().
Full Transcript
In FastAPI, class-based dependencies let you organize dependency logic inside a class. When a request comes in, FastAPI creates a new instance of your class, passing query or other parameters to __init__. Then it calls the __call__ method on that instance to get the value to inject into your endpoint function. This keeps each request's data separate and clean. The example shows a class QueryParams that reads a query parameter q. FastAPI creates an instance with q's value, calls __call__ to return q, and injects it into the read_items endpoint. After the request, the instance is discarded. This flow helps keep your code organized and reusable.