Bird
0
0

Given this code, what will be the response when calling GET /items/42?

medium📝 component behavior Q4 of 15
FastAPI - Dependency Injection
Given this code, what will be the response when calling GET /items/42?
from fastapi import FastAPI, Depends

app = FastAPI()

class ItemDependency:
    async def __call__(self, item_id: int):
        return f"Item ID is {item_id}"

@app.get('/items/{item_id}')
async def read_item(dep: str = Depends(ItemDependency())):
    return {"message": dep}
A{"message": "Item ID is dep"}
B{"message": "Item ID is 42"}
CRuntime error due to missing parameter
D{"message": "42"}
Step-by-Step Solution
Solution:
  1. Step 1: Understand dependency injection with parameters

    ItemDependency's __call__ accepts item_id, which FastAPI injects from path parameter.
  2. Step 2: Analyze endpoint return

    The dependency returns 'Item ID is 42', which is returned in JSON message.
  3. Final Answer:

    {"message": "Item ID is 42"} -> Option B
  4. Quick Check:

    Dependency returns formatted string = B [OK]
Quick Trick: Dependencies can receive path params automatically [OK]
Common Mistakes:
MISTAKES
  • Assuming dependency returns parameter name instead of value
  • Expecting runtime error due to parameter
  • Confusing dependency return with raw parameter

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes