SyntaxStudy
Sign Up
Python JSON Validation with Pydantic
Python Intermediate 5 min read

JSON Validation with Pydantic

Pydantic Models

Pydantic parses and validates JSON into typed Python models, raising errors for missing or wrong-type fields.

Example
from pydantic import BaseModel, EmailStr, field_validator
from typing import Optional

class User(BaseModel):
    id: int
    name: str
    email: EmailStr
    role: Optional[str] = "user"

    @field_validator("name")
    def name_not_empty(cls, v):
        if not v.strip(): raise ValueError("Name cannot be blank")
        return v

user = User.model_validate({"id": 1, "name": "Alice", "email": "alice@example.com"})
print(user.model_dump_json())
Pro Tip

Pydantic is the standard for FastAPI — models auto-generate JSON schemas for OpenAPI docs.