Bird
0
0

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

medium📝 component behavior Q4 of 15
FastAPI - Dependency Injection
Given the code below, what will be the output when accessing the /users/ endpoint?
from fastapi import FastAPI, Depends
app = FastAPI()
def get_user():
    return "Alice"
@app.get('/users/')
def read_user(user: str = Depends(get_user)):
    return {"user": user}
ARuntime error due to missing parameter
B{"user": "Alice"}
C{"user": null}
D{"user": "get_user"}
Step-by-Step Solution
Solution:
  1. Step 1: Understand dependency injection

    The Depends(get_user) calls get_user and injects its return value into user.
  2. Step 2: Check the returned value from get_user

    get_user returns the string "Alice", so the route returns {"user": "Alice"}.
  3. Final Answer:

    {"user": "Alice"} -> Option B
  4. Quick Check:

    Depends injects function return = "Alice" [OK]
Quick Trick: Depends injects the return value of the dependency function [OK]
Common Mistakes:
MISTAKES
  • Expecting the function name instead of its return value
  • Assuming null is injected if no parameter passed
  • Thinking a runtime error occurs without explicit call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes