Difficulty: Intermediate
How do you add advanced validation to query parameters, path parameters, and request bodies in FastAPI?
FastAPI provides `Query()`, `Path()`, `Body()`, and `Field()` classes for fine-grained validation beyond basic type hints.
Query() - Validates query parameters with min/max length, regex patterns, greater-than/less-than constraints. Path() - Same validation for path parameters, always required. Body() - Extracts and validates individual fields from the request body. Field() - Used inside Pydantic models for per-field validation.
All accept: - `min_length` / `max_length` (strings) - `ge`, `gt`, `le`, `lt` (numbers) - `pattern` (regex) - `title`, `description`, `examples` (OpenAPI docs) - `alias` (alternative field name)
These constraints appear in the generated OpenAPI schema and Swagger UI.
from fastapi import FastAPI, Query, Path, Body
from pydantic import BaseModel, Field
from typing import Annotated
app = FastAPI()
class Product(BaseModel):
name: str = Field(min_length=1, max_length=100, examples=["Laptop"])
price: float = Field(gt=0, description="Price must be positive")
category: str = Field(pattern=r"^[a-z-]+quot;, description="Lowercase slug")
@app.get("/search")
def search(
q: Annotated[str, Query(min_length=2, max_length=50, description="Search term")] = "",
page: Annotated[int, Query(ge=1, le=1000)] = 1,
size: Annotated[int, Query(ge=10, le=100)] = 20,
):
return {"q": q, "page": page, "size": size}
@app.get("/items/{item_id}")
def get_item(
item_id: Annotated[int, Path(gt=0, title="The ID of the item to get")]
):
return {"item_id": item_id}
Query, Path, Body, Field, validation constraints