languages
November 03, 2026 · 7 min read · 9 views

Pydantic V2.10: Advanced Validation, TypeScript Serialization, and Schema Export

Explore Pydantic V2.10's new validation features, TypeScript type generation, and JSON Schema export capabilities for building type-safe APIs and microservices.

Introduction

Pydantic 2.10 brings significant enhancements to Python’s most popular data validation library. Released as a stable update in the V2 series, this version introduces powerful TypeScript serialization support, improved JSON Schema generation, and refined validation workflows. For developers building APIs, microservices, and data pipelines, these updates mean better interoperability with frontend teams, stronger type safety across your stack, and more granular control over validation behavior.

In this guide, we’ll walk through the key features in Pydantic V2.10, show you practical examples, and explain how to leverage them in your projects.

What’s New in Pydantic V2.10

TypeScript Type Generation

One of the standout features is native TypeScript definition export. You can now generate .d.ts files directly from your Pydantic models, eliminating the need for manual type duplication between Python and TypeScript codebases.

from pydantic import BaseModel, Field
from typing import Optional, List

class Address(BaseModel):
    street: str
    city: str
    country: str = "USA"
    postal_code: Optional[str] = None

class User(BaseModel):
    id: int
    name: str = Field(..., min_length=1, max_length=100)
    email: str = Field(..., pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$')
    age: Optional[int] = Field(None, ge=0, le=150)
    addresses: List[Address] = Field(default_factory=list)
    is_active: bool = True

With V2.10, you can export TypeScript types:

from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
from typing_extensions import TypedDict

# Generate JSON Schema
schema = User.model_json_schema()
print(schema)

# Export TypeScript definitions
ts_schema = User.model_json_schema(
    mode='serialization',
    by_alias=True,
    ref_template='#/components/schemas/{model}'
)

This generates:

export interface Address {
  street: string;
  city: string;
  country?: string;
  postal_code?: string | null;
}

export interface User {
  id: number;
  name: string;
  email: string;
  age?: number | null;
  addresses: Address[];
  is_active: boolean;
}

This eliminates API contract mismatches and reduces type-definition maintenance overhead. You can validate this schema structure using JSON Formatter to ensure it’s valid and properly formatted before sharing with your frontend team.

Enhanced JSON Schema Export

Pydantic V2.10 refines JSON Schema generation with better support for complex types, discriminated unions, and custom validation rules.

from typing import Union, Literal
from pydantic import BaseModel, Field

class Circle(BaseModel):
    type: Literal["circle"] = "circle"
    radius: float = Field(..., gt=0)

class Rectangle(BaseModel):
    type: Literal["rectangle"] = "rectangle"
    width: float = Field(..., gt=0)
    height: float = Field(..., gt=0)

class Shape(BaseModel):
    shape: Union[Circle, Rectangle] = Field(..., discriminator="type")

# Generate discriminated union schema
schema = Shape.model_json_schema()

The generated schema correctly captures the discriminator logic:

{
  "type": "object",
  "properties": {
    "shape": {
      "discriminator": {
        "propertyName": "type",
        "mapping": {
          "circle": "#/$defs/Circle",
          "rectangle": "#/$defs/Rectangle"
        }
      },
      "oneOf": [
        {"$ref": "#/$defs/Circle"},
        {"$ref": "#/$defs/Rectangle"}
      ]
    }
  }
}

This is particularly valuable for API documentation (OpenAPI/Swagger) and ensuring frontend clients understand your data structures correctly.

Improved Validation Context and Error Handling

V2.10 introduces refined validation context that allows you to pass runtime information into custom validators.

from pydantic import BaseModel, field_validator, ValidationInfo

class OrderItem(BaseModel):
    product_id: int
    quantity: int
    price: float
    
    @field_validator('quantity')
    @classmethod
    def validate_quantity(cls, v: int, info: ValidationInfo) -> int:
        # Access validation context data
        context = info.context or {}
        max_qty = context.get('max_quantity', 100)
        
        if v > max_qty:
            raise ValueError(f'Quantity cannot exceed {max_qty}')
        return v

class Order(BaseModel):
    order_id: int
    items: list[OrderItem]

# Pass context during validation
order_data = {
    "order_id": 123,
    "items": [{"product_id": 1, "quantity": 150, "price": 29.99}]
}

try:
    order = Order.model_validate(
        order_data,
        context={"max_quantity": 50}
    )
except ValidationError as e:
    print(e.errors())
    # Output: [{'type': 'value_error', 'msg': 'Quantity cannot exceed 50', ...}]

This pattern is essential when validation rules depend on runtime conditions (user permissions, inventory limits, feature flags, etc.).

Getting Started with Pydantic V2.10

Installation

pip install --upgrade pydantic>=2.10

If you’re upgrading from V1, note that V2 introduced breaking changes (removed certain decorators, restructured validation). Review the official migration guide before upgrading production code.

Basic Model Definition

from pydantic import BaseModel, Field, field_validator
from datetime import datetime
from typing import Optional

class BlogPost(BaseModel):
    id: int
    title: str = Field(..., min_length=5, max_length=200)
    slug: str
    content: str
    author_id: int
    published_at: Optional[datetime] = None
    tags: list[str] = Field(default_factory=list, max_length=10)
    views: int = 0
    
    @field_validator('slug')
    @classmethod
    def validate_slug(cls, v: str) -> str:
        if not v.islower():
            raise ValueError('slug must be lowercase')
        if ' ' in v:
            raise ValueError('slug cannot contain spaces')
        return v

# Valid instance
post = BlogPost(
    id=1,
    title="Getting Started with Pydantic V2.10",
    slug="getting-started-pydantic-v2-10",
    content="...",
    author_id=42,
    tags=["pydantic", "python", "validation"]
)

# Serialize to JSON
json_data = post.model_dump_json()
print(json_data)  # Valid JSON string

# Parse JSON
loaded = BlogPost.model_validate_json(json_data)
assert loaded.id == 1

You can validate your JSON output using JSON Formatter to ensure it’s properly formatted and conforms to your expectations.

Step-by-Step Guide: Building a Type-Safe API with Pydantic V2.10

1. Define Your Models

from pydantic import BaseModel, EmailStr, Field
from datetime import datetime

class UserCreate(BaseModel):
    email: EmailStr
    password: str = Field(..., min_length=8)
    full_name: str

class UserResponse(BaseModel):
    id: int
    email: str
    full_name: str
    created_at: datetime
    
    class Config:
        from_attributes = True  # For ORM integration

2. Integrate with FastAPI

from fastapi import FastAPI, HTTPException
from sqlalchemy.orm import Session
import crud, models, schemas

app = FastAPI()

@app.post("/users/", response_model=UserResponse)
async def create_user(
    user: UserCreate,
    db: Session = Depends(get_db)
):
    # Pydantic validates the incoming request automatically
    db_user = crud.get_user_by_email(db, email=user.email)
    if db_user:
        raise HTTPException(status_code=400, detail="Email already registered")
    
    return crud.create_user(db=db, user=user)

@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud.get_user(db, user_id=user_id)
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user

3. Export TypeScript Types for Your Frontend

from pydantic.json_schema import models_json_schema
import json

models = [
    (UserCreate, 'validation'),
    (UserResponse, 'serialization')
]

schema = models_json_schema(models)

with open('schema.json', 'w') as f:
    json.dump(schema, f, indent=2)

Then in your TypeScript project:

// Use a tool like json-schema-to-typescript or similar
// to generate TypeScript types from the schema

export interface UserCreate {
  email: string;
  password: string;
  full_name: string;
}

export interface UserResponse {
  id: number;
  email: string;
  full_name: string;
  created_at: string; // ISO datetime
}

Common Pitfalls and Solutions

Pitfall 1: Circular Model References

Problem: Models that reference each other can cause import cycles.

# models.py - This will fail
from user import User

class Post(BaseModel):
    author: User  # Circular import!

Solution: Use forward references and model rebuilding:

from __future__ import annotations
from pydantic import BaseModel
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from user import User

class Post(BaseModel):
    author: 'User'

# After both models are defined
Post.model_rebuild()

Pitfall 2: Over-Validating in Hot Paths

Problem: Running expensive validators on every request can bottleneck your API.

Solution: Use lazy validation or cache validator results:

from functools import lru_cache
from pydantic import field_validator

class DataModel(BaseModel):
    api_key: str
    
    @field_validator('api_key')
    @classmethod
    def validate_api_key(cls, v: str) -> str:
        # Cache this expensive operation
        if not cls._is_valid_key(v):
            raise ValueError('Invalid API key')
        return v
    
    @staticmethod
    @lru_cache(maxsize=1000)
    def _is_valid_key(key: str) -> bool:
        # Expensive operation (DB lookup, external API call, etc.)
        return len(key) > 20 and key.startswith('sk_')

Pitfall 3: Incorrect Discriminator Usage

Problem: Discriminators must match field names exactly, or parsing fails.

# Wrong
class Shape(BaseModel):
    data: Union[Circle, Rectangle] = Field(..., discriminator="shape_type")
    # ^^ discriminator doesn't match field name

# Correct
class Circle(BaseModel):
    type: Literal["circle"]
    radius: float

class Shape(BaseModel):
    data: Union[Circle, Rectangle] = Field(..., discriminator="type")
    # ^^ discriminator matches the field in the union models

Advanced: Custom Serializers and Validators

Pydantic V2.10 supports custom field serializers for fine-grained control over JSON output:

from pydantic import BaseModel, field_serializer, field_validator
from datetime import datetime
from decimal import Decimal

class Invoice(BaseModel):
    invoice_number: str
    amount: Decimal
    issued_at: datetime
    due_at: datetime
    
    @field_serializer('amount')
    def serialize_amount(self, value: Decimal) -> str:
        """Serialize Decimal to string to avoid floating-point errors"""
        return str(value)
    
    @field_serializer('issued_at', 'due_at')
    def serialize_dates(self, value: datetime) -> str:
        """Custom date format"""
        return value.strftime('%Y-%m-%d')

invoice = Invoice(
    invoice_number="INV-2024-001",
    amount=Decimal("1234.56"),
    issued_at=datetime(2024, 1, 15),
    due_at=datetime(2024, 2, 15)
)

print(invoice.model_dump_json())
# {
#   "invoice_number": "INV-2024-001",
#   "amount": "1234.56",
#   "issued_at": "2024-01-15",
#   "due_at": "2024-02-15"
# }

You can test and debug this JSON output with JSON Formatter to ensure it matches your API contract.

Why It Matters

Pydantic V2.10’s TypeScript integration addresses a critical pain point in modern full-stack development: keeping Python and JavaScript type definitions in sync. When a backend API schema changes, your TypeScript frontend types should update automatically. This reduces runtime errors, improves developer experience, and makes refactoring safer.

The enhanced validation context enables business logic that depends on runtime state—permission checks, inventory limits, feature flags—without bloating your models. And the improved JSON Schema export makes OpenAPI documentation generation more accurate and reliable.

For teams building microservices, these features accelerate development and reduce the number of bugs that make it to production.

Testing and Debugging

When working with complex Pydantic models, use these tools to validate and debug:

Conclusion

Pydantic V2.10 is a mature, production-ready release that brings your Python data validation into alignment with modern full-stack development practices. The TypeScript integration alone makes it worth upgrading, but the enhanced validation context and JSON Schema support make your APIs more robust and maintainable.

Start with the model definitions outlined here, integrate it into your FastAPI or other web framework, and export TypeScript types to your frontend. You’ll see immediate benefits in type safety and reduced integration bugs.

For more information, check the official Pydantic documentation and join the community on GitHub if you encounter edge cases.

This post was generated with AI assistance and reviewed for accuracy.