Bird
Raised Fist0
FastAPIframework~10 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the main purpose of using class-based dependencies in FastAPI?
easy
A. To automatically generate HTML forms
B. To replace all route functions with classes
C. To group related dependency logic in one reusable place
D. To handle database connections only

Solution

  1. Step 1: Understand the role of class-based dependencies

    Class-based dependencies allow grouping related logic inside a class, making code cleaner and reusable.
  2. Step 2: Compare options with this purpose

    Only To group related dependency logic in one reusable place correctly describes grouping related logic; others describe unrelated features.
  3. Final Answer:

    To group related dependency logic in one reusable place -> Option C
  4. Quick Check:

    Class-based dependencies = Group logic [OK]
Hint: Class-based dependencies group logic inside a class [OK]
Common Mistakes:
  • Thinking class dependencies replace route functions
  • Assuming they auto-generate HTML
  • Believing they only handle databases
2. Which method must a class implement to be used as a dependency in FastAPI?
easy
A. __init__
B. __call__
C. dependency
D. run

Solution

  1. Step 1: Recall FastAPI dependency requirements

    FastAPI requires the class to be callable, which means it must implement the __call__ method.
  2. Step 2: Match method names to this requirement

    Only __call__ makes the class instance callable; __init__ is for initialization, others are invalid.
  3. Final Answer:

    __call__ -> Option B
  4. Quick Check:

    Callable class = __call__ method [OK]
Hint: Class must be callable via __call__ method [OK]
Common Mistakes:
  • Choosing __init__ instead of __call__
  • Using random method names like 'run'
  • Confusing dependency with method name
3. Given this class-based dependency, what will be the output when accessing the endpoint?
from fastapi import FastAPI, Depends

app = FastAPI()

class Greeting:
    def __init__(self, name: str = "Guest"):
        self.name = name
    def __call__(self):
        return f"Hello, {self.name}!"

@app.get("/hello")
async def hello(greet: str = Depends(Greeting)):
    return {"message": greet}
medium
A. {"message": "Hello!"}
B. {"message": "Hello, name!"}
C. TypeError at runtime
D. {"message": "Hello, Guest!"}

Solution

  1. Step 1: Analyze the Greeting class behavior

    The class sets name to "Guest" by default and __call__ returns "Hello, Guest!" string.
  2. Step 2: Understand dependency injection in endpoint

    Depends(Greeting) creates an instance with default name, so greet is "Hello, Guest!" string.
  3. Final Answer:

    {"message": "Hello, Guest!"} -> Option D
  4. Quick Check:

    Default name used = Hello, Guest! [OK]
Hint: Default parameter used if no argument passed [OK]
Common Mistakes:
  • Expecting 'name' literal instead of variable value
  • Assuming runtime error without cause
  • Ignoring default parameter in __init__
4. Identify the error in this class-based dependency usage:
class Counter:
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1

@app.get("/count")
async def get_count(counter: Counter = Depends(Counter)):
    counter.increment()
    return {"count": counter.count}
medium
A. count attribute should be a class variable
B. Counter class lacks a __call__ method
C. increment method should be async
D. Depends() cannot accept classes

Solution

  1. Step 1: Trace the dependency execution flow

    Depends(Counter) creates a new instance each request; self.count = 0, increment() sets to 1, returns {"count": 1}. Count resets every request.
  2. Step 2: Pinpoint the logical error

    self.count is an instance attribute (per-request); for persistent counting across requests, count must be a class attribute.
  3. Final Answer:

    count attribute should be a class variable -> Option A
  4. Quick Check:

    Instance attr = resets per request [OK]
Hint: Use class variables for shared state across requests [OK]
Common Mistakes:
  • Thinking Depends can't accept classes
  • Assuming async needed for increment
  • Confusing instance and class variables
5. How can you modify this class-based dependency to accept a dynamic parameter from the request query?
class UserInfo:
    def __init__(self, user_id: int):
        self.user_id = user_id
    def __call__(self):
        return f"User ID is {self.user_id}"

@app.get("/user")
async def user(info: str = Depends(UserInfo)):
    return {"info": info}

Choose the correct way to pass user_id from query parameters.
hard
A. Use __init__(self, user_id: int = Query(...)) and import Query
B. Add user_id parameter to __call__ method instead
C. Pass user_id directly in Depends(UserInfo(user_id))
D. Use global variable for user_id inside UserInfo

Solution

  1. Step 1: Understand how FastAPI injects parameters

    FastAPI injects parameters into __init__ if they have default values with Query or Body.
  2. Step 2: Use Query to declare user_id in __init__

    Adding user_id: int = Query(...) in __init__ allows FastAPI to get it from query parameters.
  3. Final Answer:

    Use __init__(self, user_id: int = Query(...)) and import Query -> Option A
  4. Quick Check:

    Query param in __init__ = dynamic dependency [OK]
Hint: Use Query in __init__ to get query params [OK]
Common Mistakes:
  • Trying to pass parameters in __call__
  • Passing instance in Depends directly
  • Using global variables instead of parameters