Pydantic Validation
Type coercion and model validation.
How it Works
Pydantic allows Python dataclasses to automatically mutate fundamentally untyped network configurations into typed representations.
This protects system state using robust type constraints.
Source Code
Declares an strict schema User model for validation payloads.
models.py
Try in Editorfrom pydantic import BaseModel, EmailStr, Field
from typing import List, Optional
import json
class User(BaseModel):
id: int
name: str = Field(min_length=2)
email: EmailStr
tags: List[str] = []
is_active: bool = True
# Simulating an API response with mixed types
incoming_data = {
"id": "123", # string gets coerced to int
"name": "Alice",
"email": "alice@example.com",
"tags": ("python", "developer") # tuple gets coerced to list
}
# Validate and instantiate
user = User(**incoming_data)
print("--- Validated Pydantic Model ---")
print(repr(user))
print("\n--- Exported to JSON ---")
print(user.model_dump_json(indent=2))Terminal Output
--- Validated Pydantic Model ---
User(id=123, name='Alice', email='alice@example.com', tags=['python', 'developer'], is_active=True)
--- Exported to JSON ---
{
"id": 123,
"name": "Alice",
"email": "alice@example.com",
"tags": [
"python",
"developer"
],
"is_active": true
}Real-world Applications
- API endpoint protection
- Config schema validation
- Database interfacing