Annotated validation style recommended in Pydantic v2.
Request Data Processing Flow
FastAPI intercepts incoming HTTP requests, extracts parameters from every part of the request, validates their types using Pydantic, and feeds the clean values directly into your route function.Validation happens before your function is ever called. If any input fails, FastAPI immediately returns a
422 Unprocessable Entity with a detailed error message explaining exactly what went wrong.Path Parameters
Path parameters are variables embedded directly inside the URL path. You define them using curly braces in the route, then add a matching function argument with a type annotation.- Define the variable in the path inside curly braces:
/employees/{employee_id}. - Annotate
employee_id: intin the function signature — if a user requests/employees/abc, FastAPI immediately returns422without you writing any checking code.
Validated Path Parameters
UsePath() with Annotated to enforce additional constraints:
Query Parameters
Any function parameter that is not part of the path is automatically treated as a query parameter. They appear after the? in the URL.
- Use
str | None = Nonefor optional parameters. - Provide a default value directly (e.g.,
limit: int = 10).
Validated Query Parameters
alias="dept" means clients send ?dept=Engineering but your parameter is named department in Python.
Request Bodies with Pydantic
When you need to send structured data — typically to create or update a resource — you use a request body withPOST, PUT, or PATCH. Define the shape using a Pydantic model.
- Reads the request body as JSON
- Validates it against
EmployeeCreate - Creates an
EmployeeCreateobject and injects it as theemployeeparameter
employee.model_dump() to get a standard Python dictionary from the validated model.
Recommended Annotated Style
In Pydantic v2, the preferred approach separates the type from the validation metadata:
Annotated is the recommended approach going forward.
Headers
You can read HTTP headers sent by clients using theHeader class. FastAPI automatically converts snake_case parameter names to kebab-case header names.
FastAPI maps
x_api_key (Python snake_case) to the X-API-Key header (HTTP kebab-case) automatically. You don’t need to do anything special.