Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

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:

ASP.NET Core developers often ask where validation attributes went. In Python, validation usually lives in Pydantic model fields and validators.