Skip to course content
Free FastAPI backend course

FastAPI for AI Backend Development

Unit 05.03: Nested models and the shape of real payloads

Real payloads nest, and the error message has to say which nested field failed.

Nested models and the error path

A customer containing an address, with a constrained postcode and a bounded tag list.

The code parses a valid payload and then an invalid nested one.

from pydantic import BaseModel, Field, ValidationError


class Address(BaseModel):
    line1: str = Field(min_length=1)
    postcode: str = Field(pattern=r"^[A-Z0-9 ]{3,10}$")


class Customer(BaseModel):
    name: str
    address: Address
    tags: list[str] = Field(default_factory=list, max_length=10)


ok = Customer(name="A Sharma",
              address={"line1": "1 High St", "postcode": "SW1A 1AA"},
              tags=["priority"])
print(f"parsed: {ok.address.postcode}, {len(ok.tags)} tag(s)")
print(f"address type after parsing: {type(ok.address).__name__}")

try:
    Customer(name="A", address={"line1": "1 High St", "postcode": "lowercase!"})
except ValidationError as exc:
    e = exc.errors()[0]
    print(f"\nnested failure reported at: {'.'.join(str(x) for x in e['loc'])}")

# The error names the nested path, so a caller with a deeply structured payload
# learns which field failed rather than that "the request was invalid".

The parsed address is an Address object rather than a dictionary, so everything downstream gets the same type guarantees the top level does.

The error names the nested path. A caller with a deeply structured payload learns which field failed rather than that "the request was invalid", which is the difference between a fixable error and a support ticket.

The mistake this prevents

The mistake is typing a nested object as dict. It parses anything, provides no validation, produces no schema for the caller, and pushes every check into the handler.

Takeaway

Model nested structures as nested models. The error path names the exact failing field, and the parsed object carries the same guarantees throughout.