Full answer
Pydantic models validate on creation. Common conversions:
m.model_dump(): dict of Python values. Options:exclude_unset=True(only fields that were provided),exclude_none=True,include={...},exclude={...},by_alias=True, andmode="json"(turn dates, UUIDs and Decimals into JSON-compatible values).m.model_dump_json(): a JSON string, produced by the fast Rust serializer.Student.model_validate({"name": "Asha", "age": "17"}): validates a dict and coerces"17"to17(lax mode). RaisesValidationErrorwith a list of errors.Student.model_validate_json('{"name": "Asha"}'): parses and validates in one step; faster thanjson.loadsfollowed bymodel_validate.Student.model_validate(orm_obj)needsmodel_config = ConfigDict(from_attributes=True)(v1 called thisorm_mode). FastAPI'sresponse_modeluses it to turn ORM objects into responses.m.model_copy(update={"age": 18})makes a copy (it does not re-validate the updated values).
v1 names still work in v2 but emit deprecation warnings: dict(), json(), parse_obj(), parse_raw(), from_orm(), copy().
Notes:
- Validation errors are structured:
exc.errors()givesloc,msg,typeandinput, andexc.json()serialises them. model_dump()keeps nested models as dicts; usemode="json"beforejson.dumps.- Model fields keep Python types (
datetime), somodel_dump()returns adatetimebutmode="json"returns an ISO string. - In FastAPI you rarely call these yourself: request bodies are validated automatically and return values are serialised, but they are essential in services, tests and background jobs.
from datetime import date
from pydantic import BaseModel, ConfigDict, ValidationError
class Student(BaseModel):
model_config = ConfigDict(from_attributes=True)
name: str
age: int
born: date | None = None
s = Student.model_validate({"name": "Asha", "age": "17", "born": "2009-03-04"}) # "17" is coerced to 17
print(s)
print(s.model_dump())
print(s.model_dump(mode="json"), s.model_dump(exclude={"born"}))
print(s.model_dump_json())
print(Student.model_validate_json('{"name": "Ravi", "age": 18}'))
part = Student(name="Kiran", age=16)
print(part.model_dump(exclude_unset=True), part.model_dump(exclude_none=True))
class OrmRow: # stands in for a SQLAlchemy object
def __init__(self):
self.name, self.age, self.born = "Meera", 19, None
print(Student.model_validate(OrmRow()))
print(s.model_copy(update={"age": 18}).age)
try:
Student.model_validate({"name": "X", "age": "abc"})
except ValidationError as exc:
print([(e["loc"], e["type"]) for e in exc.errors()])
Standalone script. Run it with `python file.py`; it uses Pydantic only. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): name='Asha' age=17 born=datetime.date(2009, 3, 4) {'name': 'Asha', 'age': 17, 'born': datetime.date(2009, 3, 4)} {'name': 'Asha', 'age': 17, 'born': '2009-03-04'} {'name': 'Asha', 'age': 17} {"name":"Asha","age":17,"born":"2009-03-04"} name='Ravi' age=18 born=None {'name': 'Kiran', 'age': 16} {'name': 'Kiran', 'age': 16} name='Meera' age=19 born=None 18 [(('age',), 'int_parsing')]
Key points
- model_dump and model_dump_json serialise; model_validate and model_validate_json parse
- from_attributes=True reads ORM objects
- exclude_unset is useful for PATCH-style updates
- mode='json' makes output JSON-safe
- v1 method names are deprecated
Common mistakes
- Using v1 method names such as dict() and parse_obj() in new code
- Forgetting from_attributes=True when validating ORM objects
- Passing model_dump() output with datetimes straight to json.dumps
- Expecting model_copy(update=...) to validate the new values
Follow-ups
- How does model_dump(exclude_unset=True) help PATCH endpoints?
- What does strict mode change?
- How do you rename fields with aliases?
Tips
- Name 4 conversion methods
- Mention from_attributes
- Mention deprecated v1 names