Bird
0
0

Given this code snippet, what will be printed when a request is made to /items/42?

medium📝 component behavior Q13 of 15
FastAPI - Dependency Injection
Given this code snippet, what will be printed when a request is made to /items/42?
from fastapi import FastAPI, Depends

app = FastAPI()

def common_dep():
    print("Global dependency called")

@app.get("/items/{item_id}")
def read_item(item_id: int, dep=Depends(common_dep)):
    return {"item_id": item_id}
ANo output printed because common_dep is not global
BGlobal dependency called printed once per request
CGlobal dependency called printed twice per request
DSyntaxError due to missing global dependency
Step-by-Step Solution
Solution:
  1. Step 1: Check how common_dep is used

    common_dep is used as a route dependency only on the read_item function, not as a global dependency.
  2. Step 2: Understand when common_dep runs

    It runs only when the /items/{item_id} route is called, printing the message once per request to that route.
  3. Final Answer:

    Global dependency called printed once per request -> Option B
  4. Quick Check:

    Route dependency prints only when route is called, not global [OK]
Quick Trick: Route dependencies run per route, not global unless set globally [OK]
Common Mistakes:
MISTAKES
  • Assuming common_dep is global when it's route-specific
  • Expecting multiple prints per request
  • Confusing global and route dependencies

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes