Bird
0
0

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

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

app = FastAPI(dependencies=[Depends(lambda: print('Global dep called'))])

@app.get('/users/{user_id}')
async def read_user(user_id: int):
    return {'user_id': user_id}
AGlobal dep called printed only once at startup
BNo output printed
CGlobal dep called printed once per request
DError because print cannot be a dependency
Step-by-Step Solution
Solution:
  1. Step 1: Understand when global dependencies run

    Global dependencies run before every request, so the print statement runs each time.
  2. Step 2: Confirm print output behavior

    Each request triggers the lambda, printing 'Global dep called' once per request.
  3. Final Answer:

    Global dep called printed once per request -> Option C
  4. Quick Check:

    Global dependency runs per request = print runs each time [OK]
Quick Trick: Global dependencies run before every request, so print runs each time [OK]
Common Mistakes:
MISTAKES
  • Thinking global dependencies run only once at startup
  • Assuming print cannot be used in dependencies
  • Expecting no output from print

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes