Phase 14 of 25 · Topic 14.4

Pydantic V2 BaseModels & Fast Rust-Backed Validation

1Concept

Pydantic V2 features a core rewritten in Rust (`pydantic-core`), providing 5x-50x faster validation and JSON serialization. Models validate input payloads, coerce compatible types, and provide detailed structured validation errors.

2Architecture Diagram

Input Dict: {"username": "admin", "age": "28"} ---> Pydantic coerces age to int(28) & validates!

3Code Example

Python 3.12
from pydantic import BaseModel, EmailStr, Field

class UserModel(BaseModel):
    user_id: int
    username: str = Field(min_length=3, max_length=20)
    email: str
    is_active: bool = True

user = UserModel(user_id=101, username="alex_dev", email="alex@corp.com")
print(f"Validated Model: {user.username} (ID: {user.user_id})")
print(f"Serialized JSON: {user.model_dump_json()}")

4Expected Output

Validated Model: alex_dev (ID: 101)
Serialized JSON: {"user_id":101,"username":"alex_dev","email":"alex@corp.com","is_active":true}

5Key Takeaways

  • Use `model.model_dump()` for dictionaries and `model.model_dump_json()` for JSON strings in V2.
  • Pydantic coerces types automatically (e.g. `'28'` becomes `int(28)`).
  • Raises `pydantic.ValidationError` containing JSON error structures on invalid payloads.