Pydantic is the standard data validation, serialization, and settings management library for Python, powered by a Rust core in V2.
Pydantic is the de facto standard data validation and settings management library for the Python programming language. Created by Samuel Colvin, Pydantic enforces type hints at runtime and provides user-friendly error messages when data is invalid. With the release of Pydantic V2, the library's core validation and parsing logic was completely rewritten in Rust (pydantic-core), delivering 5x to 50x performance improvements. Pydantic serves as the core foundation for modern Python frameworks including FastAPI, Django Ninja, SQLModel, LangChain, and OpenAI Structured Outputs.
Convert raw JSON payloads and API responses into typed Pydantic models with our JSON to Pydantic Model Generator, explore structural schemas with the JSON Schema Visualizer, or read our comprehensive guide on Generating Pydantic Models from JSON Schemas.
| Specification | Details |
|---|---|
| Creator & Lead Maintainer | Samuel Colvin (samuelcolvin) / Pydantic Services Inc. |
| Current Standard | Pydantic v2.x (backed by pydantic-core in Rust) |
| Core Base Class | pydantic.BaseModel |
| Configuration Model | model_config = ConfigDict(...) (v2) / class Config: (v1 legacy) |
| Serialization Methods | .model_dump() (Python dictionary), .model_dump_json() (JSON string) |
| Validation Decorators | @field_validator, @model_validator (v2) / @validator, @root_validator (v1) |
| Ecosystem Integrations | FastAPI, Django Ninja, SQLModel, LangChain, LlamaIndex, Instructor, Celery |
| Type Support | PEP 484 / 585 / 604 type hints (str, int, float, bool, list, dict, datetime, UUID, Pattern) |
Pydantic models are defined as Python classes inheriting from pydantic.BaseModel. Field types are declared using standard Python type annotations. When instantiated, Pydantic parses and coerces input values according to these type contracts:
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field
class UserProfile(BaseModel):
id: int
username: str = Field(min_length=3, max_length=50)
email: str
is_active: bool = True
created_at: datetime
roles: List[str] = Field(default_factory=list)
bio: Optional[str] = None
model_config = ConfigDict(populate_by_name=True)
pydantic-core)In Pydantic v1, validation and type coercion were executed entirely in Python bytecode, which became a bottleneck in high-throughput microservices. In Pydantic v2:
pydantic-core, which constructs a compiled Rust validator tree (SchemaValidator).MyModel.model_validate_json(...)) executes in compiled Rust without constructing intermediate Python dictionary objects.Because Python adheres to snake_case (PEP 8) while web APIs often use camelCase, Pydantic provides robust alias mapping:
class PaginatedResponse(BaseModel):
page_number: int = Field(alias="pageNumber")
page_size: int = Field(alias="pageSize")
total_count: int = Field(alias="totalCount")
model_config = ConfigDict(populate_by_name=True)
# Can be initialized using camelCase JSON or snake_case Python keyword arguments:
response = PaginatedResponse.model_validate({"pageNumber": 1, "pageSize": 50, "totalCount": 500})
print(response.page_number) # 1
| Feature | Pydantic V2 | Pydantic V1 | Python dataclasses |
attrs |
msgspec |
|---|---|---|---|---|---|
| Validation Engine | Compiled Rust (pydantic-core) |
Pure Python | None (Type hints only) | Optional validators | Compiled C |
| Runtime Type Coercion | Yes (Automatic & configurable) | Yes | No | No | Yes |
| FastAPI / Framework Support | Native standard | Legacy standard | Manual integration | Manual integration | High performance |
| JSON Schema Generation | Native (model_json_schema()) |
Native (schema()) |
External package | External package | Native |
| Serialization Speed | Ultra Fast | Moderate | Fast | Fast | Blazing Fast |
| Ecosystem & Tooling | Massive ecosystem | Extensive | Standard library | Broad | Growing |
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, EmailStr, Field
app = FastAPI()
class CreateUserRequest(BaseModel):
email: EmailStr
password: str = Field(min_length=8)
full_name: str
age: int = Field(ge=18, le=120)
@app.post("/users", status_code=status.HTTP_201_CREATED)
async def create_user(payload: CreateUserRequest):
# payload is guaranteed to be validated and typed:
return {"status": "created", "email": payload.email, "user": payload.full_name}
@field_validatorfrom pydantic import BaseModel, field_validator
class TransactionPayload(BaseModel):
currency: str
amount: float
@field_validator("currency")
@classmethod
def validate_currency_code(cls, v: str) -> str:
upper = v.upper()
if upper not in {"USD", "EUR", "GBP", "JPY"}:
raise ValueError(f"Unsupported currency: {v}")
return upper
@field_validator("amount")
@classmethod
def validate_positive_amount(cls, v: float) -> float:
if v <= 0:
raise ValueError("Amount must be strictly positive")
return round(v, 2)
Pydantic v2 was rewritten with a Rust-based validation core (pydantic-core), providing 5x to 50x higher throughput and lower memory consumption. Pydantic v2 replaced class Config: with model_config = ConfigDict(...), renamed .dict() to .model_dump(), and introduced @field_validator and @model_validator in place of legacy @validator.
In Pydantic v2, declaring x: Optional[str] without a default value means the field accepts None, but the key must still be supplied in the payload. To allow omitting the field entirely, assign a default value: x: Optional[str] = None.
Yes. Calling MyModel.model_json_schema() generates a compliant JSON Schema (Draft 2020-12) representation of your model, including field descriptions, constraints, enumerations, and nested object definitions.
Instead of writing Python classes manually, paste your JSON payload into our JSON to Pydantic Model Generator to instantly generate type-annotated Pydantic v2 BaseModel classes with recursive child models and field aliases.
Free, browser-based utilities to test, generate, and inspect Pydantic Data Validation & Settings Management Library for Python payloads directly.
Convert JSON and JSON Schema into typed Pydantic v2 and v1 BaseModel classes for FastAPI, Django Ninja, and Python applications.
Convert JSON to Zod schema definitions with automatic TypeScript type inference.
Convert JSON to TypeScript interfaces or type aliases instantly.
Generate TypeScript interfaces, Zod schemas, and Valibot schemas from JSON.
Render Draft-07 / 2020-12 JSON Schemas into interactive visual trees, documentation diagrams, and realistic mock data.
Repair and fix malformed JSON data from AI outputs, API responses, and copy-paste.
Convert OpenAPI/Swagger specs (JSON or YAML) to TypeScript interfaces, types, or Zod schemas.