Bird
0
0

How can you modify this class-based dependency to accept a dynamic parameter from the request query?

hard🚀 Application Q15 of 15
FastAPI - Dependency Injection
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.
AUse __init__(self, user_id: int = Query(...)) and import Query
BAdd user_id parameter to __call__ method instead
CPass user_id directly in Depends(UserInfo(user_id))
DUse global variable for user_id inside UserInfo
Step-by-Step Solution
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]
Quick Trick: Use Query in __init__ to get query params [OK]
Common Mistakes:
MISTAKES
  • Trying to pass parameters in __call__
  • Passing instance in Depends directly
  • Using global variables instead of parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes