Bird
Raised Fist0
FastAPIframework~20 mins

Class-based dependencies in FastAPI - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Class-based Dependency Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this FastAPI class-based dependency?
Consider this FastAPI dependency class and endpoint. What will be the JSON response when accessing /items/42?
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

class ItemDependency:
    def __init__(self, item_id: int):
        self.item_id = item_id

    def get_item(self):
        return {"item_id": self.item_id, "name": f"Item {self.item_id}"}

@app.get("/items/{item_id}")
async def read_item(dep: ItemDependency = Depends(ItemDependency)):
    return dep.get_item()
A{"item_id": "42", "name": "Item 42"}
BTypeError: __init__() missing 1 required positional argument: 'item_id'
C{"item_id": 42}
D{"item_id": 42, "name": "Item 42"}
Attempts:
2 left
💡 Hint
Think about how FastAPI injects path parameters into class dependencies.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a class-based dependency with a __call__ method in FastAPI?
Select the code snippet that correctly implements a class-based dependency with a __call__ method that accepts a path parameter user_id.
A
class UserDependency:
    def __call__(self, user_id: str):
        return {"user_id": int(user_id)}

@app.get("/users/{user_id}")
async def get_user(dep: UserDependency = Depends(UserDependency)):
    return dep
B
class UserDependency:
    def __call__(self):
        return {"user_id": user_id}

@app.get("/users/{user_id}")
async def get_user(dep: UserDependency = Depends(UserDependency)):
    return dep
C
class UserDependency:
    def __init__(self, user_id: int):
        self.user_id = user_id

@app.get("/users/{user_id}")
async def get_user(dep: UserDependency = Depends(UserDependency)):
    return {"user_id": dep.user_id}
D
class UserDependency:
    def __call__(self, user_id: int):
        return {"user_id": user_id}

@app.get("/users/{user_id}")
async def get_user(dep: UserDependency = Depends(UserDependency)):
    return dep
Attempts:
2 left
💡 Hint
The __call__ method must accept the parameter and return the expected data.
🔧 Debug
advanced
2:00remaining
Why does this class-based dependency raise a runtime error?
Examine the code below. When calling /orders/5, it raises an error. What is the cause?
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

class OrderDependency:
    def __init__(self, order_id: int):
        self.order_id = order_id

    def __call__(self):
        return {"order_id": self.order_id}

@app.get("/orders/{order_id}")
async def get_order(dep: OrderDependency = Depends(OrderDependency)):
    return dep()
AThe endpoint returns the class instance instead of calling it, causing a TypeError.
BThe __call__ method is missing the 'order_id' parameter, causing a runtime error.
CFastAPI cannot pass 'order_id' to the __init__ method automatically, causing a TypeError.
DThe Depends function is used incorrectly without parentheses, causing a syntax error.
Attempts:
2 left
💡 Hint
Check how FastAPI injects parameters into class dependencies.
state_output
advanced
2:00remaining
What is the value of dep.value after this request?
Given the class-based dependency below, what will be the value of dep.value after a GET request to /calc/10?
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

class Calculator:
    def __init__(self, number: int):
        self.value = number * 2

@app.get("/calc/{number}")
async def calculate(dep: Calculator = Depends(Calculator)):
    return {"result": dep.value}
ATypeError: __init__() missing 1 required positional argument: 'number'
B20
C10
D0
Attempts:
2 left
💡 Hint
How does FastAPI pass path parameters to class constructors?
🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI class-based dependencies is TRUE?
Select the correct statement about how FastAPI handles class-based dependencies with parameters.
ATo receive parameters, a class-based dependency should implement a __call__ method with parameters matching the route parameters.
BFastAPI automatically injects path and query parameters into the __init__ constructor of dependency classes without extra configuration.
CClass-based dependencies cannot access request data unless explicitly passed via constructor parameters.
DUsing class-based dependencies disables FastAPI's automatic validation of parameters.
Attempts:
2 left
💡 Hint
Think about how FastAPI calls class dependencies to inject parameters.

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