Chapter 7: Request Binding and Validation
ASP.NET Core binds route values, query strings, headers, forms, and bodies. FastAPI does the same using function parameters, Annotated, and Pydantic models.
from typing import Annotated
from fastapi import Header, Query
from pydantic import BaseModel, Field
class RecipeSearch(BaseModel):
q: str | None = Field(default=None, max_length=100)
page: int = Field(default=1, ge=1)
page_size: int = Field(default=20, ge=1, le=100)
@router.get("")
def search_recipes(
filters: Annotated[RecipeSearch, Query()],
accept_language: Annotated[str | None, Header()] = None,
):
...
Python validation practices:
- Prefer Pydantic constraints over manual
ifchecks for shape validation. - Keep business rules in services or domain functions.
- Use
field_validatorandmodel_validatorfor validation that belongs to the data contract. - Return consistent error shapes. FastAPI gives a default
422validation response; decide whether to keep it or wrap it.
ASP.NET Core developers often ask where validation attributes went. In Python, validation usually lives in Pydantic model fields and validators.