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

← All FastAPI questions