Bird
0
0

Given the code below, what will be the output when accessing /users/42?

medium📝 Predict Output Q4 of 15
FastAPI - Dependency Injection
Given the code below, what will be the output when accessing /users/42?
from fastapi import FastAPI, Depends

app = FastAPI()

def get_user(user_id: int):
    return {"user_id": user_id, "name": "Alice"}

@app.get("/users/{user_id}")
def read_user(user_id: int, user: dict = Depends(get_user)):
    return user
A{"user_id": 42, "name": "Alice"}
BError: missing user_id parameter in get_user
C{"user": {"user_id": 42, "name": "Alice"}}
DError: Depends cannot pass path parameters automatically
Step-by-Step Solution
Solution:
  1. Step 1: Analyze get_user dependency parameters

    get_user expects a user_id parameter, but FastAPI cannot automatically pass path parameters to dependencies without explicit declaration.
  2. Step 2: Understand dependency parameter injection

    Depends does not automatically forward path parameters to dependency functions unless declared with matching parameters or using Depends with parameters.
  3. Final Answer:

    Error: missing user_id parameter in get_user -> Option B
  4. Quick Check:

    Dependency parameters must match or be provided [OK]
Quick Trick: Dependencies need explicit parameters to receive path values [OK]
Common Mistakes:
MISTAKES
  • Assuming dependencies get path params automatically
  • Not matching dependency function parameters
  • Expecting nested dict output without code support

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes