Full answer
FastAPI supports Pydantic v2 since 0.100 and current releases require it. Interviewers ask about v2 because many codebases are still mid-migration.
Renames you will meet daily:
| v1 | v2 |
|---|---|
obj.dict() | obj.model_dump() |
obj.json() | obj.model_dump_json() |
Model.parse_obj(d) | Model.model_validate(d) |
Model.parse_raw(s) | Model.model_validate_json(s) |
Model.schema() | Model.model_json_schema() |
obj.copy(update=...) | obj.model_copy(update=...) |
class Config: orm_mode = True | model_config = ConfigDict(from_attributes=True) |
@validator, @root_validator | @field_validator, @model_validator |
Field(regex=...), min_items | Field(pattern=...), min_length |
__fields__ | model_fields |
BaseSettings in pydantic | separate pydantic-settings package |
Behaviour changes that cause bugs:
Optional[int]without a default is now required (it may be None, but must be sent). Writeint | None = Nonefor truly optional fields.- Lax conversion is narrower: v2 no longer turns
1.5into1for anintfield, and numbers are not converted to strings by default (strfield with123fails).ConfigDict(coerce_numbers_to_str=True)restores that if needed. - Error format changed: each error has
type,loc,msg,input, andurl. Tests that assert on old error messages break. model_dump(mode="json")gives JSON-safe types (dates as strings) in a dict.- Validators:
@field_validatormust be a classmethod;valuesbecameinfo.data.
Migration approach:
- Run
bump-pydantic, the official codemod, for mechanical renames. - Fix deprecation warnings (v1 names still work in v2 with warnings, until removed).
- Re-run tests, especially ones that check error messages or edge-case coercion.
- Measure: serialisation-heavy endpoints often get noticeably faster.
python
import warnings
from typing import Optional
from pydantic import BaseModel, ConfigDict, ValidationError, field_validator
class StudentRow: # stands in for an ORM object
id, name, marks = 1, "Tanvi", 91
class Student(BaseModel):
model_config = ConfigDict(from_attributes=True) # v1: class Config: orm_mode = True
id: int
name: str
marks: int
nickname: Optional[str] # v2: required, but may be None
@field_validator("name")
@classmethod
def title_case(cls, v: str) -> str:
return v.title()
try:
Student.model_validate(StudentRow())
except ValidationError as e:
print("missing:", e.errors()[0]["loc"], e.errors()[0]["type"])
s = Student.model_validate({"id": 1, "name": "tanvi", "marks": 91, "nickname": None})
print(s.model_dump(), s.model_dump_json())
try:
Student(id=1, name="x", marks=91.5, nickname=None)
except ValidationError as e:
print("float to int:", e.errors()[0]["type"])
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
s.dict() # v1 name still works, with a warning
print("v1 .dict() warning:", caught[0].category.__name__)
Standalone script; needs only pydantic 2.x. 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): missing: ('nickname',) missing {'id': 1, 'name': 'Tanvi', 'marks': 91, 'nickname': None} {"id":1,"name":"Tanvi","marks":91,"nickname":null} float to int: int_from_float v1 .dict() warning: PydanticDeprecatedSince20
Key points
- Rust core makes v2 much faster
- dict/json/parse_obj became model_dump/model_dump_json/model_validate
- orm_mode -> from_attributes; Config -> model_config
- Optional without default is now required
- Use bump-pydantic and fix deprecation warnings
Common mistakes
- Assuming Optional[X] means 'not required' in v2
- Leaving v1 method names and ignoring deprecation warnings until they are removed
- Asserting on exact v1 error messages in tests
- Importing BaseSettings from pydantic instead of pydantic-settings
Follow-ups
- What does bump-pydantic do and what does it not handle?
- How did lax conversion change between v1 and v2?
- How would you migrate a 200-model codebase safely?
Tips
- Know at least five renames without looking
- Call out the Optional behaviour change, it causes real bugs
- Describe a migration plan, not just the differences