Request Data

FastAPI interview question · Easy difficulty

How do path parameters, query parameters, and request bodies differ in FastAPI?easy

Status
✓
Type
conceptual
Topic
request-data
Frequency
common
Tags
FastAPI, path parameters, query parameters, Pydantic, request body
Answer

Path parameters are values embedded in the URL and declared as typed function arguments matching the {name} segment in the route. Query parameters are extra function arguments not present in the path, and become optional once given a default value. Request bodies are declared as Pydantic BaseModel subclasses, which FastAPI parses and validates automatically, rejecting malformed requests before the endpoint function even runs.

Explanation

For a route like @app.get("/items/{item_id}") with def read_item(item_id: int), the type hint is enforced automatically — a request like /items/abc returns a 422 Unprocessable Entity with a clear validation error and no manual parsing needed. Function parameters not in the path, like def list_items(skip: int = 0, limit: int = 10, q: str | None = None), become query parameters called as /items/?skip=0&limit=5&q=phone; parameters without a default are required. For request bodies, a BaseModel subclass declares the expected JSON shape, and FastAPI parses the body into an instance of it, validating every field before the handler runs.

Follow-upWhat HTTP status code does FastAPI return when a path parameter fails type validation?
Follow-upHow does FastAPI decide whether a function argument is a path param, query param, or body field?
Follow-upWhy declare request bodies as Pydantic models instead of parsing raw JSON yourself?