Consider this FastAPI dependency that takes a parameter and returns a greeting message. What will be the response when accessing /hello?name=Alice?
from fastapi import FastAPI, Depends app = FastAPI() def greet(name: str): return f"Hello, {name}!" @app.get("/hello") async def hello(message: str = Depends(greet)): return {"message": message}
Think about how the Depends function injects the parameter from the query string.
The dependency greet takes the query parameter name. FastAPI automatically passes the query parameter name=Alice to greet. So the returned message is "Hello, Alice!".
Choose the correct way to define a dependency function that takes an optional parameter lang with default value "en".
Remember to use FastAPI's Query for default query parameters in dependencies.
Option C uses Query("en") to set a default query parameter value for lang. Option C sets a Python default but does not integrate with FastAPI's query system. Option C lacks FastAPI parameter declaration. Option C misuses Depends.
Examine the code below. Why does calling /items cause a runtime error?
from fastapi import FastAPI, Depends app = FastAPI() def get_multiplier(factor: int): return lambda x: x * factor @app.get("/items") async def read_items(multiplier = Depends(get_multiplier)): return {"result": multiplier(5)}
Think about how FastAPI injects parameters into dependencies.
The dependency function get_multiplier requires a parameter factor, but FastAPI does not know how to provide it automatically. This causes a runtime error because the dependency cannot be resolved.
Which statement best describes how FastAPI resolves dependencies with parameters that have default values?
Think about how query parameters with defaults behave in FastAPI.
FastAPI uses the default value for dependency parameters if the client does not provide them in the request. This allows optional parameters with defaults.
Given the following code, what is the JSON response when accessing /compute?value=3?
from fastapi import FastAPI, Depends, Query app = FastAPI() def double(value: int = Query(...)): return value * 2 def add_five(number: int = Depends(double)): return number + 5 @app.get("/compute") async def compute(result: int = Depends(add_five)): return {"result": result}
Trace the dependency calls and their returned values step-by-step.
The query parameter value=3 is passed to double, which returns 6. Then add_five receives 6 and returns 11. The endpoint returns {"result": 11}.