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 {"number": num}
The dependency function get_number returns the integer 42. FastAPI injects this value into the endpoint parameter num. The endpoint returns a dictionary with key "number" and value 42.
Option A correctly defines a query parameter 'q' with type string. Option A lacks type annotation, so FastAPI treats 'q' as a path parameter which is missing. Option A uses wrong type (int) if expecting string. Option A references 'q' without defining it.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.post("/items") async def create_item(item: Item): return item
The Pydantic model Item requires both 'name' (string) and 'price' (float). The JSON only provides 'name', so validation fails because 'price' is missing.
from fastapi import FastAPI app = FastAPI() counter = 0 @app.get("/counter") async def get_counter(): global counter counter += 1 return {"count": counter}
The global variable counter starts at 0. Each call increments it by 1. The first call returns 1, the second call returns 2.
Dependency injection helps separate concerns by letting you provide components like database connections or services to endpoints cleanly. This makes code easier to test, maintain, and reuse. Other options are incorrect or misleading.