Skip to content

Request Validation: Pydantic Query/Body Models, Cookies, Headers, Custom Validators, Error Responses ​

"When a request contains invalid data, FastAPI internally raises a RequestValidationError. And it also includes a default exception handler for it." — FastAPI documentation, "Handling Errors", fastapi.tiangolo.com/tutorial/handling-errors

Summary: Every value a FastAPI endpoint receives comes from one of four places in the HTTP request: the path, the query string, the header block (cookies included) or the body (JSON, a URL-encoded form or a multipart form with files). The function signature says which place, the type and the constraints. Pydantic v2 then converts and validates every value, collects all failures, and FastAPI answers 422 Unprocessable Content before your code runs. This page covers the declarations themselves (Query, Body, Cookie, Header, Form, File, Pydantic models for each location), the validator hooks for rules a type cannot express (AfterValidator, BeforeValidator, field_validator, model_validator, computed_field), cookies going out (Set-Cookie with HttpOnly, Secure, SameSite), and the error responses coming back: the default 422 body, a RequestValidationError handler that emits RFC 9457 Problem Details, custom exception classes, and how every declaration shows up in the OpenAPI schema. Focus: optional and required query parameters and defaults, Annotated with Query() constraints (min_length, max_length, pattern, ge/gt/le/lt), alias, title, description, examples, deprecated, include_in_schema; the Pydantic model for query parameters with extra="forbid"; request bodies with Body(), nested models, multiple body parameters and embed=True; Field, aliases, model_dump(exclude_unset=True); path + query + body together; Cookie() and cookie models; Header(), underscore conversion (convert_underscores), duplicate headers, header models, the Authorization header; Form(), UploadFile and python-multipart; strict mode versus coercion, Enum, Literal, UUID and datetime parsing, type adapters; the 422 shape, RequestValidationError and Pydantic's ValidationError, @app.exception_handler, HTTPException, Problem Details (application/problem+json), the error response model and the responses parameter; a national postcode validator (the course's Indian PIN code exercise, generalised) with a checksum example; and what each declaration puts into the OpenAPI / JSON Schema. Learning goal: Declare every input of an endpoint so precisely that the function only ever sees clean, typed values; write custom validators at the right hook; set cookies that a browser will protect; return one documented error format for every failure; and know exactly which of these behaviours depend on the FastAPI version you run.

This page owns request validation in FastAPI: where each input comes from, the validation hooks, cookies and headers, and the error responses that validation produces. It does not re-teach its neighbours. The routing basics, path parameters, the first look at Query() and the default 422 are in FastAPI Fundamentals. Pydantic as a library (models, generics, settings, serialisation in depth) is in Typing & Pydantic v2. Validation that needs the database or another service belongs in a dependency: Dependency Injection. The general exception and response machinery (handlers for every error type, StreamingResponse, SSE) is in Exceptions & Responses. Separate create/read/update models per resource are treated fully in SQLAlchemy 2 & SQLModel. Verifying an Authorization: Bearer token is Authentication in FastAPI. Fixtures and dependency overrides are in Testing FastAPI. The HTTP design side (status codes, resources, idempotency keys) is REST API Design. Input validation as a security control is covered in OWASP API Security Top 10 (mass assignment, "BOPLA") and the API Security Hardening Checklist. The Go counterparts are net/http and JSON, XML, Struct Tags.

Facts below were checked against the FastAPI tutorial and advanced guide (query, body, cookie, header and form parameters and their models, request files, handling errors, response cookies, additional responses), the FastAPI release notes up to 0.165.0 (2026-11-18), the Pydantic 2.x documentation (validators, models, fields, aliases, serialisation, strict mode, conversion table, JSON Schema, type adapters, validation errors), the Starlette request/response docs, RFC 9457, RFC 6265, RFC 9110, RFC 7578, MDN's Set-Cookie reference, the python-multipart README, Laravel 13's validation/request/response docs and the go-playground/validator README. The page is written for Python 3.12+ with current FastAPI and Pydantic. The snippets, however, ran on the only interpreter on the build machine, CPython 3.9.6, so the snippet project pins the newest releases that still install there: FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, python-multipart 0.0.20, Uvicorn 0.39.0, httpx 0.28.1, pytest 8.4.2, plus eval-type-backport for str | None on 3.9. Every status code, error body and header marked "real" below is what that run printed. This chapter's surface changed a lot after 0.128.8: FastAPI 0.132.0 to 0.165.0 changed how parameter models combine, how null is treated in JSON bodies, which header names are accepted and how forms handle empty values. Each such change is dated to its release note where it matters and summarised in Version differences.

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why validate at the edge at allWhy it exists
Pydantic v1 to FastAPI 0.165, RFC 7807 to 9457Where it comes from
A before/after order APIPython
q: str | None = None vs q: strQuery parameters: optional, required, default
min_length, pattern, ge, ltQuery constraints
alias, title, examples, deprecatedParameter metadata
AfterValidator, BeforeValidatorAnnotated validators
Annotated[Filter, Query()], extra="forbid"Query parameter models
JSON body, Body(), embed=TrueRequest body models
Nested models, lists of modelsNested models
Field, aliases, model_dump(exclude_unset=True)Field, aliases and partial updates
field_validator, model_validator, computed_fieldModel validators
Path + query + body in one signatureMixing sources
Cookie(), cookie modelsReading cookies
Set-Cookie, HttpOnly, Secure, SameSiteSetting cookies
Header(), user_agent → User-Agent, repeated headersHeaders
Authorization: Bearer …The Authorization header
Form(), UploadFile, python-multipartForms and files
"5" → 5 or an error? Enum, Literal, UUID, datetimeCoercion, strict mode and special types
TypeAdapterType adapters
The 422 body, loc, typeThe 422 response
Replace the 422 with Problem DetailsRequestValidationError handler and RFC 9457
class OutOfStock(Exception) → 409Custom exception classes
responses={409: ...} in the docsError response models in OpenAPI
Indian PIN code, UK and Iranian postcodes, LuhnValidating a national postcode
What /openapi.json shows for each declarationOpenAPI effects
Behaviour that changed after 0.128.8Version differences
Validation order, exact error textsMechanics
Common bugs and their fixesSolving the classic problems
Which declaration for which inputChoosing
Monolith to distributed systemIn architecture
Reproduce itLab
Laravel Form Requests and validation rulesFor PHP/Laravel developers
Go struct tags and validatorThe Go angle

Everything in one minute ​

Where a value comes from, how to declare it, and what a failure looks like. All loc values are real output of the snippet app or the saved probes (runs/p4-output.txt for the header and path rows).

SourceDeclarationExample request422 loc on failure
Pathcart_id: UUID (name in the template)/carts/7d0e…/items["path", "cart_id"]
Query (one value)limit: Annotated[int, Query(ge=1, le=100)] = 20?limit=50["query", "limit"]
Query (repeated key)tag: Annotated[list[str], Query()] = []?tag=a&tag=b["query", "tag"]
Query (model)filters: Annotated[ProductFilter, Query()]?category=books&limit=5["query", "<field>"]
Headeruser_agent: Annotated[str, Header(min_length=50)]User-Agent: curl/8["header", "user-agent"]
Header (model)headers: Annotated[ClientHeaders, Header()]X-Request-ID: …["header", "x_request_id"] (0.128.8)
Cookiesession_id: Annotated[str, Cookie()]Cookie: session_id=…["cookie", "session_id"]
JSON body (one model)order: OrderIn{"email": …, "lines": […]}["body", "lines", 0, "qty"]
JSON body (several)line: OrderLine, gift_note: Annotated[str, Body()]{"line": {…}, "gift_note": "…"}["body", "line", …]
Form fieldusername: Annotated[str, Form()]username=sara&password=…["body", "username"]
Filephotos: Annotated[list[UploadFile], File()]multipart parts["body", "photos"]

The validation hooks, in the order they run for one field (diagram in Mechanics):

HookRuns onUse it forRaises → 422 type
BeforeValidator(fn)The raw inputNormalising: strip spaces, 560 001 → 560001, number → stringyour ValueError → value_error
Core type validationRaw input → type"5" → 5 (lax) or refusal (strict)int_parsing, int_type, uuid_parsing, enum, literal_error …
Field(...) / Query(...) constraintsThe typed valuege, le, min_length, pattern, max_length on listsgreater_than_equal, string_too_short, string_pattern_mismatch, too_long
AfterValidator(fn) / @field_validatorThe validated valueRules a type cannot express: regex + checksum, prefixesvalue_error
@model_validator(mode="after")The whole modelCross-field rules: min_price ≤ max_price, unique SKUsvalue_error at the model's loc
@computed_fieldOutput onlyDerived values: total_cents— (it is not input)

What the client gets back. The default comes from FastAPI; the right column is the snippet's Problem Details handler (both real).

SituationDefault FastAPIWith the Problem Details handler
Any validation failure422 application/json {"detail": [{type, loc, msg, input, ctx}]}422 application/problem+json {type, title, status, detail, instance, errors: [{location, pointer | parameter, code, detail}]}
raise HTTPException(404, "…")404 {"detail": "…"}404 {"type": "about:blank", "title": "Not Found", "status": 404, …}
Router 404 / 405{"detail": "Not Found"}Same envelope (handler registered for Starlette's HTTPException)
raise OutOfStock(...) (custom class)500 unless handled409 {"type": ".../out-of-stock", "sku": …, "available": 0}
Header model missing a field422 whose input echoes every request header, Authorization included422 without input

Why it exists ​

An API's inputs are written by strangers: browsers with stale JavaScript, mobile apps three versions old, partner integrations, scripts, attackers. Each input is a string (path, query, headers, cookies, form fields) or untyped JSON. Without a validation layer, every handler starts with twenty lines of if "email" not in data, int(request.query_params.get("limit", "20")) and try/except ValueError. The first failed check returns, so the client fixes one problem per round trip. Types are never converted, so "2" reaches the database as text. Unknown fields such as is_admin pass straight through to the ORM (mass assignment). The error format differs per developer, and none of it is documented. FastAPI moves all of that into the signature: the type and its constraints are the validation, are the conversion and are the documentation. Pydantic does the work in its Rust core and reports every failing field at once (for a scalar field with several constraints, only the first failing check; a Union field can report one error per member).

Hand-written validationDeclared validation (FastAPI + Pydantic)
data = await request.json() then if chainsorder: OrderIn
First error wins; one fix per round tripAll errors in one response
"2" stays a string; int() crashes with 500"2" → 2 (lax) or refused (strict), never a 500
Unknown fields silently kept and echoed backextra="forbid" → 422 extra_forbidden
Ad-hoc {"error": "..."}, status 200 or 400One error shape, 422, replaceable by Problem Details
Cookies set with framework defaultsHttpOnly, Secure, SameSite chosen per cookie
/docs knows nothing about the inputsEvery parameter, constraint and example in OpenAPI

An everyday picture. A parcel counter at the post office. The clerk (FastAPI) has a printed form per service (the signature). The form says which boxes exist and where they are (path, query, header, cookie, body), what may go in each ("postcode: 6 digits, not starting with 0") and which boxes are optional. Before anything is weighed or paid, the clerk checks the whole form and hands it back with every wrong box circled in red (the 422 list). A box the form does not have ("is_admin: yes") is crossed out and returned, not ignored (extra="forbid"). Some checks need more than the box: "billing country must match the card" looks at two boxes together (a model validator), and "is the parcel heavier than our stock of stamps?" needs the back office (a dependency or a domain exception, a 409, not a 422). The receipt stapled to your parcel has small print you cannot remove (HttpOnly) and is only valid at this branch (SameSite). And the post office's complaint form (Problem Details) is the same for every kind of complaint.

Three common misunderstandings, up front ​

  1. "Optional[str] / str | None makes a parameter optional." The default value does. q: str | None without = None is still required (missing). The FastAPI docs: "The type str | None allows None as a Python value, but it does not make a query parameter optional."
  2. "Pydantic validation is a security boundary on its own." It checks shape and local rules. It does not know whether order 42 belongs to this user (that is authorization, OWASP API1), whether the SKU exists (a database question) or whether a file is really a PNG (magic bytes). Keep database CHECK constraints too; the snippet shows one catching what skipped validation.
  3. "Raise ValueError in my endpoint and FastAPI turns it into a 422." Only inside validators (Pydantic converts it to value_error). In the endpoint body a ValueError is an unhandled exception: 500. In the endpoint, raise HTTPException or a domain exception with a handler.

Where it comes from ​

Pydantic v2.0 was released on 2023-06-30 with a validation core rewritten in Rust (pydantic-core). FastAPI 0.100.0 (2023-07-07) added Pydantic v2 support. 0.126.0 (2025-12-20) dropped Pydantic v1, which also retired the v1 error type names (type_error.integer) still printed in some old tutorials. Two FastAPI releases created this chapter's newest APIs. 0.113.0 (2024-09-05) introduced form models, and 0.114.0 added extra="forbid" for them. 0.115.0 (2024-09-17) introduced query, header and cookie parameter models: "Use Pydantic models to restrict extra values for Query parameters (also applies to Header and Cookie parameters)." Annotated custom validation with AfterValidator got docs and tests in 0.115.11 (2025-03-01). 0.115.12 fixed convert_underscores=False for header models.

A long run of 2026 releases then refined exactly this surface. 0.132.0 (2026-02-23) added strict_content_type: a JSON body without a JSON Content-Type is rejected by default. 0.136.3 (2026-05-23) made FastAPI "not accept underscore headers when using convert_underscores=True (the default)". In October 2026, 0.147.0 to 0.162.0 reworked form handling (empty strings, unchecked checkboxes, unselected files). The same releases changed parameter models: 0.148.0 made defaults no longer count as "set" for exclude_unset, 0.152.0 made header-model errors report the HTTP header name, 0.157.0 allowed combining several models, 0.159.0 allowed optional models and 0.160.0 applied extra to sibling fields. 0.151.0 distinguished JSON null from an omitted value. 0.164.0 and 0.165.0 (2026-11-18) added configurable body-size and form-parsing limits. On the standards side, RFC 7807 (March 2016) defined "Problem Details for HTTP APIs" and RFC 9457 (July 2023) obsoleted it. RFC 9110 (June 2022) renamed 422 from WebDAV's "Unprocessable Entity" (RFC 4918) to "Unprocessable Content". RFC 6265 (April 2011) is the cookie standard and defines Secure and HttpOnly; SameSite is not in it (it is not mentioned in the RFC text), and this page takes its values and the browser defaults from MDN's Set-Cookie reference.

1  2011-04  RFC 6265: Set-Cookie, Secure, HttpOnly
2  2016-03  RFC 7807: Problem Details for HTTP APIs (application/problem+json)
3  2022-06  RFC 9110: 422 is now "Unprocessable Content"
4  2023-06  Pydantic 2.0 (Rust core); 2023-07 FastAPI 0.100 supports it; 2023-07 RFC 9457 obsoletes 7807
5  2024-09  FastAPI 0.113 form models; 0.115 query / header / cookie parameter models
6  2025-03  FastAPI 0.115.11 documents AfterValidator in Annotated; 0.115.12 header-model convert_underscores fix
7  2025-12  FastAPI 0.126 drops Pydantic v1
8  2026-02  0.128.8 (last release for Python 3.9, pinned here); 0.132 strict_content_type
9  2026-05  0.136.3 rejects underscore header names by default
10 2026-10  0.147-0.162: form empty values, exclude_unset, header-name locs, combined and optional models, JSON null
11 2026-11  0.164 max body size; 0.165 form parsing limits

Python ​

Before ​

An order API that validates by hand. The body comes from await request.json() and is checked field by field, so the first error wins. "2" stays a string. Unknown fields such as is_admin are echoed back. The postcode check is isdigit(). The session cookie has no flags. Headers and cookies are read from request.headers and request.cookies, so /docs shows nothing. A negative quantity is stopped only by the database CHECK constraint, as a 500.

py
"""Before: an order API that validates by hand.

Everything here "works" for the happy path. The bugs are the lesson:
- the body is read with request.json() and checked field by field, so the first error wins,
  types are not converted ("2" stays a string) and unknown fields are silently kept;
- errors are 400 with an ad-hoc {"error": ...} shape that differs per route;
- the postcode check is `isdigit()`, so "000000" and "12" pass;
- the session cookie is set without HttpOnly, Secure or SameSite;
- headers are read from request.headers, so /docs shows no parameters at all;
- a database CHECK constraint is the only thing that stops a negative quantity, and it answers 500.
"""

from __future__ import annotations

import sqlite3

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI(title="Orders (before)")

_db = sqlite3.connect(":memory:", check_same_thread=False)
_db.execute("CREATE TABLE order_lines (sku TEXT NOT NULL, qty INTEGER NOT NULL CHECK (qty BETWEEN 1 AND 99))")


@app.post("/orders")
async def create_order(request: Request):
    data = await request.json()
    if "email" not in data:
        return JSONResponse({"error": "email missing"}, status_code=400)
    if "@" not in data["email"]:
        return JSONResponse({"error": "bad email"}, status_code=400)
    postcode = data.get("postcode", "")
    if not postcode.isdigit():
        return JSONResponse({"error": "postcode"}, status_code=400)
    for line in data.get("lines", []):
        # qty is whatever JSON sent: "2", 2, -5 or 2.5 all reach the database
        _db.execute("INSERT INTO order_lines (sku, qty) VALUES (?, ?)", (line["sku"], line["qty"]))
    return data  # echoes unknown fields such as "is_admin" back to the client


@app.get("/products")
async def list_products(request: Request):
    limit = int(request.query_params.get("limit", "20"))  # "abc" -> ValueError -> 500
    return {"limit": limit, "extra": dict(request.query_params)}


@app.post("/login")
async def login(request: Request):
    response = JSONResponse({"ok": True})
    response.set_cookie("session", "s3cr3t")  # readable by JavaScript, sent over plain HTTP
    return response


@app.get("/me")
async def me(request: Request):
    session = request.cookies.get("session")
    request_id = request.headers.get("x-request-id")
    if not session:
        return JSONResponse({"message": "no session"}, status_code=400)
    return {"session": session, "request_id": request_id}

The tests pin every bug down (each passes because the bug is real):

py
"""Pins down the bugs of app/before.py; each test passes because the bug is real."""

from __future__ import annotations

import sqlite3

import pytest
from fastapi.testclient import TestClient

from app.before import app

client = TestClient(app, raise_server_exceptions=False)


def test_first_error_only_and_ad_hoc_shape() -> None:
    r = client.post("/orders", json={"postcode": "12"})
    assert r.status_code == 400
    assert r.json() == {"error": "email missing"}  # the bad postcode is never reported


def test_isdigit_accepts_impossible_postcodes() -> None:
    for postcode in ("000000", "12", "0123456789012"):
        r = client.post("/orders", json={"email": "a@b.co", "postcode": postcode, "lines": []})
        assert r.status_code == 200


def test_unknown_fields_are_echoed_back() -> None:
    r = client.post("/orders", json={"email": "a@b.co", "postcode": "560001", "is_admin": True})
    assert r.json()["is_admin"] is True


def test_string_quantity_is_stored_and_negative_quantity_is_a_500() -> None:
    ok = client.post("/orders", json={"email": "a@b.co", "postcode": "1", "lines": [{"sku": "x", "qty": "2"}]})
    assert ok.status_code == 200  # "2" reached the database as text; SQLite coerced it
    bad = client.post("/orders", json={"email": "a@b.co", "postcode": "1", "lines": [{"sku": "x", "qty": -5}]})
    assert bad.status_code == 500  # only the CHECK constraint stopped it


def test_check_constraint_is_what_fired() -> None:
    from app.before import _db

    with pytest.raises(sqlite3.IntegrityError, match="CHECK constraint failed"):
        _db.execute("INSERT INTO order_lines (sku, qty) VALUES ('x', -5)")


def test_hand_parsed_query_is_a_500_and_has_no_docs() -> None:
    assert client.get("/products?limit=abc").status_code == 500
    op = client.get("/openapi.json").json()["paths"]["/products"]["get"]
    assert "parameters" not in op


def test_cookie_without_flags() -> None:
    r = client.post("/login")
    assert r.headers["set-cookie"] == "session=s3cr3t; Path=/; SameSite=lax"  # no HttpOnly, no Secure

After ​

Reusable validated types come first: normalise with BeforeValidator, check with AfterValidator. They cover the Indian PIN code, Iranian and UK postcodes, and a Luhn-checked gift-card number.

py
"""Reusable validated types: normalise first (BeforeValidator), then check (AfterValidator).

The course's "Indian PIN code" exercise, generalised: every national postcode rule is
"normalise -> regex for the shape -> structural/checksum rule -> canonical form".
- India PIN: six digits, first digit 1-9 is the postal zone (9 = Army Postal Service).
- Iran: ten digits (5-digit departure code + 5-digit distribution code).
- UK: outward code + inward code, normalised to upper case with one space.
Checksums (Luhn, "mod 10") are shown on a gift-card number, because postcodes have none.
"""

from __future__ import annotations

import re
from typing import Annotated, Any, Callable, Dict

from pydantic import AfterValidator, BeforeValidator

PIN_RE = re.compile(r"^[1-9][0-9]{5}$")
IR_RE = re.compile(r"^[0-9]{10}$")
# Simplified shape of a UK postcode (outward code, space, inward code); not the full official grammar.
UK_RE = re.compile(r"^[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][A-Z]{2}$")

PIN_ZONES = {
    "1": "North", "2": "North", "3": "West", "4": "West", "5": "South",
    "6": "South", "7": "East", "8": "East", "9": "Army Postal Service",
}


def _strip_spaces(value: Any) -> Any:
    """BeforeValidator: runs on the raw input, before Pydantic's own str validation."""
    if isinstance(value, int):          # JSON clients send 560001 as a number
        value = str(value)
    if isinstance(value, str):
        return re.sub(r"[\s-]", "", value)
    return value                        # let Pydantic report the wrong type


def check_indian_pin(value: str) -> str:
    """AfterValidator: runs on an already validated str."""
    if not PIN_RE.fullmatch(value):
        raise ValueError("an Indian PIN code is 6 digits and cannot start with 0")
    return value


def check_iranian_postcode(value: str) -> str:
    if not IR_RE.fullmatch(value):
        raise ValueError("an Iranian postcode is 10 digits")
    return value


def _normalise_uk(value: Any) -> Any:
    if isinstance(value, str):
        compact = re.sub(r"\s", "", value).upper()
        return compact[:-3] + " " + compact[-3:] if len(compact) > 3 else compact
    return value


def check_uk_postcode(value: str) -> str:
    if not UK_RE.fullmatch(value):
        raise ValueError("not a UK postcode (expected e.g. SW1A 1AA)")
    return value


IndianPIN = Annotated[str, BeforeValidator(_strip_spaces), AfterValidator(check_indian_pin)]
IranianPostcode = Annotated[str, BeforeValidator(_strip_spaces), AfterValidator(check_iranian_postcode)]
UKPostcode = Annotated[str, BeforeValidator(_normalise_uk), AfterValidator(check_uk_postcode)]

# One entry per country: the address model picks the rule from the `country` field.
POSTCODE_RULES: Dict[str, Callable[[str], str]] = {
    "IN": lambda v: check_indian_pin(_strip_spaces(v)),
    "IR": lambda v: check_iranian_postcode(_strip_spaces(v)),
    "GB": lambda v: check_uk_postcode(_normalise_uk(v)),
}


def pin_zone(pin: str) -> str:
    return PIN_ZONES[pin[0]]


def luhn_valid(number: str) -> bool:
    """Luhn / mod 10: double every second digit from the right, subtract 9 above 9, sum % 10 == 0."""
    total = 0
    for i, ch in enumerate(reversed(number)):
        d = int(ch)
        if i % 2 == 1:
            d *= 2
            if d > 9:
                d -= 9
        total += d
    return total % 10 == 0


def check_gift_card(value: str) -> str:
    if not re.fullmatch(r"[0-9]{16}", value):
        raise ValueError("a gift card number is 16 digits")
    if not luhn_valid(value):
        raise ValueError("gift card number failed the Luhn check (typo?)")
    return value


GiftCardNumber = Annotated[str, BeforeValidator(_strip_spaces), AfterValidator(check_gift_card)]

One model per input location: a query model with extra="forbid" and a cross-field rule, nested body models with strict fields, aliases, a computed_field and a country-dependent postcode rule, a PATCH model for exclude_unset, a header model and a cookie model.

py
"""Request models: one per input location (query, body, headers, cookies, form).

Works on FastAPI 0.128.8 (the pinned version). Two things newer FastAPI adds are NOT used here:
combining several query/header/cookie models in one function (0.157.0) and optional
parameter models `Model | None = None` (0.159.0); on 0.128.8 the first answers 422 "missing"
for both models and the second fails at import with an AssertionError.
"""

from __future__ import annotations

from datetime import datetime, timezone
from enum import Enum
from typing import List, Literal, Optional
from uuid import UUID

from pydantic import (
    BaseModel,
    ConfigDict,
    Field,
    ValidationInfo,
    computed_field,
    field_validator,
    model_validator,
)

from app.validators import POSTCODE_RULES, GiftCardNumber


class Category(str, Enum):
    """On Python 3.11+ write `class Category(StrEnum)`."""

    books = "books"
    games = "games"
    music = "music"


# --- query -----------------------------------------------------------------------------------


class ProductFilter(BaseModel):
    """GET /products?category=books&max_price=5000&tag=new&tag=sale&order_by=price&limit=10"""

    model_config = ConfigDict(extra="forbid")  # ?tool=plumbus -> 422 extra_forbidden

    category: Optional[Category] = None
    q: Optional[str] = Field(None, min_length=2, max_length=50, description="Free-text search")
    min_price: int = Field(0, ge=0)
    max_price: int = Field(1_000_000, gt=0, le=1_000_000)
    tag: List[str] = Field(default_factory=list, max_length=5)  # repeated ?tag=a&tag=b
    order_by: Literal["id", "price", "name"] = "id"
    desc: bool = False
    limit: int = Field(20, ge=1, le=100)
    offset: int = Field(0, ge=0)

    @model_validator(mode="after")
    def price_range(self) -> ProductFilter:
        if self.min_price > self.max_price:
            raise ValueError("min_price must not be greater than max_price")
        return self


# --- body ------------------------------------------------------------------------------------


class Address(BaseModel):
    model_config = ConfigDict(str_strip_whitespace=True)

    name: str = Field(min_length=1, max_length=100)
    line1: str = Field(min_length=1, max_length=200)
    city: str = Field(min_length=1, max_length=100)
    country: Literal["IN", "IR", "GB"]
    postcode: str

    @field_validator("postcode")
    @classmethod
    def postcode_matches_country(cls, v: str, info: ValidationInfo) -> str:
        # info.data holds the fields validated so far (declaration order): country is above us.
        country = info.data.get("country")
        if country is None:  # country itself failed; its own error is already reported
            return v
        return POSTCODE_RULES[country](v)


class OrderLine(BaseModel):
    model_config = ConfigDict(extra="forbid")

    sku: str = Field(pattern=r"^[A-Z]{3}-[0-9]{4}$", examples=["BOK-0001"])
    qty: int = Field(ge=1, le=99)
    unit_price_cents: int = Field(ge=0, strict=True)  # strict: "4200" (a string) is refused


class OrderIn(BaseModel):
    """POST /orders body. Nested models, list constraints, cross-field rules, a computed total."""

    model_config = ConfigDict(
        extra="forbid",  # {"is_admin": true} -> 422 instead of being silently dropped
        json_schema_extra={
            "examples": [
                {
                    "email": "sara@example.com",
                    "shipping": {"name": "Sara", "line1": "12 MG Road", "city": "Bengaluru",
                                 "country": "IN", "postcode": "560 001"},
                    "lines": [{"sku": "BOK-0001", "qty": 2, "unit_price_cents": 4200}],
                }
            ]
        },
    )

    email: str = Field(pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$", max_length=254)
    shipping: Address
    billing: Optional[Address] = None
    lines: List[OrderLine] = Field(min_length=1, max_length=50)
    coupon: Optional[str] = Field(None, alias="couponCode", max_length=20)
    gift_card: Optional[GiftCardNumber] = None
    deliver_after: Optional[datetime] = None

    @field_validator("email")
    @classmethod
    def lower_email(cls, v: str) -> str:
        return v.lower()

    @field_validator("deliver_after")
    @classmethod
    def aware_and_future(cls, v: Optional[datetime]) -> Optional[datetime]:
        if v is None:
            return v
        if v.tzinfo is None:
            raise ValueError("deliver_after needs a time zone offset, e.g. 2026-12-01T09:00:00+05:30")
        if v <= datetime.now(timezone.utc):
            raise ValueError("deliver_after must be in the future")
        return v

    @model_validator(mode="after")
    def unique_skus(self) -> OrderIn:
        skus = [line.sku for line in self.lines]
        if len(skus) != len(set(skus)):
            raise ValueError("each sku may appear only once; raise qty instead")
        return self

    @computed_field  # appears in model_dump() and in the response schema (readOnly)
    @property
    def total_cents(self) -> int:
        return sum(line.qty * line.unit_price_cents for line in self.lines)


class OrderOut(BaseModel):
    id: UUID
    email: str
    status: Literal["pending", "paid", "shipped"]
    total_cents: int
    shipping: Address


class OrderPatch(BaseModel):
    """PATCH body: every field optional; model_dump(exclude_unset=True) tells sent from absent."""

    model_config = ConfigDict(extra="forbid")

    email: Optional[str] = Field(None, pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
    shipping: Optional[Address] = None
    note: Optional[str] = Field(None, max_length=500)  # null is a real value: "clear the note"


# --- headers and cookies ---------------------------------------------------------------------


class ClientHeaders(BaseModel):
    """Header model. Field x_request_id is read from the X-Request-ID header (underscores -> hyphens)."""

    model_config = ConfigDict(extra="ignore")  # "forbid" would reject Host, User-Agent, Accept ...

    x_request_id: UUID
    x_client_version: str = Field("0.0.0", pattern=r"^\d+\.\d+\.\d+$")
    accept_language: Optional[str] = None
    x_feature: List[str] = []  # duplicate headers: X-Feature: a / X-Feature: b -> ["a", "b"]


class SessionCookies(BaseModel):
    """Cookie model: the cookies this API reads; everything else a browser sends is ignored."""

    session_id: str = Field(min_length=16, max_length=128, pattern=r"^[A-Za-z0-9_-]+$")
    theme: Literal["light", "dark"] = "light"


class Preferences(BaseModel):
    theme: Literal["light", "dark"]

The error format: a RequestValidationError handler that emits RFC 9457 Problem Details without echoing the input, a handler for Starlette's HTTPException, custom exception classes, and the responses= entries that document all of it:

py
"""Error responses as Problem Details (RFC 9457, application/problem+json).

FastAPI's default 422 body is {"detail": [{type, loc, msg, input, ctx}]}. This module replaces it
with one documented shape for every error the API produces:
- RequestValidationError (422) -> "errors" extension, one entry per problem, with a JSON Pointer
  for body fields and the parameter name for query/header/cookie values. The raw `input` is NOT
  echoed: for header models it would contain every request header, Authorization included.
- HTTPException (any status)   -> same envelope, `detail` from the exception.
- Domain exceptions (custom exception classes) -> their own type URI and status.
"""

from __future__ import annotations

import logging
from http import HTTPStatus
from typing import Any, Dict, List, Optional

from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from starlette.exceptions import HTTPException as StarletteHTTPException

log = logging.getLogger("shop.errors")

PROBLEM_JSON = "application/problem+json"
TYPE_BASE = "https://shop.example/problems/"


class FieldProblem(BaseModel):
    pointer: Optional[str] = None  # body fields: JSON Pointer, e.g. "#/lines/0/qty"
    parameter: Optional[str] = None  # query/path/header/cookie: the name on the wire
    location: str  # "body" | "query" | "path" | "header" | "cookie"
    code: str  # Pydantic error type: missing, int_parsing, string_too_short, value_error ...
    detail: str


class Problem(BaseModel):
    """The error response model, documented in OpenAPI through `responses=`."""

    type: str = "about:blank"
    title: str
    status: int
    detail: Optional[str] = None
    instance: Optional[str] = None
    errors: Optional[List[FieldProblem]] = None


def problem_response(status: int, title: str, request: Request, *, type_: str = "about:blank",
                     detail: Optional[str] = None, headers: Optional[Dict[str, str]] = None,
                     **extensions: Any) -> JSONResponse:
    body: Dict[str, Any] = {"type": type_, "title": title, "status": status, "instance": request.url.path}
    if detail is not None:
        body["detail"] = detail
    body.update(extensions)
    return JSONResponse(body, status_code=status, media_type=PROBLEM_JSON, headers=headers)


def json_pointer(parts: List[Any]) -> str:
    """RFC 6901: escape "~" as "~0" first, then "/" as "~1", in every reference token."""
    tokens = [str(p).replace("~", "~0").replace("/", "~1") for p in parts]
    return "#/" + "/".join(tokens) if tokens else "#"


def _to_field_problem(err: Dict[str, Any]) -> Dict[str, Any]:
    loc = list(err.get("loc", ()))
    where = str(loc[0]) if loc else "body"
    rest = loc[1:]
    item: Dict[str, Any] = {"location": where, "code": err["type"], "detail": err["msg"]}
    if where == "body":
        item["pointer"] = json_pointer(rest)
    else:
        item["parameter"] = str(rest[0]) if rest else None
    return item


# --- custom exception classes ----------------------------------------------------------------


class DomainError(Exception):
    """Base class: raise these from services; handlers turn them into Problem Details."""

    status = 400
    slug = "domain-error"
    title = "Request could not be processed"

    def __init__(self, detail: str, **extensions: Any) -> None:
        super().__init__(detail)
        self.detail = detail
        self.extensions = extensions


class OutOfStock(DomainError):
    status = 409
    slug = "out-of-stock"
    title = "Not enough stock"


class UnsupportedPostcodeArea(DomainError):
    status = 422
    slug = "unsupported-postcode-area"
    title = "We do not deliver to this postcode"


def install_problem_handlers(app: FastAPI) -> None:
    @app.exception_handler(RequestValidationError)
    async def validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
        errors = [_to_field_problem(e) for e in exc.errors()]
        # Log codes and locations, never the raw input (it may contain tokens or personal data).
        log.info("validation failed %s %s", request.url.path, [(e["location"], e["code"]) for e in errors])
        return problem_response(
            422, "Your request is not valid.", request, type_=TYPE_BASE + "validation",
            detail=f"{len(errors)} validation error(s)", errors=errors,
        )

    # Register for Starlette's HTTPException so router 404/405s get the same envelope.
    @app.exception_handler(StarletteHTTPException)
    async def http_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
        detail = exc.detail if isinstance(exc.detail, str) else None
        # RFC 9457 4.2.1: with type "about:blank" the title SHOULD be the status code's reason phrase.
        try:
            title = HTTPStatus(exc.status_code).phrase
        except ValueError:  # a non-standard status code
            title = "Error"
        return problem_response(exc.status_code, title, request, detail=detail,
                                headers=getattr(exc, "headers", None))

    @app.exception_handler(DomainError)
    async def domain_handler(request: Request, exc: DomainError) -> JSONResponse:
        return problem_response(exc.status, exc.title, request, type_=TYPE_BASE + exc.slug,
                                detail=exc.detail, **exc.extensions)


# What `responses=` puts into OpenAPI for routes that use this envelope. `model` registers the
# Problem schema but FastAPI files it under application/json; the explicit `content` entry is what
# documents the media type actually sent (both entries end up in the schema; checked in the tests).
_PROBLEM_CONTENT = {PROBLEM_JSON: {"schema": {"$ref": "#/components/schemas/Problem"}}}
PROBLEM_RESPONSES: Dict[int, Dict[str, Any]] = {
    422: {"model": Problem, "description": "Validation failed (RFC 9457 Problem Details)",
          "content": _PROBLEM_CONTENT},
    409: {"model": Problem, "description": "Conflict, e.g. out of stock", "content": _PROBLEM_CONTENT},
}

The database keeps CHECK constraints that mirror the rules, and the filter becomes bound parameters only:

py
"""SQLite behind the API. Validation at the edge does not replace constraints in the database:
the CHECKs below mirror the Pydantic rules, so a bug or a second writer cannot store what the
API would have refused. The ORM version (SQLAlchemy 2 / SQLModel) is in its own chapter.
"""

from __future__ import annotations

import sqlite3
import threading
from typing import Any, Dict, List, Optional

SCHEMA = """
CREATE TABLE IF NOT EXISTS products (
    id          INTEGER PRIMARY KEY,
    sku         TEXT    NOT NULL UNIQUE CHECK (sku GLOB '[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]'),
    name        TEXT    NOT NULL CHECK (length(name) BETWEEN 1 AND 120),
    category    TEXT    NOT NULL CHECK (category IN ('books', 'games', 'music')),
    price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
    stock       INTEGER NOT NULL CHECK (stock >= 0),
    tags        TEXT    NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS orders (
    id          TEXT    PRIMARY KEY,
    email       TEXT    NOT NULL CHECK (email LIKE '%_@_%._%'),
    postcode    TEXT    NOT NULL,
    country     TEXT    NOT NULL CHECK (country IN ('IN', 'IR', 'GB')),
    total_cents INTEGER NOT NULL CHECK (total_cents >= 0)
);
CREATE TABLE IF NOT EXISTS order_lines (
    order_id    TEXT    NOT NULL REFERENCES orders (id),
    sku         TEXT    NOT NULL,
    qty         INTEGER NOT NULL CHECK (qty BETWEEN 1 AND 99),
    PRIMARY KEY (order_id, sku)
);
"""

SEED = [
    ("BOK-0001", "The Pragmatic Programmer", "books", 4200, 10, "new,bestseller"),
    ("BOK-0002", "Designing Data-Intensive Applications", "books", 5500, 3, "bestseller"),
    ("GAM-0001", "Chess Set", "games", 3000, 0, "sale"),
    ("GAM-0002", "Go Board", "games", 6500, 5, ""),
    ("MUS-0001", "Kind of Blue (vinyl)", "music", 2800, 7, "sale,new"),
]

# The filter model maps to bound parameters only. ORDER BY cannot be a bound parameter, so the
# column comes from a whitelist keyed by the Literal the model already validated.
ORDER_COLUMNS = {"id": "id", "price": "price_cents", "name": "name"}

LIST_SQL = """
SELECT id, sku, name, category, price_cents, stock
FROM products
WHERE (:category IS NULL OR category = :category)
  AND (:q IS NULL OR name LIKE '%' || :q || '%')
  AND price_cents BETWEEN :min_price AND :max_price{tag_clauses}
ORDER BY {order_column} {direction}
LIMIT :limit OFFSET :offset
"""


class Shop:
    def __init__(self, path: str = ":memory:") -> None:
        self._conn = sqlite3.connect(path, check_same_thread=False)
        self._conn.row_factory = sqlite3.Row
        self._lock = threading.Lock()
        with self._lock:
            self._conn.executescript(SCHEMA)
            if self._conn.execute("SELECT count(*) FROM products").fetchone()[0] == 0:
                self._conn.executemany(
                    "INSERT INTO products (sku, name, category, price_cents, stock, tags) VALUES (?, ?, ?, ?, ?, ?)",
                    SEED,
                )
                self._conn.commit()

    def list_products(self, *, category: Optional[str], q: Optional[str], min_price: int, max_price: int,
                      tags: List[str], order_by: str, desc: bool, limit: int, offset: int) -> List[Dict[str, Any]]:
        params: Dict[str, Any] = {"category": category, "q": q, "min_price": min_price,
                                  "max_price": max_price, "limit": limit, "offset": offset}
        # One bound parameter per tag (?tag=a&tag=b means "has a AND b"); the SQL text never holds input.
        tag_clauses = ""
        for i, tag in enumerate(tags):
            params[f"tag{i}"] = tag
            tag_clauses += f"\n  AND (',' || tags || ',') LIKE '%,' || :tag{i} || ',%'"
        sql = LIST_SQL.format(tag_clauses=tag_clauses, order_column=ORDER_COLUMNS[order_by],
                              direction="DESC" if desc else "ASC")
        with self._lock:
            return [dict(r) for r in self._conn.execute(sql, params)]

    def stock_of(self, sku: str) -> Optional[int]:
        with self._lock:
            row = self._conn.execute("SELECT stock FROM products WHERE sku = ?", (sku,)).fetchone()
        return None if row is None else row["stock"]

    def insert_order(self, order_id: str, email: str, postcode: str, country: str, total_cents: int,
                     lines: List[Dict[str, Any]]) -> None:
        with self._lock, self._conn:  # one transaction: all lines or none
            self._conn.execute(
                "INSERT INTO orders (id, email, postcode, country, total_cents) VALUES (?, ?, ?, ?, ?)",
                (order_id, email, postcode, country, total_cents),
            )
            self._conn.executemany(
                "INSERT INTO order_lines (order_id, sku, qty) VALUES (?, ?, ?)",
                [(order_id, line["sku"], line["qty"]) for line in lines],
            )

    def raw_insert_line(self, order_id: str, sku: str, qty: Any) -> None:
        """Used by a test to show the CHECK constraint catching what skipped validation."""
        with self._lock, self._conn:
            self._conn.execute("INSERT INTO order_lines (order_id, sku, qty) VALUES (?, ?, ?)", (order_id, sku, qty))

The application: one route per input location, plus a route that mixes path, query and two body parameters:

py
"""After: the shop API with every input declared, validated and documented.

Run it:  uvicorn app.main:app --reload       Docs: /docs, /redoc, /openapi.json
Each route shows one input location; the error format is Problem Details (app/problems.py).
"""

from __future__ import annotations

import secrets
from contextlib import asynccontextmanager
from typing import Annotated, AsyncIterator, Dict, List, Optional
from uuid import UUID, uuid4

from fastapi import (
    Body,
    Cookie,
    FastAPI,
    File,
    Form,
    Header,
    HTTPException,
    Path,
    Query,
    Request,
    Response,
    UploadFile,
    status,
)
from fastapi.exceptions import RequestValidationError
from pydantic import AfterValidator, BaseModel, ValidationError

from app.db import Shop
from app.models import (
    Address,
    ClientHeaders,
    OrderIn,
    OrderLine,
    OrderOut,
    OrderPatch,
    Preferences,
    ProductFilter,
    SessionCookies,
)
from app.problems import PROBLEM_RESPONSES, OutOfStock, UnsupportedPostcodeArea, install_problem_handlers
from app.validators import IndianPIN, pin_zone


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    app.state.shop = Shop()
    app.state.orders: Dict[UUID, Dict] = {}
    app.state.sessions: Dict[str, str] = {}
    yield


app = FastAPI(
    title="Shop API",
    version="1.0.0",
    lifespan=lifespan,
    openapi_tags=[
        {"name": "catalog", "description": "Query parameters and query models"},
        {"name": "orders", "description": "JSON bodies, nested models, custom validators"},
        {"name": "session", "description": "Forms, cookies and headers"},
        {"name": "returns", "description": "File uploads"},
    ],
)
install_problem_handlers(app)


class ProductOut(BaseModel):
    id: int
    sku: str
    name: str
    category: str
    price_cents: int
    stock: int


# --- query -----------------------------------------------------------------------------------


@app.get("/products", tags=["catalog"], response_model=List[ProductOut], responses=PROBLEM_RESPONSES)
def list_products(request: Request, filters: Annotated[ProductFilter, Query()]) -> List[dict]:
    f = filters
    return request.app.state.shop.list_products(
        category=f.category.value if f.category else None, q=f.q, min_price=f.min_price,
        max_price=f.max_price, tags=f.tag, order_by=f.order_by, desc=f.desc, limit=f.limit, offset=f.offset,
    )


def _known_prefix(value: str) -> str:
    if not value.startswith(("isbn-", "ean-")):
        raise ValueError('id must start with "isbn-" or "ean-"')
    return value


@app.get("/lookup", tags=["catalog"])
def lookup(
    id: Annotated[Optional[str], AfterValidator(_known_prefix)] = None,
    q: Annotated[
        Optional[str],
        Query(alias="item-query", title="Search text", description="Matched against the product name",
              min_length=3, max_length=50, pattern=r"^[\w\s-]+$", examples=["chess"]),
    ] = None,
    min_rating: Annotated[float, Query(gt=0, le=5)] = 0.5,
    max_weight_g: Annotated[int, Query(ge=1, lt=30_000)] = 29_999,
    sort: Annotated[Optional[str], Query(deprecated=True, description="Use /products?order_by=")] = None,
    debug: Annotated[bool, Query(include_in_schema=False)] = False,
) -> dict:
    return {"id": id, "q": q, "min_rating": min_rating, "max_weight_g": max_weight_g, "sort": sort, "debug": debug}


@app.get("/catalog/search", tags=["catalog"], deprecated=True, summary="Old search, use GET /products")
def legacy_search(q: Optional[str] = None) -> dict:
    # Operation-level deprecation: still served, struck through in /docs.
    return {"q": q, "use_instead": "/products"}


# --- path + validated custom type --------------------------------------------------------------


@app.get("/postcodes/in/{pin}", tags=["catalog"], responses=PROBLEM_RESPONSES)
def check_pin(pin: Annotated[IndianPIN, Path(description="Indian PIN code, spaces allowed")]) -> dict:
    zone = pin_zone(pin)
    if zone == "Army Postal Service":
        raise UnsupportedPostcodeArea("Army Postal Service PINs (first digit 9) are not served", pin=pin)
    return {"pin": pin, "zone": zone, "sorting_district": pin[:3]}


# --- body ------------------------------------------------------------------------------------


@app.post("/orders", tags=["orders"], status_code=status.HTTP_201_CREATED, response_model=OrderOut,
          responses=PROBLEM_RESPONSES)
def create_order(
    request: Request,
    response: Response,
    order: OrderIn,
    idempotency_key: Annotated[UUID, Header(description="Client-generated UUID; retries reuse it")],
) -> dict:
    # Validated and documented here; storing it and replaying the first response is not shown
    # (see REST API Design: idempotency keys).
    shop: Shop = request.app.state.shop
    for line in order.lines:
        stock = shop.stock_of(line.sku)
        if stock is None:
            raise HTTPException(status.HTTP_404_NOT_FOUND, f"unknown sku {line.sku}")
        if stock < line.qty:
            raise OutOfStock(f"{line.sku}: {stock} left, {line.qty} requested", sku=line.sku, available=stock)
    order_id = uuid4()
    shop.insert_order(str(order_id), order.email, order.shipping.postcode, order.shipping.country,
                      order.total_cents, [line.model_dump() for line in order.lines])
    stored = {"id": order_id, "email": order.email, "status": "pending",
              "total_cents": order.total_cents, "shipping": order.shipping.model_dump()}
    request.app.state.orders[order_id] = stored
    response.headers["Location"] = f"/orders/{order_id}"
    return stored


@app.patch("/orders/{order_id}", tags=["orders"], response_model=OrderOut, responses=PROBLEM_RESPONSES)
def patch_order(request: Request, order_id: UUID, patch: OrderPatch) -> dict:
    stored = request.app.state.orders.get(order_id)
    if stored is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "order not found")
    changes = patch.model_dump(exclude_unset=True)  # only what the client sent, null included
    # Apply to a copy and re-validate as the full resource BEFORE storing: {"email": null} is valid
    # for the patch model (every field optional) but not for an order. Nothing is mutated on failure.
    candidate = {**stored, **changes}
    try:
        merged = OrderOut.model_validate(candidate)
    except ValidationError as exc:
        raise RequestValidationError(
            [{"type": e["type"], "loc": ("body", *e["loc"]), "msg": e["msg"]} for e in exc.errors()]
        ) from None
    request.app.state.orders[order_id] = merged.model_dump()
    return merged


@app.post("/carts/{cart_id}/items", tags=["orders"], status_code=status.HTTP_201_CREATED)
def add_to_cart(
    cart_id: UUID,  # path
    line: OrderLine,  # body key "line"
    gift_note: Annotated[Optional[str], Body(max_length=200)] = None,  # body key "gift_note"
    dry_run: bool = False,  # query
) -> dict:
    return {"cart_id": str(cart_id), "line": line.model_dump(), "gift_note": gift_note, "dry_run": dry_run}


@app.post("/wishlist", tags=["orders"])
def add_to_wishlist(line: Annotated[OrderLine, Body(embed=True)]) -> dict:
    return {"saved": line.sku}


@app.post("/addresses/validate", tags=["orders"], responses=PROBLEM_RESPONSES)
def validate_address(address: Address) -> Address:
    return address


# --- forms, cookies, headers -----------------------------------------------------------------


@app.post("/session", tags=["session"])
def login(
    request: Request,
    response: Response,
    username: Annotated[str, Form(min_length=3, max_length=50)],
    password: Annotated[str, Form(min_length=8)],
    remember: Annotated[bool, Form()] = False,
) -> dict:
    if password != "correct horse":  # stand-in for a real password check (see the auth chapter)
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "bad credentials")
    session_id = secrets.token_urlsafe(24)
    request.app.state.sessions[session_id] = username
    response.set_cookie(
        "session_id", session_id,
        httponly=True,  # not readable from document.cookie
        secure=True,  # only sent over HTTPS
        samesite="lax",  # not sent on cross-site POST/fetch; sent on top-level GET navigation
        max_age=60 * 60 * 24 * 30 if remember else None,  # None = session cookie
        path="/",
    )
    return {"user": username}


@app.get("/session/me", tags=["session"], responses=PROBLEM_RESPONSES)
def who_am_i(request: Request, cookies: Annotated[SessionCookies, Cookie()]) -> dict:
    user = request.app.state.sessions.get(cookies.session_id)
    if user is None:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "session expired")
    return {"user": user, "theme": cookies.theme}


@app.put("/preferences", tags=["session"])
def set_preferences(prefs: Preferences, response: Response) -> Preferences:
    # Read by front-end JavaScript, so deliberately NOT HttpOnly; still Secure and SameSite.
    response.set_cookie("theme", prefs.theme, secure=True, samesite="lax", max_age=60 * 60 * 24 * 365)
    return prefs


@app.delete("/session", tags=["session"], status_code=status.HTTP_204_NO_CONTENT)
def logout(response: Response) -> None:
    response.delete_cookie("session_id", path="/", secure=True, httponly=True, samesite="lax")


@app.get("/client", tags=["session"], responses=PROBLEM_RESPONSES)
def client_info(headers: Annotated[ClientHeaders, Header()]) -> dict:
    return headers.model_dump(mode="json")


@app.get("/account", tags=["session"])
def account(
    authorization: Annotated[Optional[str], Header()] = None,
    user_agent: Annotated[Optional[str], Header()] = None,  # reads User-Agent
    x_legacy_token: Annotated[Optional[str], Header(convert_underscores=False)] = None,  # reads x_legacy_token
) -> dict:
    # Preview only: real token verification (JWT, scopes) lives in the authentication chapter.
    scheme, _, token = (authorization or "").partition(" ")
    if scheme.lower() != "bearer" or not token:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token",
                            headers={"WWW-Authenticate": "Bearer"})
    return {"token_length": len(token), "user_agent": user_agent, "legacy": x_legacy_token}


# --- files -------------------------------------------------------------------------------------

ALLOWED_IMAGE_TYPES = {"image/jpeg", "image/png"}
MAX_PHOTO_BYTES = 2 * 1024 * 1024


@app.post("/returns/{order_id}/photos", tags=["returns"], status_code=status.HTTP_201_CREATED,
          responses=PROBLEM_RESPONSES)
async def upload_return_photos(
    order_id: UUID,
    reason: Annotated[str, Form(min_length=10, max_length=500)],
    photos: Annotated[List[UploadFile], File(description="1-3 JPEG or PNG images, 2 MiB each")],
) -> dict:
    if not 1 <= len(photos) <= 3:
        raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "send 1 to 3 photos")
    saved = []
    for photo in photos:
        head = await photo.read(8)  # trust the bytes, not the client's content_type
        is_png, is_jpeg = head.startswith(b"\x89PNG\r\n\x1a\n"), head.startswith(b"\xff\xd8\xff")
        if photo.content_type not in ALLOWED_IMAGE_TYPES or not (is_png or is_jpeg):
            raise HTTPException(status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, f"{photo.filename}: not a JPEG/PNG")
        data = head + await photo.read(MAX_PHOTO_BYTES + 1 - len(head))  # never more than limit + 1
        if len(data) > MAX_PHOTO_BYTES:
            raise HTTPException(status.HTTP_413_CONTENT_TOO_LARGE, f"{photo.filename}: over 2 MiB")
        saved.append({"filename": photo.filename, "content_type": photo.content_type, "bytes": len(data)})
    return {"order_id": str(order_id), "reason": reason, "photos": saved}

The tests are 64 in total. They walk through query and body validation, cookies and headers, forms and files, the error envelopes, and the OpenAPI schema each declaration produces:

py
from __future__ import annotations

from typing import Iterator

import pytest
from fastapi.testclient import TestClient

from app.main import app


@pytest.fixture()
def client() -> Iterator[TestClient]:
    # https base URL: the session cookie is Secure, and a Secure cookie is not sent back over http://.
    with TestClient(app, base_url="https://testserver") as c:
        yield c


@pytest.fixture()
def http_client() -> Iterator[TestClient]:
    with TestClient(app) as c:  # base_url http://testserver
        yield c


def problem_codes(body: dict) -> list:
    """[(location, pointer-or-parameter, code), ...] from a Problem Details body."""
    return [(e["location"], e.get("pointer") or e.get("parameter"), e["code"]) for e in body["errors"]]
py
from __future__ import annotations

from fastapi.testclient import TestClient

from tests.conftest import problem_codes


def test_query_model_defaults(client: TestClient) -> None:
    r = client.get("/products")
    assert r.status_code == 200
    assert [p["sku"] for p in r.json()] == ["BOK-0001", "BOK-0002", "GAM-0001", "GAM-0002", "MUS-0001"]


def test_query_model_filters_and_repeated_tags(client: TestClient) -> None:
    r = client.get("/products?tag=sale&tag=new&order_by=price&desc=true")
    assert [p["sku"] for p in r.json()] == ["MUS-0001"]
    r = client.get("/products?category=books&max_price=5000")
    assert [p["sku"] for p in r.json()] == ["BOK-0001"]
    r = client.get("/products?q=go&order_by=name")
    assert [p["sku"] for p in r.json()] == ["GAM-0002"]


def test_extra_query_parameter_is_forbidden(client: TestClient) -> None:
    r = client.get("/products?limit=10&tool=plumbus")
    assert r.status_code == 422
    assert r.headers["content-type"] == "application/problem+json"
    assert problem_codes(r.json()) == [("query", "tool", "extra_forbidden")]


def test_constraint_errors_are_all_reported(client: TestClient) -> None:
    r = client.get("/products?limit=0&offset=-1&order_by=rating&category=toys&q=x")
    assert r.status_code == 422
    assert sorted(problem_codes(r.json())) == sorted([
        ("query", "category", "enum"),
        ("query", "q", "string_too_short"),
        ("query", "order_by", "literal_error"),
        ("query", "limit", "greater_than_equal"),
        ("query", "offset", "greater_than_equal"),
    ])


def test_model_validator_on_query_model(client: TestClient) -> None:
    r = client.get("/products?min_price=5000&max_price=100")
    assert problem_codes(r.json()) == [("query", None, "value_error")]
    assert "min_price must not be greater than max_price" in r.json()["errors"][0]["detail"]


def test_list_length_constraint(client: TestClient) -> None:
    r = client.get("/products?" + "&".join(f"tag=t{i}" for i in range(6)))
    assert problem_codes(r.json()) == [("query", "tag", "too_long")]


def test_sql_injection_attempt_is_just_a_string(client: TestClient) -> None:
    r = client.get("/products", params={"q": "x' OR '1'='1"})
    assert r.status_code == 200 and r.json() == []  # bound parameter, matched literally


def test_individual_params_after_validator_alias_bounds(client: TestClient) -> None:
    assert client.get("/lookup?id=isbn-978").json()["id"] == "isbn-978"
    r = client.get("/lookup?id=abc")
    assert problem_codes(r.json()) == [("query", "id", "value_error")]
    assert r.json()["errors"][0]["detail"] == 'Value error, id must start with "isbn-" or "ean-"'
    assert client.get("/lookup?item-query=chess").json()["q"] == "chess"
    assert client.get("/lookup?q=chess").json()["q"] is None  # the alias is the only wire name
    r = client.get("/lookup?min_rating=0&max_weight_g=30000")
    assert sorted(problem_codes(r.json())) == [("query", "max_weight_g", "less_than"),
                                               ("query", "min_rating", "greater_than")]


def test_hidden_and_deprecated_parameters_still_work(client: TestClient) -> None:
    body = client.get("/lookup?debug=yes&sort=name").json()
    assert body["debug"] is True and body["sort"] == "name"


def test_path_pin_code(client: TestClient) -> None:
    assert client.get("/postcodes/in/560 001").json() == {"pin": "560001", "zone": "South", "sorting_district": "560"}
    r = client.get("/postcodes/in/056001")
    assert problem_codes(r.json()) == [("path", "pin", "value_error")]
    r = client.get("/postcodes/in/900001")
    assert r.status_code == 422
    assert r.json()["type"] == "https://shop.example/problems/unsupported-postcode-area"
    assert r.json()["pin"] == "900001"
py
from __future__ import annotations

import sqlite3
import uuid

import pytest
from fastapi.testclient import TestClient

from tests.conftest import problem_codes

GOOD = {
    "email": "Sara@Example.com",
    "shipping": {"name": " Sara ", "line1": "12 MG Road", "city": "Bengaluru", "country": "IN", "postcode": "560 001"},
    "lines": [{"sku": "BOK-0001", "qty": 2, "unit_price_cents": 4200},
              {"sku": "MUS-0001", "qty": 1, "unit_price_cents": 2800}],
    "couponCode": "WELCOME",
}


def idem() -> dict:
    return {"Idempotency-Key": str(uuid.uuid4())}


def test_create_order_normalises_and_computes(client: TestClient) -> None:
    r = client.post("/orders", json=GOOD, headers=idem())
    assert r.status_code == 201, r.text
    body = r.json()
    assert body["email"] == "sara@example.com"  # field_validator
    assert body["shipping"]["name"] == "Sara"  # str_strip_whitespace
    assert body["shipping"]["postcode"] == "560001"  # BeforeValidator + AfterValidator
    assert body["total_cents"] == 2 * 4200 + 2800  # computed_field
    assert r.headers["location"] == f"/orders/{body['id']}"


def test_nested_errors_have_json_pointers(client: TestClient) -> None:
    bad = {**GOOD, "lines": [{"sku": "bok-1", "qty": 0, "unit_price_cents": "4200"}],
           "shipping": {**GOOD["shipping"], "postcode": "056001"}}
    r = client.post("/orders", json=bad, headers=idem())
    assert r.status_code == 422
    assert sorted(problem_codes(r.json())) == sorted([
        ("body", "#/shipping/postcode", "value_error"),
        ("body", "#/lines/0/sku", "string_pattern_mismatch"),
        ("body", "#/lines/0/qty", "greater_than_equal"),
        ("body", "#/lines/0/unit_price_cents", "int_type"),  # strict=True: no "4200" -> 4200
    ])


def test_extra_body_field_is_forbidden(client: TestClient) -> None:
    r = client.post("/orders", json={**GOOD, "is_admin": True}, headers=idem())
    assert problem_codes(r.json()) == [("body", "#/is_admin", "extra_forbidden")]


def test_alias_is_the_wire_name(client: TestClient) -> None:
    body = {k: v for k, v in GOOD.items() if k != "couponCode"}
    r = client.post("/orders", json={**body, "coupon": "WELCOME"}, headers=idem())
    assert problem_codes(r.json()) == [("body", "#/coupon", "extra_forbidden")]


def test_model_validator_cross_field(client: TestClient) -> None:
    dup = {**GOOD, "lines": [GOOD["lines"][0], GOOD["lines"][0]]}
    r = client.post("/orders", json=dup, headers=idem())
    assert problem_codes(r.json()) == [("body", "#", "value_error")]


def test_datetime_parsing_and_timezone_rule(client: TestClient) -> None:
    naive = client.post("/orders", json={**GOOD, "deliver_after": "2099-01-01T09:00:00"}, headers=idem())
    assert problem_codes(naive.json()) == [("body", "#/deliver_after", "value_error")]
    garbage = client.post("/orders", json={**GOOD, "deliver_after": "next tuesday"}, headers=idem())
    assert problem_codes(garbage.json())[0][2] == "datetime_from_date_parsing"
    ok = client.post("/orders", json={**GOOD, "deliver_after": "2099-01-01T09:00:00+05:30"}, headers=idem())
    assert ok.status_code == 201


def test_gift_card_luhn_checksum(client: TestClient) -> None:
    ok = client.post("/orders", json={**GOOD, "gift_card": "6036 0000 0012 3450"}, headers=idem())
    assert ok.status_code == 201
    typo = client.post("/orders", json={**GOOD, "gift_card": "6036 0000 0012 3405"}, headers=idem())
    assert problem_codes(typo.json()) == [("body", "#/gift_card", "value_error")]
    assert "Luhn" in typo.json()["errors"][0]["detail"]


def test_postcode_rule_depends_on_country(client: TestClient) -> None:
    for country, postcode, expected in [("IR", "13145-67890", "1314567890"), ("GB", "sw1a1aa", "SW1A 1AA")]:
        addr = {**GOOD["shipping"], "country": country, "postcode": postcode}
        r = client.post("/addresses/validate", json=addr)
        assert r.status_code == 200 and r.json()["postcode"] == expected
    r = client.post("/addresses/validate", json={**GOOD["shipping"], "country": "GB", "postcode": "560001"})
    assert problem_codes(r.json()) == [("body", "#/postcode", "value_error")]


def test_header_required_with_the_body(client: TestClient) -> None:
    r = client.post("/orders", json=GOOD)
    assert problem_codes(r.json()) == [("header", "idempotency-key", "missing")]


def test_out_of_stock_is_a_custom_exception(client: TestClient) -> None:
    r = client.post("/orders", json={**GOOD, "lines": [{"sku": "GAM-0001", "qty": 1, "unit_price_cents": 3000}]},
                    headers=idem())
    assert r.status_code == 409
    assert r.headers["content-type"] == "application/problem+json"
    assert r.json() == {"type": "https://shop.example/problems/out-of-stock", "title": "Not enough stock",
                        "status": 409, "instance": "/orders", "detail": "GAM-0001: 0 left, 1 requested",
                        "sku": "GAM-0001", "available": 0}


def test_patch_exclude_unset(client: TestClient) -> None:
    created = client.post("/orders", json=GOOD, headers=idem()).json()
    r = client.patch(f"/orders/{created['id']}", json={"email": "new@example.com"})
    assert r.status_code == 200
    assert r.json()["email"] == "new@example.com"
    assert r.json()["shipping"]["postcode"] == "560001"  # untouched: not in exclude_unset dump


def test_patch_null_on_non_nullable_field_is_422_and_changes_nothing(client: TestClient) -> None:
    created = client.post("/orders", json=GOOD, headers=idem()).json()
    for body, pointer in [({"email": None}, "#/email"), ({"shipping": None}, "#/shipping")]:
        r = client.patch(f"/orders/{created['id']}", json={**body, "note": "x"})
        assert r.status_code == 422, r.text
        assert [(e["pointer"], e["code"]) for e in r.json()["errors"]] == [(pointer, "string_type" if "email" in body else "model_type")]
    assert client.app.state.orders[uuid.UUID(created["id"])]["email"] == "sara@example.com"  # not mutated
    assert client.app.state.orders[uuid.UUID(created["id"])]["shipping"]["postcode"] == "560001"


def test_json_pointer_escapes_tilde_and_slash(client: TestClient) -> None:
    r = client.post("/orders", json={**GOOD, "a/b~c": 1}, headers=idem())
    assert [e["pointer"] for e in r.json()["errors"]] == ["#/a~1b~0c"]  # RFC 6901


def test_multiple_body_parameters_and_embed(client: TestClient) -> None:
    cart = uuid.uuid4()
    line = {"sku": "BOK-0001", "qty": 1, "unit_price_cents": 4200}
    r = client.post(f"/carts/{cart}/items?dry_run=1", json={"line": line, "gift_note": "Happy birthday"})
    assert r.status_code == 201 and r.json()["dry_run"] is True and r.json()["gift_note"] == "Happy birthday"
    flat = client.post(f"/carts/{cart}/items", json=line)  # the model's fields at top level
    assert ("body", "#/line", "missing") in problem_codes(flat.json())
    assert client.post("/wishlist", json={"line": line}).json() == {"saved": "BOK-0001"}
    assert problem_codes(client.post("/wishlist", json=line).json()) == [("body", "#/line", "missing")]


def test_malformed_json(client: TestClient) -> None:
    r = client.post("/addresses/validate", content=b'{"name": "x"', headers={"content-type": "application/json"})
    assert problem_codes(r.json()) == [("body", "#/12", "json_invalid")]


def test_database_check_is_the_last_line(client: TestClient) -> None:
    shop = client.app.state.shop
    with pytest.raises(sqlite3.IntegrityError, match="CHECK constraint failed"):
        shop.raw_insert_line("x", "BOK-0001", 0)
py
from __future__ import annotations

import uuid

from fastapi.testclient import TestClient

from tests.conftest import problem_codes

LOGIN = {"username": "sara", "password": "correct horse"}


def test_login_sets_hardened_cookie(client: TestClient) -> None:
    r = client.post("/session", data=LOGIN)
    assert r.status_code == 200
    cookie = r.headers["set-cookie"]
    assert cookie.startswith("session_id=")
    for flag in ("HttpOnly", "Secure", "SameSite=lax", "Path=/"):
        assert flag in cookie
    assert "Max-Age" not in cookie  # session cookie unless "remember" is ticked
    remembered = client.post("/session", data={**LOGIN, "remember": "on"})
    assert "Max-Age=2592000" in remembered.headers["set-cookie"]


def test_cookie_model_reads_the_session(client: TestClient) -> None:
    client.post("/session", data=LOGIN)  # the client's cookie jar keeps session_id
    r = client.get("/session/me")
    assert r.status_code == 200 and r.json() == {"user": "sara", "theme": "light"}


def test_secure_cookie_is_not_sent_over_http(http_client: TestClient) -> None:
    http_client.post("/session", data=LOGIN)
    r = http_client.get("/session/me")
    assert r.status_code == 422
    assert problem_codes(r.json()) == [("cookie", "session_id", "missing")]


def test_cookie_model_validation(client: TestClient) -> None:
    client.cookies.set("session_id", "short")
    client.cookies.set("theme", "neon")
    r = client.get("/session/me")
    assert sorted(problem_codes(r.json())) == [("cookie", "session_id", "string_too_short"),
                                               ("cookie", "theme", "literal_error")]


def test_preferences_cookie_is_readable_by_js(client: TestClient) -> None:
    r = client.put("/preferences", json={"theme": "dark"})
    assert r.headers["set-cookie"] == "theme=dark; Max-Age=31536000; Path=/; SameSite=lax; Secure"


def test_logout_expires_the_cookie(client: TestClient) -> None:
    client.post("/session", data=LOGIN)
    r = client.delete("/session")
    assert r.status_code == 204
    assert 'session_id=""' in r.headers["set-cookie"] and "Max-Age=0" in r.headers["set-cookie"]


def test_header_model_underscores_and_duplicates(client: TestClient) -> None:
    rid = str(uuid.uuid4())
    r = client.get("/client", headers=[("X-Request-ID", rid), ("X-Client-Version", "2.4.1"),
                                       ("X-Feature", "dark-mode"), ("X-Feature", "beta"),
                                       ("Accept-Language", "fa-IR")])
    assert r.status_code == 200
    assert r.json() == {"x_request_id": rid, "x_client_version": "2.4.1", "accept_language": "fa-IR",
                        "x_feature": ["dark-mode", "beta"]}


def test_header_model_errors(client: TestClient) -> None:
    r = client.get("/client", headers={"X-Request-ID": "not-a-uuid", "X-Client-Version": "two"})
    # On 0.128.8 the loc uses the Python field name; FastAPI 0.152.0+ reports the HTTP header name.
    assert sorted(problem_codes(r.json())) == [("header", "x_client_version", "string_pattern_mismatch"),
                                               ("header", "x_request_id", "uuid_parsing")]


def test_authorization_header_preview(client: TestClient) -> None:
    r = client.get("/account")
    assert r.status_code == 401 and r.headers["www-authenticate"] == "Bearer"
    r = client.get("/account", headers={"Authorization": "Bearer abc.def.ghi", "User-Agent": "shop-ios/2.4"})
    assert r.json() == {"token_length": 11, "user_agent": "shop-ios/2.4", "legacy": None}


def test_convert_underscores_false_reads_the_literal_name(client: TestClient) -> None:
    r = client.get("/account", headers={"Authorization": "Bearer t", "x_legacy_token": "old"})
    assert r.json()["legacy"] == "old"
    r = client.get("/account", headers={"Authorization": "Bearer t", "x-legacy-token": "old"})
    assert r.json()["legacy"] is None
py
from __future__ import annotations

import uuid

from fastapi.testclient import TestClient

from tests.conftest import problem_codes

PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 100
JPEG = b"\xff\xd8\xff\xe0" + b"\x00" * 100


def test_form_fields_validate_like_query_params(client: TestClient) -> None:
    r = client.post("/session", data={"username": "sa", "password": "short"})
    assert sorted(problem_codes(r.json())) == [("body", "#/password", "string_too_short"),
                                               ("body", "#/username", "string_too_short")]


def test_json_sent_to_a_form_endpoint(client: TestClient) -> None:
    r = client.post("/session", json={"username": "sara", "password": "correct horse"})
    assert r.status_code == 422  # form fields are read from the form body only
    assert ("body", "#/username", "missing") in problem_codes(r.json())


def test_upload_files_with_form_field(client: TestClient) -> None:
    order = uuid.uuid4()
    r = client.post(f"/returns/{order}/photos", data={"reason": "The box arrived crushed"},
                    files=[("photos", ("a.png", PNG, "image/png")), ("photos", ("b.jpg", JPEG, "image/jpeg"))])
    assert r.status_code == 201, r.text
    assert r.json()["photos"] == [{"filename": "a.png", "content_type": "image/png", "bytes": 108},
                                  {"filename": "b.jpg", "content_type": "image/jpeg", "bytes": 104}]


def test_content_type_is_not_trusted(client: TestClient) -> None:
    r = client.post(f"/returns/{uuid.uuid4()}/photos", data={"reason": "The box arrived crushed"},
                    files=[("photos", ("evil.png", b"<?php system($_GET['c']);", "image/png"))])
    assert r.status_code == 415


def test_about_blank_title_is_the_reason_phrase(client: TestClient) -> None:
    r = client.post(f"/returns/{uuid.uuid4()}/photos", data={"reason": "The box arrived crushed"},
                    files=[("photos", ("evil.png", b"<?php", "image/png"))])
    assert r.status_code == 415
    assert r.json()["type"] == "about:blank" and r.json()["title"] == "Unsupported Media Type"


def test_starlette_multipart_part_limit(client: TestClient) -> None:
    # Starlette's request.form() defaults: max_files=1000, max_fields=1000, max_part_size=1 MiB (non-file parts).
    r = client.post(f"/returns/{uuid.uuid4()}/photos", files={"reason": (None, "x" * (1024 * 1024 + 1)),
                                                              "photos": ("a.png", PNG, "image/png")})
    assert r.status_code == 400
    assert r.json()["detail"] == "Part exceeded maximum size of 1024KB."


def test_size_limit(client: TestClient) -> None:
    big = PNG + b"\x00" * (2 * 1024 * 1024)
    r = client.post(f"/returns/{uuid.uuid4()}/photos", data={"reason": "The box arrived crushed"},
                    files=[("photos", ("big.png", big, "image/png"))])
    assert r.status_code == 413


def test_missing_file_and_short_reason(client: TestClient) -> None:
    r = client.post(f"/returns/{uuid.uuid4()}/photos", data={"reason": "bad"})
    assert sorted(problem_codes(r.json())) == [("body", "#/photos", "missing"),
                                               ("body", "#/reason", "string_too_short")]
py
"""The default 422 shape, what it leaks, and the Problem Details replacement."""

from __future__ import annotations

from typing import Annotated, List, Optional

from fastapi import FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from pydantic import TypeAdapter, ValidationError

from app.models import ClientHeaders, OrderLine


def _default_app() -> FastAPI:
    """No custom handlers: FastAPI's own 422 body."""
    bare = FastAPI()

    @bare.get("/client")
    def client_info(headers: Annotated[ClientHeaders, Header()]) -> dict:
        return {}

    @bare.get("/items/{item_id}")
    def item(item_id: int, q: Optional[str] = None) -> dict:
        if item_id == 0:
            raise HTTPException(404, detail="Item not found")
        return {"item_id": item_id}

    return bare


def test_default_validation_body() -> None:
    r = TestClient(_default_app()).get("/items/abc")
    assert r.status_code == 422
    assert r.headers["content-type"] == "application/json"
    assert r.json() == {"detail": [{"type": "int_parsing", "loc": ["path", "item_id"],
                                    "msg": "Input should be a valid integer, unable to parse string as an integer",
                                    "input": "abc"}]}


def test_default_http_exception_body() -> None:
    r = TestClient(_default_app()).get("/items/0")
    assert r.status_code == 404 and r.json() == {"detail": "Item not found"}


def test_default_header_model_error_echoes_every_header() -> None:
    r = TestClient(_default_app()).get("/client", headers={"Authorization": "Bearer SECRET"})
    err = r.json()["detail"][0]
    assert err["loc"] == ["header", "x_request_id"] and err["type"] == "missing"
    assert err["input"]["authorization"] == "Bearer SECRET"  # the token is in the error body


def test_problem_details_do_not_echo_input(client: TestClient) -> None:
    r = client.get("/client", headers={"Authorization": "Bearer SECRET"})
    assert r.status_code == 422
    assert "SECRET" not in r.text
    body = r.json()
    assert body["type"] == "https://shop.example/problems/validation"
    assert body["title"] == "Your request is not valid." and body["status"] == 422
    assert body["instance"] == "/client"


def test_router_404_and_405_use_the_same_envelope(client: TestClient) -> None:
    r = client.get("/nope")
    assert r.status_code == 404 and r.headers["content-type"] == "application/problem+json"
    assert r.json() == {"type": "about:blank", "title": "Not Found", "status": 404, "instance": "/nope",
                        "detail": "Not Found"}
    r = client.delete("/products")
    assert r.status_code == 405 and r.json()["title"] == "Method Not Allowed"
    assert r.headers["allow"] == "GET"


def test_pydantic_validation_error_outside_fastapi() -> None:
    try:
        OrderLine(sku="BOK-0001", qty=100, unit_price_cents=1)
    except ValidationError as e:
        assert e.error_count() == 1
        assert e.errors(include_url=False)[0]["type"] == "less_than_equal"
    else:  # pragma: no cover
        raise AssertionError("expected ValidationError")


def test_type_adapter_validates_without_a_model() -> None:
    adapter = TypeAdapter(List[OrderLine])
    lines = adapter.validate_json('[{"sku": "BOK-0001", "qty": "2", "unit_price_cents": 4200}]')
    assert lines[0].qty == 2  # lax mode: "2" -> 2 for a non-strict int
    assert adapter.json_schema()["items"]["$ref"] == "#/$defs/OrderLine"
py
"""What each declaration puts into /openapi.json (OpenAPI 3.1, JSON Schema 2020-12)."""

from __future__ import annotations

from fastapi.testclient import TestClient


def _spec(client: TestClient) -> dict:
    return client.get("/openapi.json").json()


def _params(spec: dict, path: str, method: str = "get") -> dict:
    return {p["name"]: p for p in spec["paths"][path][method].get("parameters", [])}


def test_query_model_is_flattened_into_parameters(client: TestClient) -> None:
    params = _params(_spec(client), "/products")
    assert list(params) == ["category", "q", "min_price", "max_price", "tag", "order_by", "desc", "limit", "offset"]
    assert params["limit"]["schema"] == {"type": "integer", "maximum": 100, "minimum": 1, "default": 20, "title": "Limit"}
    assert params["order_by"]["schema"]["enum"] == ["id", "price", "name"]
    assert params["tag"]["schema"]["type"] == "array"


def test_query_metadata(client: TestClient) -> None:
    params = _params(_spec(client), "/lookup")
    assert "item-query" in params and "q" not in params  # alias
    assert params["item-query"]["description"] == "Matched against the product name"
    assert params["item-query"]["schema"]["examples"] == ["chess"]
    assert params["sort"]["deprecated"] is True
    assert "debug" not in params  # include_in_schema=False
    assert params["min_rating"]["schema"]["exclusiveMinimum"] == 0
    assert params["max_weight_g"]["schema"]["exclusiveMaximum"] == 30000


def test_header_and_cookie_parameters(client: TestClient) -> None:
    spec = _spec(client)
    headers = _params(spec, "/client")
    assert sorted(headers) == ["accept-language", "x-client-version", "x-feature", "x-request-id"]
    assert headers["x-request-id"]["in"] == "header" and headers["x-request-id"]["schema"]["format"] == "uuid"
    cookies = _params(spec, "/session/me")
    assert {n: p["in"] for n, p in cookies.items()} == {"session_id": "cookie", "theme": "cookie"}
    assert _params(spec, "/account")["x_legacy_token"]["in"] == "header"  # convert_underscores=False


def test_bodies(client: TestClient) -> None:
    spec = _spec(client)
    order_body = spec["paths"]["/orders"]["post"]["requestBody"]["content"]["application/json"]["schema"]
    assert order_body == {"$ref": "#/components/schemas/OrderIn"}
    schemas = spec["components"]["schemas"]
    assert "couponCode" in schemas["OrderIn"]["properties"]  # alias on the wire
    assert schemas["OrderIn"]["additionalProperties"] is False  # extra="forbid"
    assert schemas["OrderIn"]["examples"][0]["shipping"]["postcode"] == "560 001"
    assert "total_cents" not in schemas["OrderIn"]["properties"]  # computed: output only
    cart = spec["paths"]["/carts/{cart_id}/items"]["post"]["requestBody"]["content"]["application/json"]["schema"]
    assert cart["$ref"].startswith("#/components/schemas/Body_add_to_cart")  # several bodies -> one object
    form = spec["paths"]["/session"]["post"]["requestBody"]["content"]
    assert list(form) == ["application/x-www-form-urlencoded"]
    upload = spec["paths"]["/returns/{order_id}/photos"]["post"]["requestBody"]["content"]
    assert list(upload) == ["multipart/form-data"]


def test_tags_and_operation_deprecation(client: TestClient) -> None:
    spec = _spec(client)
    assert [t["name"] for t in spec["tags"]] == ["catalog", "orders", "session", "returns"]  # openapi_tags
    assert spec["paths"]["/orders"]["post"]["tags"] == ["orders"]
    legacy = spec["paths"]["/catalog/search"]["get"]
    assert legacy["deprecated"] is True and legacy["summary"] == "Old search, use GET /products"
    assert client.get("/catalog/search?q=go").json() == {"q": "go", "use_instead": "/products"}  # still served


def test_error_responses_documented(client: TestClient) -> None:
    responses = _spec(client)["paths"]["/orders"]["post"]["responses"]
    assert set(responses) == {"201", "409", "422"}
    problem_ref = {"$ref": "#/components/schemas/Problem"}
    assert responses["422"]["content"]["application/problem+json"]["schema"] == problem_ref
    assert responses["422"]["content"]["application/json"]["schema"] == problem_ref  # added by `model`
    assert responses["409"]["description"] == "Conflict, e.g. out of stock"
    plain = _spec(client)["paths"]["/wishlist"]["post"]["responses"]["422"]
    assert plain["content"]["application/json"]["schema"] == {"$ref": "#/components/schemas/HTTPValidationError"}

The project file pins the stack (see the version note at the top of the page):

toml
[project]
name = "request-validation-cookies-headers"
version = "0.1.0"
description = "Snippets for the Request Validation chapter: query/body models, cookies, headers, forms, files, custom validators, Problem Details"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. On 3.12+ you can move to the latest releases.
requires-python = ">=3.9"
dependencies = [
    "fastapi==0.128.8",
    # Pinned explicitly: the versions every "real run" on the page used.
    "starlette==0.49.3",
    "pydantic==2.13.5",
    # Form() and File()/UploadFile need it; without it FastAPI raises RuntimeError at import.
    # 0.0.20 is the newest release that installs on Python 3.9 (current releases need 3.11+).
    "python-multipart==0.0.20",
    "uvicorn==0.39.0",
    # Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
    "eval-type-backport==0.4.0; python_version < '3.10'",
]

[project.optional-dependencies]
test = [
    "httpx==0.28.1",
    "pytest==8.4.2",
]

[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[tool.setuptools]
packages = ["app"]

[tool.fastapi]
entrypoint = "app.main:app"

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]

The Python angle ​

Three Python features carry this chapter. typing.Annotated (PEP 593) lets one parameter carry several pieces of metadata at once: Annotated[str, BeforeValidator(strip), AfterValidator(check_pin), Path(description=...)]. FastAPI takes its own markers (Query, Path, Header, Cookie, Body, Form, File), and Pydantic takes the validators. Because the type alias IndianPIN = Annotated[str, ...] is an ordinary Python object, it can be reused in a path parameter, a body field and a test. Exceptions as control flow: a validator signals failure by raising ValueError (or AssertionError, or Pydantic's PydanticCustomError for a custom type). Pydantic catches it, records it and keeps validating the other fields. An endpoint signals failure by raising HTTPException or a domain exception class that a handler maps to a status. Classes as schemas: a BaseModel subclass is at once a runtime validator, a typed object for your editor and mypy, and a JSON Schema for OpenAPI. @classmethod field validators, @property + @computed_field and model_config = ConfigDict(...) are plain class syntax. On Python 3.11+ write class Category(StrEnum). The snippets use class Category(str, Enum), which validates the same and runs on 3.9. list[str] works at runtime from Python 3.9 and str | None from 3.10; the snippets keep from __future__ import annotations with eval-type-backport so that the modern syntax also works on 3.9, and use List/Optional in model fields only to stay readable for 3.9 readers. Pydantic's validator docs list ValueError, AssertionError ("using the assert statement also works", but asserts are skipped under python -O) and PydanticCustomError as the ways to fail.

The concept catalogue ​

One HTTP request, four sources, one loc prefix eachThe HTTP requestRequest linePOST /carts/7d0e…/items?dry_run=1 HTTP/1.1Header blockContent-Type: application/jsonX-Request-ID: 2f6c…X-Feature: a X-Feature: bCookie: session_id=…; theme=darkBody{"line": {"sku": "BOK-0001", …}, "gift_note": "Happy birthday"}or: username=sara&password=…or: multipart parts with filespathcart_id: UUID / Annotated[int, Path(ge=1)]loc ["path", …]querydry_run: bool = False / Annotated[M, Query()]loc ["query", …]headerAnnotated[str, Header()] x_request_id → X-Request-IDloc ["header", …]cookieAnnotated[str, Cookie()] / Annotated[M, Cookie()]loc ["cookie", …]JSON bodyline: OrderLine + Body(); embed=True wraps oneloc ["body", …]form / filesForm(), File(), UploadFile (python-multipart)loc ["body", …]

Query parameters: optional, required, default Must-know ​

In plain words: A function parameter that is not in the path and has a simple type is a query parameter. If it has no default it is a required query parameter; if it has a default it is optional with that value; a default of None makes it an optional query parameter whose absence you can detect.

Common misunderstanding: "q: str | None is optional." The docs: "The type str | None allows None as a Python value, but it does not make a query parameter optional. Without a default value, the parameter is still required." Second one: "?q=null sends None." It sends the string "null": "Query parameter values arrive as strings and have no built-in representation of None."

Definition: FastAPI reads parameters by name from scope["query_string"]. A parameter is required when it has no default (or Query() with no default inside Annotated). The default value, not the type, decides optionality: "Having a default value of any type, including None, makes the parameter optional (not required)." A list type needs Query() explicitly, "otherwise it would be interpreted as a request body". Bare list "won't check the contents of the list".

     GET /lookup?item-query=chess&min_rating=4.5        (real run, snippet /lookup)
1    id          absent          -> None                 (default None: optional)
2    item-query  "chess"         -> q = "chess"          (alias; length 3..50; pattern ok)
3    min_rating  "4.5"           -> 4.5                  (float, 0 < x <= 5)
4    max_weight_g absent         -> 29999                (default)
5    sort, debug absent          -> None, False
6    200 {"id": null, "q": "chess", "min_rating": 4.5, ...}
     GET /q   (probe: req: str = Query(...), no value sent)
7    422 {"type": "missing", "loc": ["query", "req"], "msg": "Field required", "input": null}

Real scenario: pagination (?limit=20&offset=40); filters that are usually absent (?category=books); a required search term (/search?q=) where an empty search makes no sense; feature switches (?include=lines); multi-select (?tag=sale&tag=new).

DeclarationAbsent?x= (empty)ValidRequired?
x: str422 missing"""v"Yes
x: str = "all""all""""v"No
x: str | None = NoneNone"""v"No
x: str | None (no default)422 missing"""v"Yes
x: Annotated[str, Query(min_length=3)]422 missing422 string_too_short"abc"Yes
x: Annotated[list[str], Query()] = [][][""]?x=a&x=b → ["a", "b"]No
x: bool = FalseFalse422 bool_parsingyes/on/1/true → TrueNo

(The first four rows and the list and bool rows were measured in the Fundamentals chapter on the same pins; the min_length row is in this chapter's tests.)

Fix / how to use it: decide per parameter: required (no default), optional with a meaningful default, or optional with None. Never rely on ?x=null. When four or more parameters travel together, move them into a query parameter model.

Query constraints Must-know ​

In plain words: Query(...) inside Annotated adds rules to a query parameter: lengths and a regex for strings, bounds for numbers, a maximum count for lists. FastAPI checks them, reports every failing parameter (for a scalar parameter, the first constraint it fails), and writes them into the docs.

Common misunderstanding: "le=100 silently caps the value." It refuses it with 422 less_than_equal; nothing is clamped. Another: "gt/ge are the same." gt=0 refuses 0 (greater_than); ge=0 accepts it. The snippet's min_rating: Query(gt=0, le=5) refused 0 with greater_than and its max_weight_g: Query(ge=1, lt=30000) refused 30000 with less_than (real).

Definition: The query constraints shared by Query, Path, Header, Cookie, Body, Form and Field are min_length, max_length and pattern for strings (also min_length/max_length for lists) and ge gt le lt plus multiple_of for numbers. FastAPI passes them to Pydantic, so the error type is Pydantic's. The docs show the pattern meaning in plain words: "^: starts with the following characters … $: ends there".

     GET /products?limit=0&offset=-1&order_by=rating&category=toys&q=x   (real, 5 errors at once)
1    category  "toys"    -> enum                 Input should be 'books', 'games' or 'music'
2    q         "x"       -> string_too_short     min_length=2
3    order_by  "rating"  -> literal_error        Literal["id", "price", "name"]
4    limit     "0"       -> greater_than_equal   ge=1
5    offset    "-1"      -> greater_than_equal   ge=0
6    RequestValidationError(5 errors) -> handler -> 422, the function never runs

Real scenario: limit capped at 100 so nobody downloads the catalogue in one call; a search box that refuses one-character queries (an index scan for LIKE '%a%'); SKU format ^[A-Z]{3}-[0-9]{4}$; ?tag= limited to five values; a page_size that must be a multiple_of=10 for a cache key scheme.

ConstraintTypes422 typeJSON Schema / OpenAPI keyword
min_length=2str / liststring_too_short / too_shortminLength / minItems
max_length=50str / liststring_too_long / too_long (real for ?tag= × 6)maxLength / maxItems
pattern=r"^[a-z]{3}$"strstring_pattern_mismatchpattern
ge=1 / gt=0numbersgreater_than_equal / greater_thanminimum / exclusiveMinimum
le=100 / lt=30000numbersless_than_equal / less_thanmaximum / exclusiveMaximum
multiple_of=10numbersmultiple_ofmultipleOf
strict=Trueanyint_type for "5" on an int (real: query values arrive as strings, so strict numeric or bool parameters always fail; a strict str parameter is fine, ?q=abc → 200, real)none

Fix / how to use it: put a bound on every number and a length on every string that reaches SQL, a log line or another service. Do not add strict=True to numeric, boolean, UUID or date query/path/header/cookie parameters: they arrive as text and strict mode refuses the string-to-type conversion (Pydantic's conversion table allows str → str in strict mode, so a strict string parameter works). Keep the regex anchored (^…$); an unanchored pattern matches a substring.

Parameter metadata: alias, title, description, examples, deprecated, include_in_schema Important ​

In plain words: Some arguments of Query() change only the documentation (title, description, examples, deprecated), one changes the wire name (alias), and one hides the parameter from the docs (include_in_schema=False).

Common misunderstanding: "With alias="item-query" both ?item-query= and ?q= work." Only the alias is read: the snippet's ?q=chess gave q = None (real). Another: "deprecated=True turns the parameter off" or "include_in_schema=False protects it." Both still accept the value (the snippet test sends ?debug=yes&sort=name and gets both).

Definition: alias is "what will be used to find the parameter value", for names like item-query that are not Python identifiers. deprecated=True is for a parameter you "have to leave … there a while because there are clients using it", shown struck through in the docs. include_in_schema=False excludes the parameter "from the generated OpenAPI schema (and thus, from the automatic documentation systems)". examples is a list (the JSON Schema 2020-12 keyword); the old singular example is deprecated in OpenAPI 3.1.

     /openapi.json for GET /lookup   (real, abbreviated)
1    {"name": "item-query", "in": "query", "required": false,
2     "schema": {"anyOf": [{"type": "string", "minLength": 3, ...}, {"type": "null"}],
3                "title": "Search text", "description": "Matched against the product name",
4                "examples": ["chess"]}, "description": "Matched against the product name"}
5    {"name": "sort", ..., "deprecated": true}
6    (no entry for "debug": include_in_schema=False)

Real scenario: a header-like query name (page-size, item-query) kept for compatibility with a JavaScript client; renaming sort to order_by with a deprecation window; a debug=1 switch only for support staff; examples that make "Try it out" work on the first click.

ArgumentEffect on the requestEffect on OpenAPI
alias="item-query"Only ?item-query= is readname: item-query
title="Search text"Noneschema.title
description="..."Nonedescription on the parameter and the schema
examples=["chess"]Noneschema.examples (Swagger UI prefills it)
deprecated=TrueNone, still accepteddeprecated: true, struck through in /docs
include_in_schema=FalseNone, still acceptedParameter absent

Fix / how to use it: describe every public parameter; use alias only for wire names that are not identifiers (or keep a field name and set alias in a model); deprecate before removing; never treat include_in_schema=False as access control (that is a dependency with authentication).

Annotated validators: AfterValidator and BeforeValidator Must-know ​

In plain words: When pattern and bounds are not enough, put a function into Annotated. AfterValidator(fn) gets a value that is already a valid str/int and either returns it (possibly changed) or raises ValueError. BeforeValidator(fn) gets the raw input first, typically to normalise it.

Common misunderstanding: "A validator can look up the database." The FastAPI docs draw the line: "If you need to do any type of validation that requires communicating with any external component, like a database or another API, you should instead use FastAPI Dependencies … These custom validators are for things that can be checked with only the same data provided in the request." Another: "BeforeValidator is just an earlier AfterValidator." It receives anything (an int, None, a dict), so it must type-check its input: Pydantic's docs say before validators "have to deal with the raw input".

Definition: Pydantic: "After validators: run after Pydantic's internal validation. They are generally more type safe and thus easier to implement." "Before validators: run before Pydantic's internal parsing and validation (e.g. coercion of a str to an int)." Pydantic also has plain validators ("terminate validation immediately after returning") and wrap validators ("the most flexible of all"). Several validators in one Annotated run in a fixed order; Pydantic's "Ordering of validators" section: "before and wrap validators are run from right to left, and after validators are then run from left to right". FastAPI: "You can achieve that using Pydantic's AfterValidator inside of Annotated." A ValueError message becomes the error msg prefixed with Value error, .

     GET /postcodes/in/560%20001     IndianPIN = Annotated[str, BeforeValidator(_strip_spaces), AfterValidator(check_indian_pin)]
1    raw path value       "560 001"
2    BeforeValidator      "560001"                   (spaces and hyphens removed; an int would become a str)
3    core str validation  ok
4    AfterValidator       regex ^[1-9][0-9]{5}$ ok -> "560001"
5    200 {"pin": "560001", "zone": "South", "sorting_district": "560"}      (real)
     GET /postcodes/in/056001
6    AfterValidator raises ValueError("an Indian PIN code is 6 digits and cannot start with 0")
7    422 {"location": "path", "parameter": "pin", "code": "value_error",
          "detail": "Value error, an Indian PIN code is 6 digits and cannot start with 0"}   (real)

Real scenario: ISBN/EAN prefixes (isbn-, ean-, the docs' example uses isbn-/imdb-); postcodes and phone numbers normalised before the check; trimming and lower-casing an email; a coupon code upper-cased; a "1,2,3" comma list split into a list in a BeforeValidator; a checksum on a gift-card or IBAN.

HookInput it seesGood forAvoid
BeforeValidatorRaw value, any typeNormalising, splitting, unwrappingBusiness rules (the type is not checked yet)
AfterValidatorTyped, constrained valueChecksums, prefixes, semantic checksI/O (database, HTTP)
PlainValidatorRaw value; no core validation after itFully custom parsingLosing the type check by accident
WrapValidatorRaw value + a handler to call core validationFallbacks, timing, re-raising with contextSimple checks (use After)
Dependency (Depends)Already validated parametersDatabase lookups, permissions, rate limitsPure format checks

Fix / how to use it: define the validated type once as an alias (IndianPIN, GiftCardNumber) and reuse it everywhere; normalise in BeforeValidator, decide in AfterValidator; write the error message for the client ("cannot start with 0", not "regex failed"); move anything that needs I/O to a dependency.

Query parameter models and extra="forbid" Must-know ​

In plain words: A Pydantic model for query parameters groups related parameters: declare filters: Annotated[ProductFilter, Query()] and FastAPI fills the model's fields from the query string. With the extra forbid setting (extra="forbid"; the docs' section is "Forbid Extra Query Parameters"), a parameter the model does not know (?tool=plumbus) is a 422 instead of being silently ignored.

Common misunderstanding: "The model appears as one nested JSON parameter." No: OpenAPI lists every field as a separate query parameter (real: category, q, min_price, max_price, tag, order_by, desc, limit, offset). The URL stays flat. Second: "I can use two query models, or Filter | None = None." Not on the pinned 0.128.8. Two models in one function both answered 422 missing (real), and an optional model failed at import with AssertionError: Query parameter 's' must be one of the supported types (real). Combining models arrived in 0.157.0 and optional models in 0.159.0.

Definition: "If you have a group of query parameters that are related, you can create a Pydantic model to declare them … This is supported since FastAPI version 0.115.0." Pydantic's extra setting decides what happens to unknown keys: "'ignore': Providing extra data is ignored (the default). 'forbid': Providing extra data is not permitted. 'allow': Providing extra data is allowed and stored in the __pydantic_extra__ dictionary attribute." Model validators work on query models too. The snippet's price_range rule produced a 422 with loc: ["query"] (no field name, real).

     GET /products?limit=0&tool=plumbus         (real, Uvicorn + curl)
1    FastAPI builds {"limit": "0", "tool": "plumbus"} from the query string
2    ProductFilter.model_validate(...)  extra="forbid"
3      limit: "0" -> 0 -> ge=1 fails        greater_than_equal
4      tool: not a field                    extra_forbidden
5    HTTP/1.1 422 Unprocessable Entity      (Uvicorn's reason phrase; RFC 9110 calls it Unprocessable Content)
     content-type: application/problem+json
     {"errors":[{"location":"query","code":"greater_than_equal","parameter":"limit",...},
                {"location":"query","code":"extra_forbidden","parameter":"tool",...}], ...}

Real scenario: a product listing with ten filters reused by /products and /products/export; a reporting endpoint whose filters must be rejected loudly when misspelt (?form=2026-01-01 instead of ?from=); a shared pagination model; an admin search that logs the validated model as one object.

Behaviour0.128.8 (real)0.157.0+ / 0.159.0+ / 0.160.0+ (release notes)
One model per location per functionWorksWorks
Two models in one functionBoth reported missingCombined; "The request parameters stay at the same level"
Model | None = NoneAssertionError at importOptional group: None if no field sent
Model with extra="forbid" next to individual paramsNot used hereextra "applies to all query parameters, including those declared in other models or dependencies"
model_dump(exclude_unset=True)Defaults count as set (real: fields_set = all fields)0.148.0: "applying a default no longer marks a field as explicitly set"

Fix / how to use it: one query model per endpoint (on any version), extra="forbid" for public APIs so typos surface, cross-field rules in a model_validator, and do not use exclude_unset on parameter models before 0.148.0.

Request body models and Body() Must-know ​

In plain words: A parameter typed as a Pydantic model is read from the JSON body. Body() makes a single value (an int, a str) a body key instead of a query parameter, and Body(embed=True) wraps a single model in a key.

Common misunderstanding: "A JSON body without Content-Type: application/json is refused." On 0.128.8 it was accepted (real: 200). 0.132.0 added strict_content_type, which rejects it by default. Second: "null for a field with a default gives the default." In the pinned version {"note": null} for note: Annotated[str | None, Body(embed=True)] = "default" returned "default" (real). Since 0.151.0, "JSON request bodies now distinguish an explicit null from an omitted value".

Definition: A body parameter is a Pydantic model, a list/dict of models, or any parameter marked with Body(). With exactly one model, the body is the model. With several, FastAPI "will then use the parameter names as keys (field names) in the body". A singular value without Body() is a query parameter: "If you declare it as is, because it is a singular value, FastAPI will assume that it is a query parameter." Body(embed=True) gives the single-model case the same shape. Body accepts the same validation and metadata arguments as Query.

     POST /wishlist   line: Annotated[OrderLine, Body(embed=True)]        (real)
1    {"line": {"sku": "BOK-0001", "qty": 1, "unit_price_cents": 4200}}   -> 200 {"saved": "BOK-0001"}
2    {"sku": "BOK-0001", "qty": 1, "unit_price_cents": 4200}             -> 422 loc ["body", "line"] missing
     POST /addresses/validate   address: Address  (one model, not embedded)
3    {"name": "x"   (truncated JSON)                                    -> 422 json_invalid, loc ["body", 12]

Real scenario: an order (one big model); a "move item" call with a model plus an importance: int body key; a client SDK that always wraps payloads in a key ({"order": {...}}); webhooks whose JSON you validate before trusting.

SignatureExpected bodyNotes
order: OrderIn{...OrderIn fields...}The common case
line: Annotated[OrderLine, Body(embed=True)]{"line": {...}}Same shape as with several bodies
line: OrderLine, gift_note: Annotated[str | None, Body()] = None{"line": {...}, "gift_note": "..."}Multiple body parameters
importance: int (no Body)query ?importance=Singular values default to query
items: list[OrderLine][{...}, {...}]A JSON array as the whole body
payload: dict[str, int]{"a": 1}Arbitrary keys, typed values

Fix / how to use it: one model per body in most endpoints; embed=True when clients send a wrapper key; send and require Content-Type: application/json (on 0.132.0+ it is enforced); do not rely on null meaning "use the default" (it changed in 0.151.0).

Nested models and multiple body parameters Must-know ​

In plain words: A model field can be another model or a list of models; FastAPI validates the whole tree and reports each error with its full path (["body", "lines", 0, "qty"]).

Common misunderstanding: "Nested validation stops at the first bad line." Every line and every nested field is checked; the snippet's bad order produced five errors across shipping, lines[0] and an extra top-level key in one response (real). Another: "Multiple body parameters mean multiple bodies." "A request can only have a single body". FastAPI builds one JSON object whose keys are the parameter names and documents it as one schema (Body_add_to_cart_carts__cart_id__items_post, real).

Definition: Fields may be typed as models, list[Model], set[str], dict[str, Model], unions and so on, to any depth. Constraints apply to the containers too (lines: list[OrderLine] = Field(min_length=1, max_length=50)). The docs: FastAPI "will perform the validation of the compound data, and will document it like that for the OpenAPI schema and automatic docs."

     POST /orders   (real; the Problem Details handler converts loc to a JSON Pointer)
1    shipping.postcode  "056001"     -> value_error          #/shipping/postcode
2    lines[0].sku       "bok-1"      -> string_pattern_mismatch   #/lines/0/sku
3    lines[0].qty       0            -> greater_than_equal   #/lines/0/qty
4    lines[0].unit_price_cents "4200" -> int_type (strict)   #/lines/0/unit_price_cents
5    is_admin           true         -> extra_forbidden      #/is_admin
6    422, "detail": "5 validation error(s)"

Real scenario: an order with addresses and lines; a booking with guests; an invoice with tax lines; a survey with answers keyed by question id (dict[UUID, Answer]); an import endpoint that takes up to 1,000 rows and must say exactly which row failed.

NeedDeclaration
A sub-objectshipping: Address
An optional sub-objectbilling: Address | None = None
A non-empty bounded listlines: list[OrderLine] = Field(min_length=1, max_length=50)
Unique scalar valuestags: set[str] (duplicates collapse silently; use a validator to refuse them)
Unique by a keymodel_validator that compares keys (snippet: unique_skus)
Keyed sub-objectsanswers: dict[UUID, Answer]
Path + body in one callcart_id: UUID, line: OrderLine

Fix / how to use it: model the body as a tree, bound every list, forbid extras on every level (extra is per model, not inherited), and test one error per level so the loc paths are known to the front end.

Field, aliases and partial updates (exclude_unset) Must-know ​

In plain words: Field(...) is to a model field what Query(...) is to a parameter: constraints, a default, a description, examples, an alias. model_dump(exclude_unset=True) returns only the fields the client actually sent, which is what a PATCH needs.

Common misunderstanding: "exclude_none=True is enough for PATCH." It drops fields the client set to null on purpose ("clear my note"). exclude_unset=True keeps an explicit null and drops only absent fields: the probe's {"name": "x", "note": null} dumped as {"name": "x", "note": null} (real). Second: "An alias means both names are accepted." With alias="couponCode" the field name coupon was refused as extra_forbidden (real); accepting both needs populate_by_name (or validate_by_name in newer Pydantic) or AliasChoices.

Definition: Pydantic: "Pydantic keeps track of fields that were explicitly set during instantiation (using the model_fields_set property). Using exclude_unset, any field that was not explicitly provided will be excluded." exclude_defaults excludes values equal to the default; exclude_none excludes None values. alias sets both the validation and serialisation name; validation_alias and serialization_alias set one side each.

     PATCH /orders/{id}  {"email": "new@example.com"}                       (real, test_patch_exclude_unset)
1    OrderPatch(email="new@example.com")        fields_set = {"email"}
2    model_dump(exclude_unset=True)            -> {"email": "new@example.com"}
3    OrderOut.model_validate({**stored, **changes})   re-validated copy; stored only if valid
4    200 {"email": "new@example.com", "shipping": {"postcode": "560001", ...}}

Real scenario: PATCH endpoints; a camelCase JSON API backed by snake_case Python (couponCode); fields renamed without breaking clients (validation_alias=AliasChoices("coupon", "couponCode")); examples per field for the docs; server-generated fields excluded from input models.

Dump optionDropsKeepsUse for
exclude_unset=TrueFields not sentExplicit null, explicit default valuesPATCH
exclude_defaults=TrueFields equal to their defaultChanged valuesCompact output
exclude_none=TrueEvery NoneNon-null valuesOutput where null is noise
by_alias=True—Uses alias namescamelCase output
mode="json"—JSON-safe types (UUID → str)Logging, caching

An all-optional patch model accepts {"email": null}, but an order must have an email. The snippet therefore applies the changes to a copy, re-validates the copy as the full OrderOut model and stores it only if that passes; otherwise it raises RequestValidationError with body-prefixed locations, so the client gets 422 #/email string_type (or #/shipping model_type) and the stored order is unchanged (real, test_patch_null_on_non_nullable_field_is_422_and_changes_nothing).

Fix / how to use it: PATCH = an all-optional model + exclude_unset=True + re-validation of the merged resource + a database update of only those columns. Separate input and output models per resource; the full treatment is in SQLAlchemy 2 & SQLModel.

Model validators: field_validator, model_validator, computed_field Must-know ​

In plain words: @field_validator("email") is a method that checks or transforms one or more fields. @model_validator(mode="after") sees the whole validated model, which is where cross-field rules live. @computed_field adds a derived, read-only field to the output (total_cents).

Common misunderstanding: "A field validator can read any other field." In an after-mode field_validator, info.data holds only the fields validated before this one (declaration order). The snippet's postcode validator can read country only because country is declared above postcode, and it returns early when country itself failed. Second: "A model-level error points at a field." A model_validator error has the model's loc (["body"] for the top level, real), so the client sees "pointer": "#"; raise it on a field (or use a field validator) when the UI must highlight one input.

Definition: Pydantic distinguishes field validators (before, after, plain, wrap) and model validators (before, after, wrap). field_validator methods are @classmethods taking (cls, value, info). A model_validator(mode="after") is an instance method that must return self. @computed_field "can be used to include properties (or cached properties) when serializing a model or dataclass". In FastAPI a computed field shows up in the output schema only: real Range-Output has "length": {..., "readOnly": true}, while Range-Input does not have the field.

     OrderIn validation order for one request
1    email          core str + pattern -> field_validator lower_email -> "sara@example.com"
2    shipping       Address: name (strip) ... country "IN" ... postcode: field_validator reads info.data["country"]
3    lines          each OrderLine: sku pattern, qty 1..99, unit_price_cents strict int
4    deliver_after  datetime parsing -> field_validator: needs tz offset, must be in the future
5    model_validator(mode="after") unique_skus -> sees self.lines
6    computed_field total_cents evaluated when the response is serialised: 2*4200 + 2800 = 11200 (real)

Real scenario: "end date after start date"; "billing address required when the card country differs"; "either email or phone"; unique SKUs per order; a normalised email; an order total computed once on the server so a client cannot send its own.

DecoratorSeesReturnsError loc
@field_validator("f") (after)Validated f, info.data of earlier fieldsNew value of f[..., "f"]
@field_validator("f", mode="before")Raw input of fValue to validate[..., "f"]
@model_validator(mode="before")Raw input dict (any type)New inputModel loc
@model_validator(mode="after")The model instanceselfModel loc
@computed_field + @propertyThe model instanceOutput-only valuen/a (not input)

Fix / how to use it: single-field rules in field_validator or AfterValidator, cross-field rules in model_validator(mode="after"), derived values in computed_field, and never trust a client-sent total.

Mixing path, query and body in one signature Important ​

In plain words: FastAPI sorts each parameter into its source by a few rules, so one function can take a path parameter, query parameters and one or more body parameters in any order.

Common misunderstanding: "Argument order tells FastAPI where to read from." It does not; names and types do. A bool after a model is still a query parameter (dry_run: bool = False in the snippet's cart route, real).

Definition: From the docs: "If the parameter is also declared in the path, it will be used as a path parameter. If the parameter is of a singular type (like int, float, str, bool, etc) it will be interpreted as a query parameter. If the parameter is declared to be of the type of a Pydantic model, it will be interpreted as a request body." Query(), Header(), Cookie(), Body(), Form(), File() override the rule.

     POST /carts/{cart_id}/items?dry_run=1    body {"line": {...}, "gift_note": "Happy birthday"}   (real)
1    cart_id    in the template          -> path,  UUID
2    line       Pydantic model           -> body key "line"
3    gift_note  Body(max_length=200)     -> body key "gift_note"
4    dry_run    bool, not in the path    -> query, "1" -> True
5    201 {"cart_id": "...", "line": {...}, "gift_note": "Happy birthday", "dry_run": true}

Real scenario: PUT /orders/{id}?notify=false with a body; POST /carts/{id}/items with a body and ?dry_run=1; PATCH /users/{id} with a body and an If-Match header; a webhook with a signature header and a JSON body.

ParameterRule that appliesSource
cart_id: UUID (in template)Name in the pathPath
dry_run: bool = FalseSingular typeQuery
line: OrderLinePydantic modelBody
gift_note: Annotated[str, Body()]Explicit markerBody
if_match: Annotated[str, Header()]Explicit markerHeader (If-Match)
request: Request / response: ResponseSpecial typeInjected

Fix / how to use it: keep identifiers in the path, options in the query, the resource in the body, metadata in headers; mark anything ambiguous explicitly.

Reading cookies: Cookie() and cookie models Must-know ​

In plain words: session_id: Annotated[str, Cookie()] reads the session_id cookie from the Cookie request header; a cookie model reads several cookies at once and validates them like any model.

Common misunderstanding: "Swagger UI can send my cookie." The docs warn: "even if you fill the data and click "Execute", because the docs UI works with JavaScript, the cookies won't be sent". Second: "If the browser has the cookie, my test client has it too." A Secure cookie set over http://testserver was not sent back: the snippet's http client got 422 missing for session_id, the https client got the session (real). Third: passing cookies= per request to TestClient.get prints Setting per-request cookies=<...> is being deprecated, because the expected behaviour on cookie persistence is ambiguous (real, httpx 0.28.1); set cookies on the client instead.

Definition: "To declare cookies, you need to use Cookie, because otherwise the parameters would be interpreted as query parameters." Cookie is "a "sister" class of Path and Query" and accepts the same constraints. A cookie model (Annotated[SessionCookies, Cookie()]) is "supported since FastAPI version 0.115.0" and supports extra="forbid": "Your API now has the power to control its own cookie consent." The browser sends only name=value pairs; no attribute (Secure, HttpOnly, Path) travels back, so the server cannot tell how a cookie was set.

     GET /session/me   Cookie: session_id=short; theme=neon        (real, curl -b)
1    SessionCookies.model_validate({"session_id": "short", "theme": "neon"})
2    session_id  min_length=16             -> string_too_short
3    theme       Literal["light", "dark"]  -> literal_error
4    422 errors: [{"location": "cookie", "parameter": "session_id", ...}, {"location": "cookie", "parameter": "theme", ...}]

Real scenario: server-side sessions (session_id → Redis); a CSRF double-submit token; a UI preference (theme); an A/B bucket; a "remember me" token; consent flags.

NeedDeclarationNote
One cookie, optionaltheme: Annotated[str | None, Cookie()] = NoneAbsent → None
One cookie, requiredsession_id: Annotated[str, Cookie(min_length=16)]Absent → 422 missing
A groupcookies: Annotated[SessionCookies, Cookie()]0.115.0+
Reject unknown cookiesmodel_config = {"extra": "forbid"}Browsers send analytics cookies too; rarely wise
Cookie name not an identifierCookie(alias="__Host-session")__Host- names need an alias (real: read abc, runs/p4-output.txt)
Raw accessrequest.cookiesStarlette Request

Fix / how to use it: read session cookies through a model with tight min_length/pattern, use an https base_url in tests for Secure cookies, set cookies on the client object, not per request, and validate the session in a dependency (the lookup is I/O).

Setting cookies: Set-Cookie, HttpOnly, Secure, SameSite Must-know ​

In plain words: To set a cookie, declare response: Response and call response.set_cookie(...), or return a Response you built yourself. The attributes decide where the browser will send the cookie back and who can read it.

Common misunderstanding: "set_cookie defaults are secure." Starlette's defaults are secure=False, httponly=False, samesite="lax" (real signature on 0.49.3), so the Before app's cookie came out as session=s3cr3t; Path=/; SameSite=lax, readable by JavaScript and sent over plain HTTP (real). Second: "SameSite=None is the permissive option for cross-site APIs." MDN: "The Secure attribute must also be set when using this value."

Definition: Starlette: Response.set_cookie(key, value, max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite="lax", partitioned=False). partitioned exists in 0.49.3 and, per the current Starlette docs, works "Only available for Python 3.14+, otherwise an error will be raised". RFC 6265: "The Secure attribute limits the scope of the cookie to "secure" channels" and "The HttpOnly attribute limits the scope of the cookie to HTTP requests". MDN on SameSite: Strict: "Send the cookie only for requests originating from the same site that set the cookie"; Lax adds top-level navigations with safe methods; "Some browsers use Lax as the default value if SameSite is not specified". __Host- prefix: "must be set with the Secure attribute … must not have a Domain attribute specified, and the Path attribute must be set to /". FastAPI: "FastAPI will use that temporary response to extract the cookies (also headers and status code), and will put them in the final response", while response_model still filters the returned value.

Set-Cookie out, Cookie back: the attributes decide when the browser sends itFastAPI (login)POST /sessionresponse.set_cookie(…)Response headerSet-Cookie: session_id=Jpjc…; HttpOnly; Max-Age=2592000;Path=/; SameSite=lax; Secure(real header from the lab run)Browsercookie jar per siteenforces every attributesends only name=valueNext request headerCookie: session_id=Jpjc…; theme=darkno attributes travel back: the server cannot seewhether a cookie was Secure or HttpOnlyAttribute → effectHttpOnlynot visible to document.cookie (XSS cannot read it)Securesent only over https:// (TestClient needs an https base_url)SameSite=Strictnever sent on cross-site requestsSameSite=Lax (Starlette default)cross-site only on top-level GET navigationSameSite=Nonealways sent; requires Secure__Host- prefixrequires Secure, Path=/ and no Domain
     POST /session  (form: username, password, remember=on)               (real, Uvicorn + curl)
1    Form fields validated (min_length) -> password check (stand-in)
2    session_id = secrets.token_urlsafe(24)
3    response.set_cookie("session_id", ..., httponly=True, secure=True, samesite="lax", max_age=2592000)
4    HTTP/1.1 200 OK
     set-cookie: session_id=JpjcVlGCnBkj4sBVHMJDRSbyECUYfCaV; HttpOnly; Max-Age=2592000; Path=/; SameSite=lax; Secure
5    DELETE /session -> 204, set-cookie: session_id=""; ...; Max-Age=0 ...     (real, test_logout)

Real scenario: a session cookie for a server-rendered or same-site SPA; a theme cookie that JavaScript must read (HttpOnly off on purpose, snippet /preferences); a third-party embed that needs SameSite=None; Secure; a logout that must expire the cookie with the same path/domain it was set with.

Attributeset_cookie argumentStarlette defaultRecommended for a session cookie
HttpOnlyhttponly=TrueFalseOn
Securesecure=TrueFalseOn (HTTPS only)
SameSitesamesite="lax" | "strict" | "none""lax"lax (or strict for admin apps)
Max-Age / Expiresmax_age=, expires=none (session cookie)Short, refreshed
Pathpath="/"//
Domaindomain=none (host-only)Leave unset (host-only)
Partitionedpartitioned=TrueFalseOnly for third-party embeds (Python 3.14+)
Name prefix__Host-session—Use when possible (forces Secure, Path=/, no Domain)

Fix / how to use it: always pass httponly, secure and samesite explicitly; use delete_cookie with the same path, domain, secure, samesite; prefer __Host- names in production; CSRF protection for cookie-authenticated unsafe methods is still needed (SameSite is defence in depth, see OWASP API Security Top 10).

Headers: Header(), underscore conversion, duplicate headers, header models Must-know ​

In plain words: user_agent: Annotated[str | None, Header()] = None reads the User-Agent header. FastAPI converts underscores to hyphens and matches case-insensitively. A list[str] type collects a header that appears several times. A header model groups headers.

Common misunderstanding: "x_token in Python means I can send x_token: on the wire." With the default convert_underscores=True, the parameter reads X-Token. On 0.128.8 a request with the literal header x_token: under gave None for an individual parameter, but a header model field x_request_id accepted a literal x_request_id header (both real). FastAPI 0.136.3 made the default "not accept underscore headers". Second: "extra="forbid" on a header model is a good idea." Every client sends Host, Accept, User-Agent, and proxies add more, so a forbidding header model rejects normal traffic; the snippet uses extra="ignore".

Definition: "by default, Header will convert the parameter names characters from underscore (_) to hyphen (-) to extract and document the headers", and "HTTP headers are case-insensitive, so, you can declare them with standard Python style". Header(convert_underscores=False) turns this off, with the warning "some HTTP proxies and servers disallow the usage of headers with underscores". For duplicate headers: "You will receive all the values from the duplicate header as a Python list." Header models arrived in 0.115.0 like query models. On 0.128.8 a header-model error used the field name (["header", "x_request_id"], real); 0.152.0 changed it to "the HTTP header name, such as int-val, instead of the Python field name, int_val".

     GET /client   X-Request-ID: 2f6c… ; X-Feature: dark-mode ; X-Feature: beta        (real, curl)
1    ClientHeaders fields -> header names: x-request-id, x-client-version, accept-language, x-feature
2    x_request_id   "2f6c…"            -> UUID
3    x_client_version absent           -> "0.0.0" (default; pattern \d+\.\d+\.\d+)
4    x_feature      two header lines   -> ["dark-mode", "beta"]
5    200 {"x_request_id": "2f6c…", "x_client_version": "0.0.0", "accept_language": null, "x_feature": ["dark-mode", "beta"]}

Real scenario: X-Request-ID / traceparent for tracing; Idempotency-Key on POST /orders (the snippet requires a UUID); Accept-Language; If-Match/If-None-Match for optimistic concurrency; client version headers for deprecation warnings; X-Forwarded-For (only from a trusted proxy).

Python declarationHeader readNote
user_agent: Annotated[str | None, Header()] = NoneUser-AgentCase-insensitive match
x_request_id: Annotated[UUID, Header()]X-Request-IDRequired; 422 uuid_parsing on junk
x_feature: Annotated[list[str], Header()] = []All X-Feature linesDuplicate headers → list
x_legacy_token: Annotated[str | None, Header(convert_underscores=False)] = Nonex_legacy_token literallySome proxies drop it
idem: Annotated[UUID, Header(alias="Idempotency-Key")]Idempotency-KeyExplicit alias
headers: Annotated[ClientHeaders, Header()]One per fieldHeader model, 0.115.0+

Fix / how to use it: declare every header you rely on (so it is documented and validated), use list[str] where repetition is legal, keep header models on extra="ignore", and avoid underscore header names entirely.

The Authorization header (preview) Important ​

In plain words: authorization: Annotated[str | None, Header()] = None reads Authorization: Bearer <token>. Parsing the scheme is a validation job; verifying the token is an authentication job and belongs in a dependency.

Common misunderstanding: "A header model is a neat place to put Authorization." On 0.128.8 a header-model validation error copied all request headers into the default 422 body's input field, "authorization": "Bearer SECRET-TOKEN" included (real, probe and test_default_header_model_error_echoes_every_header). The token then sits in client-side error logs and APM breadcrumbs. The snippet's Problem Details handler drops input for every error.

Definition: RFC 9110 defines Authorization as credentials for the target resource, and a 401 response must carry WWW-Authenticate. HTTPException(401, ..., headers={"WWW-Authenticate": "Bearer"}) sets it (real: www-authenticate: Bearer). FastAPI's security utilities (OAuth2PasswordBearer, HTTPBearer, APIKeyHeader) read the same header and document it as a security scheme; they are covered in Authentication in FastAPI.

     GET /account                                            (real)
1    authorization absent -> scheme "" -> HTTPException(401, headers={"WWW-Authenticate": "Bearer"})
2    401 application/problem+json {"type": "about:blank", "title": "Unauthorized", "detail": "missing bearer token"}
     GET /account   Authorization: Bearer abc.def.ghi
3    scheme "Bearer", token "abc.def.ghi" -> 200 {"token_length": 11, ...}   (verification: auth chapter)

Real scenario: a bearer JWT from a mobile app; an ApiKey scheme for partners; HTTP Basic on an internal admin; a webhook Signature header verified with HMAC (API keys and signatures).

ConcernHereElsewhere
Read and split the headerHeader() + partition(" ")—
401 + WWW-AuthenticateHTTPException(..., headers=...)—
Verify signature, expiry, audience—JWT deep dive, Authentication in FastAPI
Scopes and roles—Authorization chapter
Never log or echo itProblem handler drops inputHardening checklist

Fix / how to use it: read Authorization as an individual header or through FastAPI's security classes, never inside a header model with the default error handler, and strip input from 422 responses on any API that accepts credentials in headers.

Forms and files: Form(), File(), UploadFile, python-multipart Must-know ​

In plain words: HTML forms and file uploads are not JSON. Form() reads a field from an application/x-www-form-urlencoded or multipart/form-data body; UploadFile gives you an uploaded file as a spooled temporary file with its name and declared content type. Both need the python-multipart package.

Common misunderstanding: "I can take a JSON body and a file in one request." The docs: "you can't also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using multipart/form-data instead of application/json. This is not a limitation of FastAPI, it's part of the HTTP protocol." Second: "UploadFile.content_type tells me what the file is." It is what the client claims. The snippet refuses a PHP payload uploaded as evil.png with image/png by checking the magic bytes (415, real).

Definition: "To use forms, first install python-multipart." Without it, the snippet's probe failed at import: RuntimeError: Form data requires "python-multipart" to be installed. (real). Form "is a class that inherits directly from Body"; File "is a class that inherits directly from Form". bytes reads the whole file into memory; UploadFile "uses a "spooled" file: A file stored in memory up to a maximum size limit, and after passing this limit it will be stored on disk", and exposes filename, content_type, file and async read/write/seek/close. Form models (Annotated[LoginForm, Form()]) exist since 0.113.0. The multipart format itself is RFC 7578.

     POST /returns/{order_id}/photos   multipart: reason=..., photos=a.png, photos=b.jpg    (real)
1    python-multipart parses parts; files spool to memory/disk
2    reason   Form(min_length=10, max_length=500)   ok
3    photos   list[UploadFile] via File()           2 files
4    per file: read(8) -> PNG/JPEG magic bytes? content_type allowed?   else 415
5    read at most 2 MiB + 1 byte -> over the limit?                        else 413
6    201 {"photos": [{"filename": "a.png", "content_type": "image/png", "bytes": 108}, ...]}

Real scenario: a login form (OAuth2 password flow requires form fields named username and password); return photos; CSV imports; avatar uploads; a support ticket with attachments; server-rendered HTML forms posted to FastAPI.

DeclarationBody typeMemoryVersion notes
username: Annotated[str, Form()]url-encoded or multipartSmallEmpty-value rules changed in 0.149.0 / 0.162.0
remember: Annotated[bool, Form()] = Falseurl-encodedSmallDocs: a checked box sends "on"; unchecked is omitted
data: Annotated[bytes, File()]multipartWhole file in RAMSmall files only
file: UploadFilemultipartSpooled to diskawait file.read(n)
photos: Annotated[list[UploadFile], File()]multipart, repeated partSpooled0.150.0: unselected inputs ignored
form: Annotated[LoginForm, Form()]url-encoded / multipartSmallForm models, 0.113.0+

Starlette already limits multipart parsing: its signature is request.form(max_files=1000, max_fields=1000, max_part_size=1024*1024), and "The max_part_size parameter limits the size of each non-file field; uploaded files are spooled to temporary storage and are not limited by max_part_size". FastAPI 0.128.8 calls request.form() with those defaults, so a 1 MiB + 1 byte text part answered 400 Part exceeded maximum size of 1024KB. and 1,001 multipart fields answered 400 Too many fields. Maximum number of fields is 1000. (both real, runs/p5-output.txt). To change them on the pinned version, take request: Request and call async with request.form(max_fields=..., max_part_size=...) yourself (real: max_part_size of 4 MiB accepted the same part); FastAPI 0.165.0 added configurable form parsing limits.

Fix / how to use it: install python-multipart, cap the file size yourself (read at most limit + 1 bytes; file parts are not limited by max_part_size; on 0.164.0+ also configure the new request body size limits), check magic bytes rather than content_type, store uploads outside the web root under generated names, and keep file metadata validation in Pydantic models.

Coercion, strict mode and special types: Enum, Literal, UUID, datetime Must-know ​

In plain words: By default Pydantic converts compatible input ("lax mode"): "5" becomes 5. Strict mode refuses anything that is not already the right type. Special types (Enum, Literal, UUID, datetime, date, Decimal) have their own parsing rules and error codes.

Common misunderstanding: "Lax mode converts anything sensible." It refuses lossy conversions: 5.5 → int is int_from_float, and 5 → str is string_type (real). Second: "Strict mode still accepts ISO date strings from JSON." Pydantic's docs say strict mode allows strings for dates in JSON input. But FastAPI 0.128.8 validates the already-parsed Python dict, so a strict model refused "2026-11-29" for a date with date_type (real probe). Use strict=True per field (as the snippet does for unit_price_cents) rather than on whole models with dates.

Definition: Pydantic: "By default, Pydantic will attempt to coerce values to the desired type when possible. For example, you can pass the string '123' as the input for the int number type, and it will be converted to the value 123." "When strict mode is enabled, Pydantic will be much less lenient when coercing data, and will instead error if the data is not of the correct type." Strict mode is set per field (Field(strict=True)), per model (ConfigDict(strict=True)) or per call (TypeAdapter(...).validate_python(x, strict=True)). The full rules are in Pydantic's conversion table.

     probe results on Pydantic 2.13.5 via FastAPI 0.128.8 (real)
1    int   "5" -> 5 ; 5.0 -> 5 ; "5.0" -> 5 ; 5.5 -> int_from_float
2    str   5 -> string_type                (no int -> str in lax mode)
3    bool  "yes" / "y" / 1 -> true ; 2 -> bool_parsing
4    float "1e3" -> 1000.0 ; Decimal "12.50" -> "12.50"
5    date  "2026-11-29T00:00:00" -> 2026-11-29 ; "2026-11-29T10:00:00" -> date_from_datetime_inexact ; 1764374400 -> 2025-11-29
6    datetime "2026-11-29T10:15:00+03:30" ok ; "yesterday" -> datetime_from_date_parsing ; 1764400000 -> 2025-11-29T07:06:40Z
7    UUID "nope" -> uuid_parsing ; Literal["a","b"] "c" -> literal_error ; Enum "toys" -> enum
8    strict int "5" -> int_type (body field, query parameter and whole model alike)

Real scenario: money as integer cents with strict=True so "4200" from a buggy client is noticed; delivery windows as timezone-aware datetimes; order ids as UUID; status values as Literal/Enum; dates from HTML date inputs; Unix timestamps from IoT devices (accepted by datetime, maybe not what you want).

TypeAccepts (lax, real)Error type
int5, 5.0, "5", "5.0"int_parsing, int_from_float, int_type (strict)
strstrings onlystring_type
booltrue/false, 1/0, "yes", "y", "on" …bool_parsing
Decimal"12.50", 12.5decimal_parsing
UUIDcanonical stringsuuid_parsing
datetimeISO 8601, Unix secondsdatetime_from_date_parsing, datetime_parsing
dateYYYY-MM-DD, midnight datetimes, Unix secondsdate_from_datetime_inexact, date_from_datetime_parsing
Literal["a", "b"]exact valuesliteral_error
Enum (str, Enum)member valuesenum

Fix / how to use it: keep lax mode for non-string parameters that arrive as text, switch on strict=True for money and identifiers in JSON bodies, require timezone offsets on datetimes with a validator (the snippet's deliver_after), and refuse Unix timestamps where a human date is expected.

Type adapters Good to know ​

In plain words: TypeAdapter(list[OrderLine]) validates, serialises and produces a JSON Schema for any type, not only for BaseModel subclasses. You use it in services, tasks and tests where there is no FastAPI parameter.

Common misunderstanding: "Validation only happens in FastAPI routes." Any Pydantic type can be validated anywhere; a background job that reads JSON from a queue should validate it with the same types the API uses.

Definition: Pydantic: "For use cases like this, Pydantic provides TypeAdapter, which can be used for type validation, serialization, and JSON schema generation without needing to create a BaseModel." Methods: validate_python, validate_json, dump_python, dump_json, json_schema.

     adapter = TypeAdapter(List[OrderLine])                          (real, test_errors)
1    adapter.validate_json('[{"sku": "BOK-0001", "qty": "2", "unit_price_cents": 4200}]')
2    -> [OrderLine(sku="BOK-0001", qty=2, unit_price_cents=4200)]    ("2" -> 2: qty is not strict)
3    adapter.json_schema()["items"]["$ref"] == "#/$defs/OrderLine"
4    TypeAdapter(int).validate_python("5", strict=True) -> ValidationError int_type

Real scenario: validating a queue message; parsing a partner's CSV rows into models; validating dict[str, int] settings; producing a schema for a non-model type; property-based tests.

ToolValidatesTypical place
Route parameterOne request inputFastAPI
Model.model_validate(data)One modelServices, tests
TypeAdapter(T).validate_python(data)Any type TJobs, scripts, libraries
TypeAdapter(T).validate_json(text)Any type from JSON textConsumers, webhooks

Fix / how to use it: reuse the API's validated types in workers via TypeAdapter, and build the adapter once at module level (building one compiles a validator).

The 422 response: RequestValidationError and ValidationError Must-know ​

In plain words: When any input fails, FastAPI raises RequestValidationError before calling your function, and its default handler answers 422 Unprocessable Content with a list: for each problem, where (loc), what kind (type), a message (msg), what was received (input) and the limits (ctx).

Common misunderstanding: "RequestValidationError and Pydantic's ValidationError are the same thing." ValidationError is what Pydantic raises when you call Model(...) or model_validate. RequestValidationError is FastAPI's exception for request inputs, built from the errors of all parameters together. A ValidationError raised inside your endpoint (for example OrderLine(qty=100) on data from a database) is not a request error: it is an unhandled exception and a 500. Second: "Uvicorn's log says 422 Unprocessable Entity, so that is the name." That is the RFC 4918 phrase Uvicorn 0.39.0 still prints; RFC 9110 calls 422 "Unprocessable Content", and Starlette's HTTP_422_UNPROCESSABLE_ENTITY constant is deprecated in favour of HTTP_422_UNPROCESSABLE_CONTENT.

Definition: RFC 9110: "The 422 (Unprocessable Content) status code indicates that the server understands the content type of the request content (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request content is correct, but it was unable to process the contained instructions." FastAPI also answers 422 for malformed JSON (json_invalid), which strictly is a syntax problem. In OpenAPI the default 422 is documented on every operation that has parameters as HTTPValidationError → detail: ValidationError[], with loc, msg, type required and input, ctx optional (real schema on 0.128.8). The RequestValidationError "contains the body it received with invalid data" (exc.body). The docs warn that converting the exception to a string "could be leaking a bit of information about your system".

     default 422 for GET /items/abc (bare app, no custom handler)                    (real)
1    {"detail": [{"type": "int_parsing", "loc": ["path", "item_id"],
2                 "msg": "Input should be a valid integer, unable to parse string as an integer",
3                 "input": "abc"}]}
     Pydantic outside FastAPI:  Range(start=5, end=2)
4    ValidationError: 1 validation error for Range
5      Value error, end must not be before start [type=value_error, input_value={'start': 5, 'end': 2}, input_type=dict]
6    e.errors(include_url=False)[0]["loc"] == ()        e.error_count() == 1

Real scenario: a form front end maps loc to inputs and highlights them; an SDK turns type codes into typed exceptions; support dashboards count the top error codes per endpoint; a monitoring rule alerts when 422s on one route jump after a client release.

ExceptionRaised byDefault statusHandler to override
RequestValidationErrorFastAPI, request inputs422@app.exception_handler(RequestValidationError)
WebSocketRequestValidationErrorFastAPI, WebSocket inputsn/a (WebSocket, not HTTP)its own handler (0.97.0+)
ResponseValidationErrorFastAPI, your return value vs response_model500rarely: it is a server bug
pydantic.ValidationError in your codePydantic500 (unhandled)catch it, or map it to a domain error
HTTPExceptionyour codeits status_codeStarlette's HTTPException

Fix / how to use it: treat 422 as the client's problem and 500 as yours: ResponseValidationError and stray ValidationErrors are bugs to fix, not to format. Keep the error type codes stable across releases; clients code against them.

RequestValidationError handler and Problem Details (RFC 9457) Must-know ​

In plain words: Override the default handler with @app.exception_handler(RequestValidationError) and return the RFC 9457 format: a JSON object with type, title, status, detail, instance and your own extension members (here errors), sent as application/problem+json.

Common misunderstanding: "Problem Details has a standard errors array." It does not; RFC 9457 defines five members and allows extensions. Its validation example invents an errors extension with detail and pointer per entry: "The fictional problem type here defines the "errors" extension". Second: "RFC 7807 is the current one." RFC 9457 "obsoletes RFC 7807" (July 2023).

Definition: RFC 9457 members: type ("a URI reference … that identifies the problem type"; when absent "its value is assumed to be "about:blank""), title, status, detail, instance. "Problem type definitions MAY extend the problem details object with additional members", and "Clients consuming problem details MUST ignore any such extensions" they do not recognise. The media type is application/problem+json. FastAPI's docs show the override: "To override it, import the RequestValidationError and use it with @app.exception_handler(RequestValidationError) to decorate the exception handler. The exception handler will receive a Request and the exception."

Four kinds of failure, three handlers, one Problem Details envelopeRequestValidationErrorraised by FastAPI before your codeHTTPExceptionraise HTTPException(401, headers=…)Router 404 / 405Starlette HTTPExceptionOutOfStock(DomainError)your custom exception classvalidation handlerexception_handler(RequestValidationError)HTTP handlerregistered for Starlette's classdomain handler@app.exception_handler(DomainError)RFC 9457 envelopetype: URI or about:blanktitle: short, per typestatus: 422 / 401 / 404 / 409detail: this occurrenceinstance: request patherrors: [...] (extension)sku, available (extension)Content-Type:application/problem+jsonAnything else → 500 from ServerErrorMiddleware (plain text "Internal Server Error"); log it, do not shape it here
     POST /orders (5 problems) with install_problem_handlers(app)                        (real, Uvicorn + curl)
1    RequestValidationError.errors() -> 5 dicts with loc tuples
2    _to_field_problem: ("body","lines",0,"qty") -> {"location": "body", "pointer": "#/lines/0/qty", "code": "greater_than_equal"}
3                       ("query","limit")       -> {"location": "query", "parameter": "limit", ...}
4    log.info(path, [(location, code), ...])    (never the input)
5    422 content-type: application/problem+json
     {"type":"https://shop.example/problems/validation","title":"Your request is not valid.","status":422,
      "instance":"/orders","detail":"5 validation error(s)","errors":[{"location":"body","code":"value_error",
      "detail":"Value error, an Indian PIN code is 6 digits and cannot start with 0","pointer":"#/shipping/postcode"}, ...]}

Real scenario: a public API with external clients that already parse RFC 9457 (many API gateways and client libraries do); one error format across a Python and a Go service; a front end that maps JSON Pointers to fields; an API that must not echo credentials or personal data back in errors.

MemberMeaning (RFC 9457)Snippet value
typeURI that identifies the problem typehttps://shop.example/problems/validation
titleShort summary of the typeYour request is not valid.
statusThe HTTP status code422
detailThis occurrence, human-readable5 validation error(s)
instanceURI of this occurrencethe request path
errors (extension)List of field problems{location, pointer | parameter, code, detail}
Content-Typeapplication/problem+jsonset on every error response

Body pointers follow RFC 6901: ~ is written ~0 and / is written ~1 in each token, so an extra key a/b~c is reported as #/a~1b~0c (real, test_json_pointer_escapes_tilde_and_slash). With type: "about:blank", RFC 9457 says the title "SHOULD be the same as the recommended HTTP status phrase for that code"; the snippet takes it from http.HTTPStatus(code).phrase (real: 415 → Unsupported Media Type).

Fix / how to use it: install one validation handler, one handler for Starlette's HTTPException and one for your domain exception base class; keep type URIs stable and documented; drop input and ctx from client output; log codes and locations only. The general handler machinery and per-exception patterns are in Exceptions & Responses.

Custom exception classes and @app.exception_handler Must-know ​

In plain words: Some failures are valid requests that the business cannot fulfil: out of stock, postcode not served, booking overlaps. Raise a custom exception class from the service layer and let one handler turn it into the right status and Problem Details body.

Common misunderstanding: "Out of stock is a validation error (422)." The request is well-formed and valid; the state of the system refuses it. That is 409 Conflict (or a domain-specific 422 when the content is unacceptable, like the snippet's unsupported postcode area). Second: "Register the HTTP handler for fastapi.HTTPException." The docs: "when you register an exception handler, you should register it for Starlette's HTTPException", so router 404/405 and Starlette internals get the same envelope (real: /nope and DELETE /products came back as Problem Details).

Definition: "You can add custom exception handlers with the same exception utilities from Starlette … with @app.exception_handler()". A handler receives (request, exc) and returns a Response. Handlers match by class, including subclasses, so one handler for DomainError covers OutOfStock and UnsupportedPostcodeArea. HTTPException(status_code, detail, headers) accepts "any value that can be converted to JSON as the parameter detail" and custom headers.

     POST /orders  lines: [{"sku": "GAM-0001", "qty": 1, ...}]                (real)
1    validation passes (shape is fine)
2    shop.stock_of("GAM-0001") == 0  -> raise OutOfStock("GAM-0001: 0 left, 1 requested", sku=..., available=0)
3    @app.exception_handler(DomainError) -> problem_response(409, "Not enough stock", type_=".../out-of-stock")
4    409 application/problem+json {"type": "https://shop.example/problems/out-of-stock", "title": "Not enough stock",
     "status": 409, "instance": "/orders", "detail": "GAM-0001: 0 left, 1 requested", "sku": "GAM-0001", "available": 0}

Real scenario: stock, credit limits and seat availability (409); a postcode the shop does not deliver to (422 with its own type); an expired coupon (422 or 410); an idempotency-key reuse with a different body (422/409); rate limits (429 with Retry-After).

FailureRaised asStatusProblem type
Malformed or invalid inputRequestValidationError (automatic)422.../validation
Unknown SKUHTTPException(404, ...)404about:blank
Not enough stockOutOfStock(DomainError)409.../out-of-stock
Army Postal Service PINUnsupportedPostcodeArea(DomainError)422.../unsupported-postcode-area
Missing bearer tokenHTTPException(401, headers={"WWW-Authenticate": "Bearer"})401about:blank
Bugany other exception500not shaped; logged

Fix / how to use it: one exception hierarchy per domain, raised from services (they stay framework-free), mapped to HTTP in one place; about:blank for plain HTTP errors and your own URI for every domain type you document.

Error response models and the responses parameter Important ​

In plain words: The 422 that FastAPI documents by default is its own HTTPValidationError shape. If you change the error format, tell OpenAPI with responses={422: {...}, 409: {...}} on the decorator, so generated clients and /docs match reality.

Common misunderstanding: "responses={422: {"model": Problem}} documents application/problem+json." FastAPI put the model under application/json (real). The snippet adds an explicit content entry for application/problem+json with a $ref to the same schema, and both entries end up in the document (asserted in test_openapi.py). Second: "Custom handlers update the docs automatically." They do not; routes without responses= still advertise HTTPValidationError (real: /wishlist).

Definition: responses is a dict from status code to an OpenAPI response object plus FastAPI's model key. FastAPI generates the schema of model, adds it to components.schemas, and merges description, content and headers you supply. An error response model is an ordinary Pydantic model (Problem with a nested FieldProblem).

     /openapi.json  POST /orders  "responses"                              (real, abbreviated)
1    "201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": ".../OrderOut"}}}}
2    "409": {"description": "Conflict, e.g. out of stock", "content": {"application/problem+json": {"schema": {"$ref": ".../Problem"}},
3                                                                  "application/json": {"schema": {"$ref": ".../Problem"}}}}
4    "422": {"description": "Validation failed (RFC 9457 Problem Details)", ... same two entries}

Real scenario: a TypeScript client generated from /openapi.json that needs typed errors; a contract test that fails when an error shape changes; an API portal that lists every error per operation.

WantWrite
Document a status with a modelresponses={409: {"model": Problem, "description": "..."}}
Document the real media typeadd "content": {"application/problem+json": {"schema": {"$ref": "#/components/schemas/Problem"}}}
Reuse across routesa module-level dict (PROBLEM_RESPONSES) or APIRouter(responses=...)
Add response headers"headers": {"Retry-After": {"schema": {"type": "integer"}}}
Replace the default 422 entryresponses={422: {"description": ..., "content": {"application/problem+json": {}}}} without model: the entry then has only that media type (real)
Hide the 422 entryresponses={"default": {"description": "Errors"}}: the generated keys become 200 and default (real, runs/p5-output.txt)

Fix / how to use it: declare responses= for every non-2xx status a route can produce (or one "default" entry pointing at the Problem schema), keep the error model in one module, and diff /openapi.json in CI.

Validating a national postcode: regex, structure, checksum Important ​

In plain words: A postcode rule has four steps: normalise ("560 001" → "560001"), check the shape with an anchored regex, check the structure (the first digit is a known zone), and, for identifiers that have one, verify a checksum. Postcodes do not have checksums; card and account numbers often do (Luhn).

Common misunderstanding: "isdigit() and a length check are enough." The Before app accepted 000000, 12 and a 13-digit string (real). An Indian PIN code is "a six-digit code" whose "first digit … indicates the zone" and is never 0. Second: "One global postcode regex works." Each country has its own grammar, so the rule depends on the country field: a field validator that reads info.data["country"].

Definition: India Post's PIN: "The first digit of a PIN indicates the zone, the second indicates the sub-zone, and the third, combined with the first two, indicates the sorting district within that zone. The final three digits are assigned to individual post offices"; the nine zones are 1–2 North, 3–4 West, 5–6 South, 7–8 East and 9 the Army Postal Service. An Iranian postcode "is a 10-digit number, the first 5 digits representing the departure code … and the second 5 digits representing the distribution code". The Luhn algorithm (the "modulus 10" or "mod 10" algorithm) "is a simple check digit formula used to validate a variety of identification numbers": double every second digit from the right, subtract 9 from results above 9, and the sum must be a multiple of 10.

     check_pin("560 001")  via IndianPIN                         (real)
1    BeforeValidator  "560 001" -> "560001"
2    regex            ^[1-9][0-9]{5}$ ok
3    structure        zone = PIN_ZONES["5"] = "South"; sorting district "560"
4    route rule       zone 9 (Army Postal Service) -> UnsupportedPostcodeArea -> 422 ".../unsupported-postcode-area"
     gift card "6036 0000 0012 3450"
5    BeforeValidator  -> "6036000000123450" ; regex 16 digits ok ; Luhn sum % 10 == 0 -> ok
6    "6036 0000 0012 3405" (two digits swapped) -> Luhn fails -> value_error "gift card number failed the Luhn check (typo?)"

Real scenario: checkout address forms in several countries; a delivery-area check (zones you serve) that is a business rule, not a format rule; gift cards, loyalty numbers and IBANs with check digits catching typos before a database lookup; national identifiers (with care: personal data, never logged).

Country / identifierNormaliseShape (regex)Structure / checksumSnippet type
India PINdrop spaces, hyphens; int → str^[1-9][0-9]{5}$first digit = zone (1–9)IndianPIN
Irandrop spaces, hyphens^[0-9]{10}$5 + 5 digits (departure + distribution)IranianPostcode
United Kingdomupper-case, one space before last 3simplified ^[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][A-Z]{2}$none (full grammar is longer)UKPostcode
Gift card (16 digits)drop spaces[0-9]{16}Luhn mod 10GiftCardNumber

Fix / how to use it: one Annotated type per identifier, a per-country dispatch table, error messages that tell the user what a valid value looks like, and serviceability (do we deliver there?) as a separate domain check, often backed by a table:

sql
-- Serviceable PIN prefixes: a business rule kept as data, checked after format validation.
CREATE TABLE serviceable_pin_prefixes (
    prefix      TEXT    PRIMARY KEY CHECK (length(prefix) = 3 AND prefix GLOB '[1-9][0-9][0-9]'),
    zone        TEXT    NOT NULL,
    cod_allowed INTEGER NOT NULL DEFAULT 0 CHECK (cod_allowed IN (0, 1))
);

-- Is "560001" served? Bound parameter only; the format was already validated by IndianPIN.
SELECT zone, cod_allowed
FROM serviceable_pin_prefixes
WHERE prefix = substr(:pin, 1, 3);

-- The order tables keep CHECK constraints that mirror the Pydantic rules (app/db.py):
-- qty INTEGER NOT NULL CHECK (qty BETWEEN 1 AND 99)
-- sku TEXT NOT NULL UNIQUE CHECK (sku GLOB '[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]')

OpenAPI effects of each declaration Important ​

In plain words: Every declaration on this page also writes into /openapi.json: parameters with in: query|header|cookie|path, request bodies with their media type, JSON Schema keywords for constraints, and responses for errors.

Common misunderstanding: "Validators show up in the docs." Only declarative constraints do (minLength, pattern, maximum …). An AfterValidator, field_validator or model_validator is invisible to OpenAPI (real: the id parameter with AfterValidator is documented as a plain optional string). Put the rule in description if clients need to know it.

Definition: FastAPI 0.128.8 emits OpenAPI 3.1.0, whose schema objects are JSON Schema 2020-12; Pydantic's JSON Schema docs list both "JSON Schema Draft 2020-12" and "OpenAPI Specification v3.1.0" as targets. Models used for input and output get separate -Input / -Output schemas when they differ (real: Range-Input without the computed field, Range-Output with "readOnly": true).

     declaration                                         -> /openapi.json (real)
1    filters: Annotated[ProductFilter, Query()]           -> 9 parameters "in": "query" (one per field)
2    Field(20, ge=1, le=100)                              -> {"type": "integer", "minimum": 1, "maximum": 100, "default": 20}
3    Query(gt=0) / Query(lt=30000)                        -> "exclusiveMinimum": 0 / "exclusiveMaximum": 30000
4    ClientHeaders via Header()                           -> "x-request-id" "in": "header", "format": "uuid"
5    extra="forbid" on OrderIn                            -> "additionalProperties": false
6    alias="couponCode"                                   -> property "couponCode"
7    Form() fields                                        -> requestBody "application/x-www-form-urlencoded"
8    File() / UploadFile                                  -> requestBody "multipart/form-data"
9    several body params                                  -> one "Body_add_to_cart_..." schema
10   AfterValidator / field_validator                     -> nothing

Real scenario: client generators (openapi-generator, orval) producing typed SDKs; contract tests in CI; API portals; LLM tools that read the schema to call the API.

DeclarationOpenAPI / JSON Schema output
Query(description=..., examples=[...])description, schema.examples
Query(deprecated=True)deprecated: true
Query(include_in_schema=False)parameter absent
Literal["id", "price", "name"]enum: ["id", "price", "name"]
UUID / datetimeformat: uuid / format: date-time
computed_fieldoutput schema only, readOnly: true
json_schema_extra={"examples": [...]}examples on the model schema
responses={409: {...}}extra response entries
@app.get(..., tags=["catalog"]) + openapi_tagsoperation tags, top-level tags with descriptions
@app.get(..., deprecated=True)operation deprecated: true (still served)

Two operation-level declarations complete the picture. tags=["orders"] on a decorator groups the operation in /docs, and FastAPI(openapi_tags=[...]) gives each tag a description and an order (real: tags = catalog, orders, session, returns). deprecated=True on the decorator marks the whole operation deprecated, unlike Query(deprecated=True), which marks one parameter. The snippet's GET /catalog/search is still served but appears with "deprecated": true and its summary (real, test_tags_and_operation_deprecation). Operation metadata (summary, description, operationId, include_in_schema on routes) is covered in FastAPI Fundamentals.

Fix / how to use it: prefer declarative constraints where they exist (they are documented for free), describe the rules validators enforce, tag every operation, deprecate operations before removing them, and snapshot /openapi.json in tests (the snippet's test_openapi.py asserts the important parts).

Version differences: what changed after FastAPI 0.128.8 Good to know ​

In plain words: The pinned 0.128.8 (2026-02-11) is the last release for Python 3.9. Between it and 0.165.0 (2026-11-18) FastAPI changed several behaviours on exactly this page. Code that relies on the old behaviour can break on upgrade.

Common misunderstanding: "A 0.x minor bump is safe for validation." These notes are marked as breaking changes in the release notes, and some quietly change which requests are accepted.

Definition: Each row quotes or summarises the release note; the "0.128.8" column is real output from this chapter's probes.

1    pin 0.128.8 in pyproject.toml (requires-python >=3.9)
2    upgrade to Python 3.11+ (0.162.6 dropped 3.10) and FastAPI 0.165.0
3    re-run the tests: the 0.128.8-specific asserts (header-model loc, null body) will fail by design
4    read the "Breaking Changes" sections between the two versions; fix callers, not tests

Real scenario: a security upgrade forces a jump from 0.128 to 0.16x; a mobile client that sends JSON without Content-Type; a front end that relies on null meaning "use the default".

Area0.128.8 (real)Changed inNew behaviour (release notes)
JSON without Content-TypeAccepted0.132.0Rejected by default (strict_content_type=False to allow)
Underscore header namesIgnored by Header(); accepted by a header model field0.136.3"Do not accept underscore headers when using convert_underscores=True"
exclude_unset on parameter modelsDefaults counted as set0.148.0Defaults no longer mark a field as set
Unselected file input(not probed)0.150.0Treated as missing
JSON null for a body value with a defaultDefault used0.151.0null validated as None; non-nullable types reject it
Header-model error locPython field name x_request_id0.152.0HTTP header name
Several models per locationBoth missing0.157.0Combined
Model | None = None parameter modelAssertionError at import0.159.0Optional group
extra with sibling parameters(not used)0.160.0extra applies to every field in that location
Omitted form booleans(not probed)0.147.0 → 0.162.0First inferred False, then back to defaults / missing
Body size, form parsing limitsNo body-size limit; multipart parsing uses Starlette's request.form() defaults (max_files=1000, max_fields=1000, max_part_size 1 MiB per non-file part), not configurable from a FastAPI route; url-encoded forms are not counted (1001 fields accepted, real)0.164.0 / 0.165.0Configurable body-size and form-parsing limits

Fix / how to use it: pin FastAPI exactly, keep tests that assert the behaviours your clients depend on, and read the "Breaking Changes" sections before every upgrade.

Mechanics ​

From raw input to your function: every field is checked; a scalar field reports its first failing checkraw input"560 001" / "5" / nullBeforeValidatornormalise raw valuestrip, lower, int→strcore typelax: "5"→5strict: "5" refusedField constraintsge le gt ltmin/max_length, patternAfterValidatorfield_validatorregex + checksummodel_validator(mode="after")sees all fields; cross-field rulescomputed_field is evaluated on outputYour function runserrors == [] → call the path operationAny errors?each failing field adds {type, loc, msg, input, ctx}FastAPI collects errors from path, query, header,cookie and body, then raises RequestValidationErroryour function is NOT calleddefault handler → 422 {"detail": [...]}Your handler (RFC 9457 Problem Details)@app.exception_handler(RequestValidationError) → 422 application/problem+json{"type": ".../validation", "title": …, "status": 422, "errors": [{"pointer": "#/lines/0/qty", "code": …}]}log codes and locations, never the raw input (a header model echoes every header, Authorization included)

The validation run for one request, step by step Important ​

     POST /orders  (Uvicorn 0.39.0, FastAPI 0.128.8, Pydantic 2.13.5)
1    Uvicorn       parse request line + headers, build scope, receive body bytes
2    Starlette     middleware stack -> router -> APIRoute for POST /orders
3    FastAPI       read body: json.loads(bytes)   (malformed -> RequestValidationError json_invalid)
4    FastAPI       solve the dependant: path params, query, headers (Idempotency-Key), cookies, body
5    Pydantic      for each source, validate against the field's core schema:
                     before validators (right to left) -> core type (lax/strict) -> constraints -> after validators (left to right)
6    Pydantic      model validators (mode="after") once all fields of that model passed
7    FastAPI       errors from ALL sources concatenated; if any -> raise RequestValidationError(errors, body=...)
8    Starlette     ExceptionMiddleware -> your handler -> 422 application/problem+json
9    (no errors)   call create_order(...) in the thread pool (def) ; your exceptions -> their handlers
10   FastAPI       serialise the return value through response_model=OrderOut (computed_field is not in OrderOut)
11   Uvicorn       send the response; access log "POST /orders HTTP/1.1" 201 Created

How FastAPI decides the source of a parameter Good to know ​

Parameter looks likeSourceOverride
Name appears in the path templatePath—
int, float, str, bool, UUID, Enum, Literal, date …QueryHeader(), Cookie(), Body(), Form()
list[str] with Query()Query, repeated key—
list[str] without a markerBodyadd Query()
Pydantic modelBody (JSON)Query(), Header(), Cookie(), Form() → parameter model
UploadFile, list[UploadFile]Multipart part(s)—
Request, Response, BackgroundTasksInjected—
Annotated[T, Depends(fn)]Result of fn—

Exact errors, warnings and log lines Must-know ​

Every line below was printed by the snippet run or the saved probes (FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, python-multipart 0.0.20, Uvicorn 0.39.0, httpx 0.28.1).

TriggerStatus / kindExact output
?tool=plumbus on an extra="forbid" query model422{"type": "extra_forbidden", "loc": ["query", "tool"], "msg": "Extra inputs are not permitted", "input": "plumbus"}
AfterValidator raising ValueError422"type": "value_error", "msg": "Value error, id must start with \"isbn-\" or \"ean-\""
model_validator on the body422{"type": "value_error", "loc": ["body"], "msg": "Value error, end must not be before start", ...}
pattern mismatch422"type": "string_pattern_mismatch", "msg": "String should match pattern '^[A-Z]{3}-[0-9]{4}$'"
strict=True int given "4200"422"type": "int_type", "msg": "Input should be a valid integer"
5.5 for int422"type": "int_from_float", "msg": "Input should be a valid integer, got a number with a fractional part"
"nope" for UUID422"type": "uuid_parsing", "msg": "Input should be a valid UUID, invalid character: found `n` at 1"
"2026-02-30" for date422"type": "date_from_datetime_parsing", "msg": "Input should be a valid date or datetime, day value is outside expected range"
"c" for Literal["a", "b"]422"type": "literal_error", "msg": "Input should be 'a' or 'b'"
Truncated JSON {"name": "x"422"type": "json_invalid", "loc": ["body", 12]
Two query models in one function422{"type": "missing", "loc": ["query", "p"], "msg": "Field required"} (and the same for s)
Annotated[Model | None, Query()] = Noneimport errorAssertionError: Query parameter 's' must be one of the supported types
Form() without python-multipartimport errorRuntimeError: Form data requires "python-multipart" to be installed.
Header model missing a field (default handler)422"loc": ["header", "x_request_id"], ..., "input": {..., "authorization": "Bearer SECRET-TOKEN"}
TestClient.get(..., cookies={...})warningSetting per-request cookies=<...> is being deprecated, because the expected behaviour on cookie persistence is ambiguous
status.HTTP_413_REQUEST_ENTITY_TOO_LARGEwarningDeprecationWarning: 'HTTP_413_REQUEST_ENTITY_TOO_LARGE' is deprecated. Use 'HTTP_413_CONTENT_TOO_LARGE' instead.
Uvicorn access log for a 422logINFO: 127.0.0.1:62350 - "GET /products?limit=0&tool=plumbus HTTP/1.1" 422 Unprocessable Entity
set_cookie("session", "s3cr3t") (defaults)headersession=s3cr3t; Path=/; SameSite=lax
Hardened set_cookieheadersession_id=…; HttpOnly; Max-Age=2592000; Path=/; SameSite=lax; Secure
SQLite CHECK on qty = 0sqlite3.IntegrityErrorCHECK constraint failed: qty BETWEEN 1 AND 99

Solving the classic problems ​

BugSymptomFixCost
Hand-written if chainsOne error per round trip; 500 on int("abc")Typed parameters and modelsNone
Unknown fields acceptedis_admin: true reaches the ORM (mass assignment)extra="forbid" on input models; separate output modelsOne line per model
str | None without default"Optional" parameter is required= NoneNone
Lax money fields"4200" accepted, client bug hiddenField(strict=True) on money and idsNone
isdigit() postcodes000000 acceptedAnchored regex + structure + per-country ruleOne type alias
Validator does I/OSlow validation, hard tests, DB calls for bad requestsFormat in validators, existence in dependencies/servicesRefactor
Cookie without flagsSession readable by XSS, sent over HTTPhttponly=True, secure=True, samesite="lax", __Host-Arguments
Logout does not log outdelete_cookie with a different path/domainSame attributes as set_cookieNone
Header model with extra="forbid"Every real browser request 422sextra="ignore" for headersNone
Token in error bodiesAuthorization echoed in a 422 inputCustom handler without inputOne handler
Default 422 documented, Problem sentGenerated clients cannot parse errorsresponses= with application/problem+jsonDict per router
Trusting UploadFile.content_typeScript uploaded as image/pngMagic bytes, size cap, generated names15 lines
No size cap on uploadsMemory/disk exhaustionRead limit + 1 bytes; proxy limit; 0.164.0+ limitsConfig
Domain errors as 500raise OutOfStock → 500Exception class + handler → 409One handler
Validation only in the APISecond writer stores bad rowsDatabase CHECK, NOT NULL, UNIQUEDDL

Mass assignment and extra fields ​

The Before app echoes is_admin back and would happily pass it to Order(**data). OWASP API3 (broken object property level authorization) is exactly this. The fix has two halves: input models that forbid unknown keys (so a typo or an attack is visible as extra_forbidden) and output models that list only what a client may see (OrderOut has no internal fields). Separate input and output models per resource are the norm, not an optimisation; see OWASP API Security Top 10.

One error format for every failure ​

Three handlers make every error look the same: RequestValidationError → 422 with errors, Starlette's HTTPException → its status (router 404/405 included), DomainError → its own status and type. Clients then need one parser. The snippet's tests assert the content type and members for each path through the handlers.

Validation that needs the database ​

"Does this SKU exist?", "is this coupon still valid?", "does order 42 belong to this user?" are not Pydantic questions. Validate the format in the model, then check existence and ownership in a dependency or service and answer 404/409/403. The database itself keeps CHECK and foreign keys; the snippet's test shows SQLite refusing qty = 0 with CHECK constraint failed even when application code skipped validation.

Safe uploads ​

Read at most limit + 1 bytes, check magic bytes, refuse anything else with 415, never use the client's filename on disk, and put a body-size limit in the reverse proxy as well as in the app. The snippet answers 413 above 2 MiB and 415 for a PHP payload named evil.png (both real).

Choosing ​

SituationUseExtra techniqueReason
One or two simple optionsIndividual Query() paramsAnnotated aliases for reuseSimplest, documented
Five+ related filters, reusedQuery parameter modelextra="forbid", model_validatorOne place for rules
Resource creationBody modelextra="forbid", strict money/idsShape + mass-assignment guard
Partial updateAll-optional modelmodel_dump(exclude_unset=True)Absent ≠ null
Client wraps payloads in a keyBody(embed=True)—Matches the client
A value next to the model in the bodyBody() on a singular value—Otherwise it is a query param
HTML form / OAuth2 password flowForm() / form modelpython-multipartNot JSON
File uploadUploadFile / list[UploadFile]Magic bytes, size capSpooled, streaming
Session identifierCookie() / cookie modelHttpOnly, Secure, SameSite, __Host-Browser-protected
Tracing / idempotency metadataHeader()UUID typeDocumented, validated
CredentialsAuthorization via security classesNever in a header modelAuth chapter owns it
Format rule a type cannot expressAfterValidatorBeforeValidator to normalisePure function, reusable
Cross-field rulemodel_validator(mode="after")Field validator with info.data if one field is "the" culpritSees all fields
Needs the DB or another APIDependency / serviceDomain exception → 404/409I/O does not belong in validators
Public API error formatProblem Details handlerresponses= with application/problem+jsonStandard, documented
Internal service, one clientDefault 422—Less code

When Pydantic validation vs a dependency vs the database ​

RulePydantic (model/validator)Dependency / serviceDatabase
Type, length, range, patternYes—Mirror as CHECK
Cross-field (min ≤ max)model_validator—CHECK (min <= max)
Exists / unique—Lookup → 404 / 409FOREIGN KEY, UNIQUE
Belongs to the caller—Authorization → 403/404Row-level security (optional)
Business state (stock, credit)—Domain exception → 409Constraint or lock
Rate / quota—Dependency → 429—

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One FastAPI app validates every input at the edge with the models on this page, maps domain exceptions to Problem Details in one module, and keeps CHECK constraints in its database. The snippet is that shape: app/models.py (inputs), app/problems.py (errors), app/db.py (constraints). Example: the shop's POST /orders validates the address and lines, checks stock in a service, writes one transaction and answers 201 with Location; every failure is one of four documented Problem types.

Modular monolith and multiple databases ​

Each module (catalog, orders, accounts) owns its input models and its domain exceptions, but all modules share one error envelope and one validation handler installed on the app. Shared validated types (IndianPIN, SKU, Money) live in a small common/types.py that every module imports, so the postcode rule exists once. When a module owns its own database, its CHECK constraints mirror its own models; cross-module references are validated by calling the owning module's service (not by joining its tables).

Microservices ​

Validation does not cross the network: each service validates its own inputs, even from internal callers, because a caller's model version may be older or newer. What does cross is the contract: the OpenAPI document with its schemas and error responses. Example: the orders service calls POST http://payments/charges with Idempotency-Key; payments answers 422 Problem Details with errors[0].pointer = "#/amount"; orders must translate that into its own error (a 502 or a 409 for its client, never a pass-through 422 whose pointer refers to a body the client never sent). A shared Problem Details format across Python and Go services makes such mapping mechanical. Idempotency design: REST API Design.

Distributed data: replicas, caches, sharded databases, multi-region ​

Validation that depends on state (stock, unique email, serviceable postcodes) is only as fresh as the data it reads. A unique-email check against a replica can pass while the primary already has the row, so the UNIQUE constraint on the primary is the real guard and the API maps its violation to 409. Lookup tables used by validators (serviceable PIN prefixes, currency lists) can be cached per process, with a TTL and a version, but a cache miss must not turn into a 422. In multi-region setups, cookie Domain and SameSite choices decide whether a session cookie set by eu.shop.example is sent to us.shop.example. Host-only __Host- cookies are not, which is usually what you want. Caching patterns: see the caching chapter linked from REST API Design.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesPractice
1×CorrectnessModels for every input, extra="forbid", strict money, Problem Details, CHECK constraints, tests per error code
10×Bad traffic and big bodies cost moneyBody-size limits at the proxy and in the app, cheap rejections first (size, content type) before parsing, 422 rate per route on a dashboard, no input in logs
100×Contracts and client fleetsOpenAPI diffs in CI, versioned error type URIs, generated SDKs with typed errors, schema validation at the gateway for the hottest routes, validated types shared as a library across services

Lab ​

All commands run from docs/snippets/python/request-validation-cookies-headers/. Outputs marked "real" were produced on CPython 3.9.6 (macOS) with the pinned versions; transcripts are saved under pipeline/sources/request-validation-cookies-headers/runs/.

1. Install and run the tests (real) ​

python3 -m venv ~/venvs/rv                      # keep the venv outside the repo (.venv/ is not git-ignored)
~/venvs/rv/bin/pip install '.[test]'            # the real run: non-editable, from a copy of this directory
                                                # (an in-place install leaves build/ and *.egg-info behind)
source ~/venvs/rv/bin/activate
export PYTHONDONTWRITEBYTECODE=1                # no __pycache__; pyproject sets -p no:cacheprovider
pytest
# ...........................................................              [100%]
# 64 passed in 0.31s

The tests import app from this directory either way (pythonpath = ["."] in pyproject.toml). The resolved versions are in requirements.lock next to the run logs (pip install -r requirements.lock reproduces them). With uv on Python 3.12+: uv run --extra test pytest (expected, not run: uv is not installed on the build machine).

2. Watch every validation layer from curl (real) ​

uvicorn app.main:app --port 18791
curl -si "http://127.0.0.1:18791/products?limit=0&tool=plumbus"
# HTTP/1.1 422 Unprocessable Entity
# content-type: application/problem+json
# {"type":"https://shop.example/problems/validation","title":"Your request is not valid.","status":422,
#  "instance":"/products","detail":"2 validation error(s)","errors":[{"location":"query","code":"greater_than_equal",
#  "detail":"Input should be greater than or equal to 1","parameter":"limit"},{"location":"query",
#  "code":"extra_forbidden","detail":"Extra inputs are not permitted","parameter":"tool"}]}
curl -s http://127.0.0.1:18791/postcodes/in/560%20001
# {"pin":"560001","zone":"South","sorting_district":"560"}
curl -s http://127.0.0.1:18791/postcodes/in/056001
# {..."errors":[{"location":"path","code":"value_error","detail":"Value error, an Indian PIN code is 6 digits and cannot start with 0","parameter":"pin"}]}

3. A nested body with five errors, then a valid order (real) ​

curl -s -X POST http://127.0.0.1:18791/orders -H 'content-type: application/json' \
  -H 'Idempotency-Key: 7d0e5b5e-4a43-4d5f-9b52-0f3d2a1c9e12' \
  -d '{"email":"sara@example.com","shipping":{"name":"Sara","line1":"x","city":"y","country":"IN","postcode":"056001"},
       "lines":[{"sku":"bok-1","qty":0,"unit_price_cents":"4200"}],"is_admin":true}'
# {..."detail":"5 validation error(s)","errors":[ #/shipping/postcode value_error, #/lines/0/sku string_pattern_mismatch,
#   #/lines/0/qty greater_than_equal, #/lines/0/unit_price_cents int_type, #/is_admin extra_forbidden ]}
curl -si -X POST http://127.0.0.1:18791/orders -H 'content-type: application/json' \
  -H 'Idempotency-Key: 7d0e5b5e-4a43-4d5f-9b52-0f3d2a1c9e11' \
  -d '{"email":"Sara@Example.com","shipping":{"name":"Sara","line1":"12 MG Road","city":"Bengaluru","country":"IN","postcode":"560 001"},
       "lines":[{"sku":"BOK-0001","qty":2,"unit_price_cents":4200}]}'
# HTTP/1.1 201 Created
# location: /orders/d02e245c-027a-4153-b4c5-10f6a317da63
# {"id":"d02e245c-...","email":"sara@example.com","status":"pending","total_cents":8400,"shipping":{...,"postcode":"560001"}}

4. Cookies and headers (real) ​

curl -si -X POST http://127.0.0.1:18791/session -d 'username=sara&password=correct horse&remember=on'
# set-cookie: session_id=JpjcVlGCnBkj4sBVHMJDRSbyECUYfCaV; HttpOnly; Max-Age=2592000; Path=/; SameSite=lax; Secure
curl -s http://127.0.0.1:18791/session/me -b 'session_id=short; theme=neon'
# {..."errors":[{"location":"cookie","code":"string_too_short",...,"parameter":"session_id"},
#               {"location":"cookie","code":"literal_error","detail":"Input should be 'light' or 'dark'","parameter":"theme"}]}
curl -s http://127.0.0.1:18791/client -H 'X-Request-ID: 2f6c1b7e-5d1a-4f0e-9a3b-8c2d4e6f8a10' -H 'X-Feature: dark-mode' -H 'X-Feature: beta'
# {"x_request_id":"2f6c1b7e-...","x_client_version":"0.0.0","accept_language":null,"x_feature":["dark-mode","beta"]}
curl -si http://127.0.0.1:18791/account
# HTTP/1.1 401 Unauthorized
# www-authenticate: Bearer
# {"type":"about:blank","title":"Unauthorized","status":401,"instance":"/account","detail":"missing bearer token"}

Curl over http:// still shows the Secure cookie, because curl does not enforce it when printing headers; a browser (or TestClient with an http:// base URL, see test_secure_cookie_is_not_sent_over_http) does not send it back.

5. The leak and its fix (real) ​

pytest -k "echoes_every_header or do_not_echo_input"
# ..                                                                       [100%]
# 2 passed, 62 deselected in 0.06s

The first test proves that FastAPI 0.128.8's default handler puts "authorization": "Bearer SECRET" into the 422 body when a header model is missing a field. The second proves the Problem Details handler does not. On FastAPI 0.165.0 the first test was not run (expected: the loc changes to the header name per 0.152.0; whether input still carries all headers was not verified).

6. Upgrade experiment (expected, not run) ​

On Python 3.12 with fastapi==0.165.0: test_header_model_errors is expected to fail on the loc (x-request-id instead of x_request_id, 0.152.0). A JSON body sent without Content-Type is expected to be refused (0.132.0). Two query models in one function are expected to work (0.157.0). Run the suite, read each failure against Version differences, and update the tests that encoded old behaviour.

For PHP/Laravel developers ​

A Pydantic body model is the closest thing FastAPI has to a Laravel Form Request, with one structural difference: the rules are types, not strings. Laravel's docs describe form requests as "custom request classes that encapsulate their own validation and authorization logic", created with php artisan make:request, each with "two methods: authorize and rules". FastAPI splits those two jobs. The model holds the rules. Authorization is a dependency, which in Laravel would be authorize(); "If the authorize method returns false, an HTTP response with a 403 status code will automatically be returned". prepareForValidation() ("to prepare or sanitize any data from the request before you apply your validation rules") is what a BeforeValidator does, and the after() hook is a model_validator(mode="after"). Laravel's error format is a 422 with "message" and an "errors" object keyed by dot paths ("nested error keys are flattened into "dot" notation format", e.g. users.0.email), where FastAPI has a loc list (["body", "users", 0, "email"]). Laravel validation rules such as unique:users and exists:... query the database inside validation; Pydantic validators should not, so those checks move to a dependency or service plus a UNIQUE constraint. Laravel runs every rule of an attribute and can list several messages for one field (its sample shows two for team_name) unless you add bail ("stop running validation rules on an attribute after the first validation failure"). For scalar constraints Pydantic behaves like bail: a value that broke both min_length and pattern produced only string_too_short (real, runs/p4-output.txt). That is not a general rule: a Union[int, bool] field given [] produced two errors, at value.int and value.bool (real, runs/p5-output.txt). Across fields it always reports every failing field. Cookies differ by default: "all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client" (the EncryptCookies middleware). Starlette signs nothing, so a FastAPI session cookie should be an opaque random id (as in the snippet), or a signed value you produce yourself. $request->header('X-Header-Name'), $request->cookie('name') and $request->bearerToken() map to Header(), Cookie() and a bearer security dependency.

php
// app/Http/Requests/StoreOrderRequest.php (Laravel 13), the OrderIn model in Laravel terms
class StoreOrderRequest extends FormRequest
{
    public function authorize(): bool { return $this->user() !== null; }        // FastAPI: a dependency, not the model

    protected function prepareForValidation(): void                             // FastAPI: BeforeValidator
    {
        $this->merge(['shipping' => [...$this->input('shipping', []),
            'postcode' => preg_replace('/[\s-]/', '', (string) $this->input('shipping.postcode'))]]);
    }

    public function rules(): array
    {
        return [
            'email'                    => ['required', 'string', 'max:254', 'email'],
            'shipping.country'         => ['required', Rule::in(['IN', 'IR', 'GB'])],             // Literal["IN", "IR", "GB"]
            'shipping.postcode'        => ['required', 'regex:/^[1-9][0-9]{5}$/'],                // IndianPIN (when IN)
            'lines'                    => ['required', 'array', 'min:1', 'max:50'],              // Field(min_length=1, max_length=50)
            'lines.*.sku'              => ['required', 'regex:/^[A-Z]{3}-[0-9]{4}$/', 'distinct', 'exists:products,sku'],
            'lines.*.qty'              => ['required', 'integer', 'between:1,99'],               // Field(ge=1, le=99)
            'lines.*.unit_price_cents' => ['required', 'integer', 'min:0'],
        ];
    }
}
// Controller: $data = $request->validated();  unknown keys are simply not in validated() (FastAPI: extra="forbid" refuses them)
Laravel / PHPFastAPI / Pydantic
Form Request (make:request)Pydantic body model
rules() strings (required|integer|between:1,99)Types + Field(ge=1, le=99)
authorize() → 403Dependency (Depends) → 403
prepareForValidation()BeforeValidator / model_validator(mode="before")
after() hookmodel_validator(mode="after")
bail (first failure per attribute)Pydantic's behaviour for scalar constraints (first failing check); unions can report one error per member; every field is reported
exists: / unique: rules (DB queries)Dependency or service + DB constraint
$request->validated()The model instance; model_dump(exclude_unset=True)
422 {"message", "errors": {"users.0.email": [...]}}422 {"detail": [{"loc": ["body", "users", 0, "email"], ...}]}
$request->query('limit', 20)limit: Annotated[int, Query(ge=1, le=100)] = 20
$request->header('X-Request-ID')x_request_id: Annotated[UUID, Header()]
$request->cookie('name') (decrypted)Cookie() (plain value; sign or use opaque ids)
$request->bearerToken()Authorization via a security dependency
$request->file('photo')UploadFile
response()->cookie(...)response.set_cookie(...)
Rule::enum(Status::class)Enum / Literal field
Custom rule class (make:rule)AfterValidator / reusable Annotated type
abort(409) / $exceptions->render(fn (OutOfStockException $e) => ...)raise OutOfStock(...) + @app.exception_handler

The Go angle ​

Go has no framework-level validation in net/http: encoding/json decodes into a struct and only checks types, so the usual stack is json.Decoder with DisallowUnknownFields (the extra="forbid" of Go: the method's doc comment says it causes "the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields") plus the go-playground/validator package, which "implements value validations for structs and individual fields based on tags". Its README example uses tags such as validate:"required", validate:"gte=0,lte=130" and validate:"required,dive,required" for nested slices, so Go struct tags with the validator package play the role of Field(...). Custom rules are registered functions, as AfterValidators are. Errors come back as validator.ValidationErrors, which you map to Problem Details yourself. Query values, headers (r.Header.Values("X-Feature") for duplicates) and cookies (r.Cookie("session_id"), http.SetCookie with HttpOnly, Secure, SameSite fields on http.Cookie) are strings that you convert by hand. Nothing writes OpenAPI for you. The fence below was compiled and run with Go 1.27.4 and validator v10.26.0 (with stub helpers; output in runs/go-fence-check.txt): a bad order returned four ValidationErrors at once, "is_admin" failed with json: unknown field "is_admin", and "qty": "2" failed at decode time. The Go chapters are net/http: Server, Client, 1.22 Routing and JSON, XML, Struct Tags.

go
// Go 1.22+ with github.com/go-playground/validator/v10: OrderLine + extra="forbid" + Problem Details
type OrderLine struct {
	SKU   string `json:"sku" validate:"required,len=8"`         // Pydantic: Field(pattern=...) (regex via a custom tag)
	Qty   int    `json:"qty" validate:"required,gte=1,lte=99"` // Field(ge=1, le=99); qty 0 fails "required" (zero value)
	Price int    `json:"unit_price_cents" validate:"gte=0"`    // strict by nature: "4200" fails json.Unmarshal
}
type OrderIn struct {
	Email string      `json:"email" validate:"required,email,max=254"`
	Lines []OrderLine `json:"lines" validate:"required,min=1,max=50,dive"` // dive = validate each element
}

var validate = validator.New(validator.WithRequiredStructEnabled())

func createOrder(w http.ResponseWriter, r *http.Request) {
	dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)) // body size cap
	dec.DisallowUnknownFields()                                    // extra="forbid"
	var in OrderIn
	if err := dec.Decode(&in); err != nil {
		writeProblem(w, 422, "Your request is not valid.", []fieldProblem{{Pointer: "#", Detail: err.Error()}})
		return
	}
	if err := validate.Struct(in); err != nil {
		var verrs validator.ValidationErrors
		errors.As(err, &verrs)
		problems := make([]fieldProblem, 0, len(verrs))
		for _, fe := range verrs { // every failing field, like Pydantic
			// Namespace() is Go names ("OrderIn.Lines[0].Qty"); map to JSON names for a real JSON Pointer
			problems = append(problems, fieldProblem{Pointer: "#/" + fe.Namespace(), Code: fe.Tag()})
		}
		writeProblem(w, 422, "Your request is not valid.", problems) // Content-Type: application/problem+json
		return
	}
	http.SetCookie(w, &http.Cookie{Name: "__Host-session", Value: newID(), Path: "/",
		HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
	w.WriteHeader(http.StatusCreated)
}
ConcernFastAPI + PydanticGo net/http + validator
Declare rulesTypes, Field, Query, validatorsStruct tags validate:"..."
Unknown JSON keysextra="forbid" → extra_forbiddendec.DisallowUnknownFields() → decode error
CoercionLax by default ("5" → 5), strict per fieldNone: JSON types must match (cannot unmarshal string into Go struct field OrderIn.lines.0.qty of type int, real)
All errors at onceYesValidationErrors lists all tag failures; decode errors stop at the first
Nested listsAutomaticdive
Custom ruleAfterValidator, field_validatorvalidate.RegisterValidation("pin", fn)
Cross-fieldmodel_validatorgtfield=, struct-level validation
Query / header / cookieTyped parameters, modelsr.URL.Query(), r.Header.Values, r.Cookie strings
Set-Cookieresponse.set_cookie(httponly=, secure=, samesite=)http.SetCookie(w, &http.Cookie{HttpOnly: true, Secure: true, SameSite: ...})
Error formatDefault 422 list; handler for Problem DetailsWrite it yourself
OpenAPIGeneratedSpec-first codegen or annotations

Common misconceptions ​

BeliefReality
str | None makes a parameter optionalThe default makes it optional; without = None it is required (missing)
?q=null sends NoneIt sends the string "null"; query strings have no null
le=100 caps the value at 100It refuses larger values with 422 less_than_equal
alias="item-query" accepts both namesOnly the alias is read (?q= was ignored, real)
deprecated=True / include_in_schema=False disable a parameterBoth still accept the value; they only change the docs
Validators can query the databaseFastAPI's docs send that to dependencies; validators are pure
A query model shows up as one nested parameterEach field is a separate query parameter in OpenAPI
Two query models or an optional model work everywhereOnly since 0.157.0 / 0.159.0; on 0.128.8 they fail (real)
extra="forbid" is always saferOn header models it rejects Host, User-Agent and proxy headers; use ignore there
Strict mode accepts ISO date strings from JSONThrough FastAPI 0.128.8 a strict model refused "2026-11-29" (date_type, real)
Lax mode converts anything sensible5.5 → int and 5 → str are refused
exclude_none is right for PATCHIt drops deliberate nulls; use exclude_unset
Raising ValueError in the endpoint gives a 422Only inside validators; in the endpoint it is a 500
A header model is a good place for AuthorizationIts default 422 echoed every header, the token included (real, 0.128.8)
set_cookie is secure by defaultsecure=False, httponly=False, samesite="lax"
SameSite=None alone is enough for cross-site cookiesIt requires Secure
UploadFile.content_type is the real file typeIt is the client's claim; check magic bytes
A JSON body and a file can share one requestMultipart and JSON exclude each other ("part of the HTTP protocol")
Problem Details defines an errors arrayerrors is an extension member; RFC 9457 defines five members
Custom handlers update the OpenAPI docsOnly responses= does
Pydantic validation replaces database constraintsA second writer or a bug bypasses it; keep CHECK / UNIQUE

Cheat sheet ​

TopicRemember
Source rulesIn path → path; simple type → query; model → body; markers override
Optional queryq: Annotated[str | None, Query(max_length=50)] = None
Required queryNo default (q: str)
Constraintsmin_length, max_length, pattern, ge gt le lt, multiple_of
Metadataalias, title, description, examples, deprecated, include_in_schema
Custom ruleAnnotated[str, BeforeValidator(norm), AfterValidator(check)]
Query modelAnnotated[Filter, Query()] + model_config = {"extra": "forbid"} (0.115.0+)
BodyModel = body; several → keys; Body() for singular values; embed=True
PATCHAll-optional model + model_dump(exclude_unset=True)
Cross-field@model_validator(mode="after") returns self
Derived output@computed_field + @property (output schema, readOnly)
Cookies inCookie() / cookie model; Secure cookies need an https test client
Cookies outresponse.set_cookie(..., httponly=True, secure=True, samesite="lax")
HeadersHeader(); _ → -; list[str] for repeats; header models extra="ignore"
Forms / filesForm(), UploadFile; install python-multipart; magic bytes + size cap
StrictField(strict=True) for money and ids in JSON; not on numeric/bool params from text
422RequestValidationError; detail[] with type, loc, msg, input, ctx
Problem Detailsapplication/problem+json; type, title, status, detail, instance + extensions
Domain errorsException class + @app.exception_handler → 409 etc.
Docsresponses={409: {"model": Problem, "content": {"application/problem+json": ...}}}

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — How does FastAPI decide whether a function parameter comes from the path, the query string or the body? Must-know ​

Answer

Answer: If the name appears in the path template it is a path parameter. If it has a singular type (int, str, bool, UUID, Enum …) it is a query parameter. If it is a Pydantic model it is the request body. Explicit markers override this: Query(), Header(), Cookie(), Body(), Form(), File(). A list[str] needs Query() or it is read as a body. Argument order does not matter. See Mixing sources and Mechanics.

2 — q: str | None without a default: is q required? What about ?q=null? Must-know ​

Answer

Answer: It is required; the default value, not the type, makes a parameter optional, so a missing q is 422 missing. Write q: str | None = None. ?q=null sends the string "null", because query strings have no null representation; ?q= sends an empty string. See Query parameters.

3 — When do you use AfterValidator, BeforeValidator, field_validator, model_validator and a dependency? Must-know ​

Answer

Answer: BeforeValidator normalises raw input before type validation (strip spaces from a postcode). AfterValidator or an after-mode field_validator checks a typed value against a rule a type cannot express (regex + checksum). model_validator(mode="after") handles cross-field rules (min ≤ max, unique SKUs). Anything that needs I/O (database, another API) goes to a dependency or service, per FastAPI's docs, and answers 404/409 rather than 422. See Annotated validators and Model validators.

4 — What does extra="forbid" do on a query model, a body model and a header model? Must-know ​

Answer

Answer: On a query or body model an unknown key becomes a 422 extra_forbidden (?tool=plumbus, "is_admin": true), which surfaces typos and blocks mass assignment. On a header model it would reject every header the model does not list, including Host, User-Agent and proxy headers, so header models should use extra="ignore". Pydantic's default is ignore. See Query parameter models.

5 — Show the default 422 body and explain each member. Which exception produces it? Must-know ​

Answer

Answer: {"detail": [{"type": "int_parsing", "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "abc"}]}. type is the Pydantic error code, loc the source plus path to the field, msg a human message, input the received value, ctx the limits (when there are any). FastAPI raises RequestValidationError before the function runs; its default handler writes this. A Pydantic ValidationError raised inside your own code is a 500, not a 422. See The 422 response.

6 — How do you return RFC 9457 Problem Details for validation errors, and what must the handler not do? Important ​

Answer

Answer: Register @app.exception_handler(RequestValidationError), map exc.errors() to an errors extension (JSON Pointer for body fields, parameter names otherwise) and return JSONResponse(..., status_code=422, media_type="application/problem+json") with type, title, status, detail, instance. Also register a handler for Starlette's HTTPException and your domain base class, so every error shares the envelope. The handler must not echo input (on 0.128.8 a header-model error carried every request header, Authorization included) and must not stringify the exception. Document it with responses=. See Problem Details.

7 — Which attributes should a session cookie have, and how do you set them in FastAPI? Important ​

Answer

Answer: HttpOnly (not readable by JavaScript), Secure (HTTPS only), SameSite=Lax or Strict (not sent on cross-site POST/fetch), Path=/, no Domain (host-only), ideally a __Host- name, and a bounded lifetime. In FastAPI: declare response: Response and call response.set_cookie("session_id", value, httponly=True, secure=True, samesite="lax", max_age=...). Starlette's defaults are secure=False, httponly=False, samesite="lax", so pass them explicitly. Delete with the same path/domain. See Setting cookies.

8 — How are header names mapped from Python, and how do you receive a header that appears twice? Important ​

Answer

Answer: Header() converts underscores to hyphens and matches case-insensitively, so user_agent reads User-Agent and x_request_id reads X-Request-ID. Header(convert_underscores=False) reads the literal name, but proxies may drop underscore headers, and FastAPI 0.136.3+ refuses them under the default setting. Declare list[str] to receive duplicate headers as a list (X-Feature: a and X-Feature: b → ["a", "b"]). See Headers.

9 — What is the difference between exclude_unset, exclude_defaults and exclude_none, and which one does PATCH need? Important ​

Answer

Answer: exclude_unset drops fields the client did not send (from model_fields_set), keeping explicit nulls and explicit default values. exclude_defaults drops fields equal to their default. exclude_none drops every None. PATCH needs exclude_unset=True, so "not sent" and "set to null" stay different. On parameter models before FastAPI 0.148.0, defaults counted as set. See Field, aliases and partial updates.

10 — How do you accept an uploaded image safely? Important ​

Answer

Answer: Install python-multipart, declare UploadFile (spooled to disk, unlike bytes), read at most limit + 1 bytes and answer 413 above the limit, check the magic bytes (PNG \x89PNG, JPEG \xff\xd8\xff) and answer 415 when they don't match, regardless of content_type, store under a generated name outside the web root, and cap the body size in the proxy too. JSON body fields cannot be combined with files in one request. See Forms and files.

11 — What is the difference between lax and strict mode, and where should strict mode not be used? Good to know ​

Answer

Answer: Lax mode converts compatible input ("5" → 5, "yes" → True) but refuses lossy conversions (5.5 → int_from_float, 5 → string_type). Strict mode accepts only the exact type. Every query, path, header and cookie value is a string, so a strict int, bool or UUID there always fails (a strict str is fine). Through FastAPI 0.128.8 a strict model also refused ISO date strings from JSON. Use Field(strict=True) on money and identifiers in JSON bodies. See Coercion and strict mode.

12 — How would you validate a national postcode such as an Indian PIN code, and where does "do we deliver there?" belong? Good to know ​

Answer

Answer: Define a reusable Annotated type. A BeforeValidator normalises (strip spaces and hyphens, int → str). An AfterValidator checks the anchored regex ^[1-9][0-9]{5}$, and the first digit maps to one of nine zones. When the rule depends on the country, a field_validator reads info.data["country"]. Postcodes have no checksum; for identifiers with check digits add Luhn (mod 10). Serviceability is a business rule: a lookup in a table, raised as a domain exception (the snippet's UnsupportedPostcodeArea → 422 with its own type). See Validating a national postcode.

Glossary ​

TermMeaning
Query parameterA ?name=value pair; any simple-typed parameter not in the path
Optional query parameterOne with a default (often None)
Required query parameterOne without a default; absent → 422 missing
Query constraintsmin_length, max_length, pattern, ge, gt, le, lt, multiple_of on Query() and friends
AnnotatedPEP 593 type wrapper carrying metadata: FastAPI markers and Pydantic validators
Query(), Path(), Header(), Cookie(), Body(), Form(), File()FastAPI markers that fix a parameter's source and carry constraints and docs
aliasThe name on the wire when it differs from the Python name
deprecatedMarks a parameter as deprecated in OpenAPI; still accepted
include_in_schemaFalse hides a parameter from OpenAPI; still accepted
examplesExample values for docs (JSON Schema 2020-12 keyword)
AfterValidatorPydantic hook that runs after type validation on the typed value
BeforeValidatorPydantic hook that runs on the raw input before type validation
PlainValidator / WrapValidatorHooks that replace / wrap Pydantic's core validation
field_validatorModel method validating one or more fields; info.data holds earlier fields
model_validatorModel method validating the whole model (before, after, wrap)
computed_fieldProperty included in serialisation and the output schema (readOnly)
Pydantic model for query parametersAnnotated[Model, Query()], a group of query parameters (0.115.0+)
Header model / Cookie modelThe same for headers / cookies
extra (forbid / ignore / allow)What a model does with unknown keys
FieldPer-field defaults, constraints, aliases, docs, strict
model_dump / exclude_unsetSerialise a model / only the fields explicitly set
model_fields_setThe set of field names provided at validation time
Nested modelsModels used as field types, validated recursively
Multiple body parametersSeveral body parameters → one JSON object keyed by parameter names
embedBody(embed=True): wrap a single body model in a key
Underscore conversion / convert_underscoresHeader() maps x_token to X-Token; False turns it off
Duplicate headersThe same header sent several times; list[str] receives all values
Authorization headerCredentials (Bearer …); 401 must send WWW-Authenticate
Set-CookieResponse header that creates a cookie with attributes
HttpOnlyCookie attribute: not readable from JavaScript
SecureCookie attribute: sent only over HTTPS
SameSiteCookie attribute (Strict, Lax, None) controlling cross-site sending
__Host- prefixCookie name prefix requiring Secure, Path=/ and no Domain
FormMarker for form fields (url-encoded or multipart)
UploadFileUploaded file: spooled temporary file + filename, content_type
python-multipartThe parser FastAPI needs for forms and files
Coercion (lax mode)Pydantic's default conversion of compatible input ("5" → 5)
Strict modeOnly the exact type is accepted
Type adapters (TypeAdapter)Validate, serialise and get a JSON Schema for any type
Enum / LiteralFixed value sets; errors enum / literal_error
UUID128-bit identifier type; error uuid_parsing
Datetime parsingISO 8601 strings or Unix seconds → datetime/date; errors datetime_*/date_*
422 Unprocessable ContentRFC 9110 name of 422 (formerly "Unprocessable Entity", RFC 4918)
RequestValidationErrorFastAPI's exception for invalid request inputs
ValidationErrorPydantic's exception when validating in your own code
ResponseValidationErrorFastAPI's exception when a return value fails response_model (500)
HTTPExceptionException carrying a status, detail and headers
exception_handlerDecorator registering a handler for an exception class
Custom exception classA domain exception (OutOfStock) mapped to a status by a handler
Problem DetailsRFC 9457 error format: type, title, status, detail, instance + extensions
RFC 9457July 2023 standard for Problem Details; obsoletes RFC 7807
application/problem+jsonMedia type of a Problem Details JSON document
Error response modelA Pydantic model describing the error body (Problem)
responses parameterDecorator argument adding response entries to OpenAPI
OpenAPI schemaThe machine-readable API description at /openapi.json (3.1.0)
JSON SchemaThe schema language OpenAPI 3.1 uses (Draft 2020-12)
Pydantic v2Pydantic 2.x, with the Rust pydantic-core validation engine
TestClient / httpxStarlette's in-process test client, built on httpx
Luhn (mod 10)Check-digit algorithm that detects all single-digit errors and almost all adjacent transpositions
PIN codeIndia's six-digit postal code; first digit = zone
Laravel Form RequestLaravel class with authorize() and rules()
Laravel validation rulesString rules such as required|integer|between:1,99
Go struct tags validatorgo-playground/validator: validate:"required,gte=1" tags
FastAPI, Starlette, UvicornFramework, ASGI toolkit it subclasses, ASGI server
SQLAlchemy, SQLModel, AlembicThe ORM, its Pydantic-flavoured layer and the migration tool (later chapters)
pytestThe test runner used by the snippet project

References ​

Built by Morteza Negahi