Complete worked example
python
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class Place(BaseModel):
country: Literal["US", "IL", "UA", "CA"]
city: str = Field(min_length=1)
class Role(BaseModel):
title: str
locations: list[Place]
def inspect_example(payload):
try:
return {"value": Role.model_validate(payload).model_dump()}
except ValidationError as error:
return {"errors": [{"path": list(e["loc"]), "type": e["type"]}
for e in error.errors(include_input=False)]}- Reasoning
- When validation succeeds, nested models are dumped into the expected ordinary JSON-compatible structure. When it fails, inspect_example selects only loc and type from each error. The location is converted into a list so a client can navigate from locations to index zero and then to country. A malformed country at the second location must retain index one. A blank city is a different failure at its own field. Observe both examples before building a form message. Mapping every error to the final field name alone would make multiple countries or cities indistinguishable in a larger request.