← Back to FastAPI, page 3

fastapi-0051 · Easy fresher

How do you convert Pydantic v2 models to and from dicts, JSON and ORM objects with model_dump(), model_validate(), model_validate_json() and from_attributes?

In Pydantic v2, model_dump() turns a model into a dict, model_dump_json() into a JSON string, model_validate() builds a validated model from a dict or object, and model_validate_json() validates a JSON string directly. Setting from_attributes=True lets model_validate() read attributes from arbitrary objects such as ORM rows. These replace the v1 methods dict(), json(), parse_obj() and from_orm().

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, and mode="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" to 17 (lax mode). Raises ValidationError with a list of errors.
  • Student.model_validate_json('{"name": "Asha"}'): parses and validates in one step; faster than json.loads followed by model_validate.
  • Student.model_validate(orm_obj) needs model_config = ConfigDict(from_attributes=True) (v1 called this orm_mode). FastAPI's response_model uses 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() gives loc, msg, type and input, and exc.json() serialises them.
  • model_dump() keeps nested models as dicts; use mode="json" before json.dumps.
  • Model fields keep Python types (datetime), so model_dump() returns a datetime but mode="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.
python
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