Bird
0
0

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

medium📝 component behavior Q13 of 15
FastAPI - Dependency Injection
Given the code below, what will be the output when accessing /items/42?
from fastapi import FastAPI, Depends

app = FastAPI()

def common_dep():
    return "shared value"

@app.get('/items/{item_id}')
def read_item(item_id: int, value: str = Depends(common_dep)):
    return {"item_id": item_id, "value": value}
AError: Missing required parameter 'value'
B{"item_id": 42, "value": 42}
C{"item_id": 42, "value": null}
D{"item_id": 42, "value": "shared value"}
Step-by-Step Solution
Solution:
  1. Step 1: Understand dependency injection

    The function common_dep returns the string "shared value". FastAPI injects this into the value parameter via Depends(common_dep).
  2. Step 2: Check the returned JSON

    The route returns a dictionary with item_id from the path and value from the dependency. So the output will be {"item_id": 42, "value": "shared value"}.
  3. Final Answer:

    {"item_id": 42, "value": "shared value"} -> Option D
  4. Quick Check:

    Dependency injects "shared value" [OK]
Quick Trick: Depends injects return value as parameter [OK]
Common Mistakes:
MISTAKES
  • Assuming dependency returns item_id
  • Expecting error due to missing parameter
  • Thinking value will be null without explicit call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes