FastAPI interview question · Most asked
How does FastAPI distinguish path, query and body parameters?
Summary
Parameters named in the path template are path parameters; simple-typed parameters not in the path are query parameters; parameters typed as Pydantic models are read from the JSON body.
Longer Answer
You can make the source explicit with Path(), Query(), Body(), Header(), Cookie() and Form(), usually via Annotated for metadata like validation constraints and descriptions. Optional query params have defaults (q: str | None = None). Lists from repeated query keys need Query(): tags: Annotated[list[str], Query()] = [].
Code Example
from typing import Annotated
from fastapi import FastAPI, Path, Query
from pydantic import BaseModel
app = FastAPI()
class ItemUpdate(BaseModel):
name: str
price: float
@app.put("/items/{item_id}")
async def update_item(
item_id: Annotated[int, Path(ge=1)],
item: ItemUpdate,
notify: Annotated[bool, Query()] = False,
):
return {"id": item_id, **item.model_dump(), "notify": notify}
Key Points
- Path template names → path params
- Scalars otherwise → query params
- Pydantic models → body
Annotated[int, Query(ge=1)]adds constraints
More most-asked FastAPI questions
- When should an endpoint be `async def` versus plain `def` in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- How does dependency injection with `Depends` work in FastAPI?
- How do you implement OAuth2 password flow with JWT in FastAPI?