Consider this FastAPI code snippet:
from fastapi import FastAPI, Depends
app = FastAPI()
def get_query():
return "query_value"
@app.get("/items")
async def read_items(q: str = Depends(get_query)):
return {"q": q}What will be the JSON response when calling /items?
from fastapi import FastAPI, Depends app = FastAPI() def get_query(): return "query_value" @app.get("/items") async def read_items(q: str = Depends(get_query)): return {"q": q}
Think about what the Depends function does when used as a default value.
The Depends function calls the dependency function get_query and uses its return value as the parameter q. So the endpoint returns {"q": "query_value"}.
Given this FastAPI code:
from fastapi import Depends, FastAPI
app = FastAPI()
def get_user():
return {"name": "Alice"}
@app.get("/profile")
async def profile(user: dict = Depends(get_user)):
return userWhat will be the output JSON when calling /profile?
from fastapi import Depends, FastAPI app = FastAPI() def get_user(): return {"name": "Alice"} @app.get("/profile") async def profile(user: dict = Depends(get_user)): return user
Check what the dependency function returns and how it is used in the endpoint.
The dependency get_user returns a dictionary with key "name" and value "Alice". The endpoint returns this dictionary directly.
Identify which code snippet will cause a syntax error when using Depends in FastAPI.
Look carefully at the function parameter syntax.
Option A is missing the equals sign (=) between the parameter name and the default value, causing a syntax error.
Examine this code:
from fastapi import FastAPI, Depends
app = FastAPI()
def get_number():
return 42
@app.get("/number")
async def read_number(num: int = Depends(get_number)):
return {"num": num + 1}When calling /number, a runtime error occurs. Why?
from fastapi import FastAPI, Depends app = FastAPI() def get_number(): return 42 @app.get("/number") async def read_number(num: int = Depends(get_number)): return {"num": num + 1}
Consider the type returned by the dependency and how it is used.
The dependency returns 42 (int). The endpoint adds 1 to it, resulting in 43. No error occurs.
Choose the most accurate description of the Depends function behavior in FastAPI.
Think about how dependencies are executed and their scope.
Depends calls the dependency function for each request and injects its result. It does not cache globally, does not require async, and does not convert return values to strings.