Generate Pydantic models from JSON
Paste any JSON sample and get Python BaseModel classes with correct type annotations, ready for FastAPI, data validation, or LLM tool definitions.
from pydantic import BaseModel
from typing import Optional, List, Any
class Root(BaseModel):
user: RootUser
version: int
class RootUser(BaseModel):
id: int
name: str
email: str
active: bool
roles: List[str]
address: RootUserAddress
class RootUserAddress(BaseModel):
city: str
country: strHow to generate Pydantic models from JSON
Pydantic is the de-facto Python data validation library and the foundation of FastAPI. Paste a JSON sample, get fully-typed BaseModel classes with nested models, lists, and optional fields — ready to drop into your project.
- 01
Paste a JSON sample
Use a representative example — an API response, webhook payload, OpenAPI
example, or config file. The generator infers Python types from the sample's shape and emits oneBaseModelclass per nested object.If a field can be
nullor missing in production, include a sample row where it is — single-sample inference can't see what isn't there. Edit the output to addOptional[T]after generation.Need to clean malformed JSON first? Pipe it through JSON Repair before pasting.
API responsewebhook payloadFastAPI examplesingle-sample inferenceOpenAPIinput · json sample2 keys{"name":"Ada","age":36}21 B · 1 linevalid · loaded - 02
Name the root class
Defaults to
Root. Pick PascalCase per PEP 8 —User,WebhookPayload,OrderResponse. Nested objects auto-generate child classes with prefixed names (UserAddress), keeping the import graph flat and tree-shakeable.JSON keys with camelCase or kebab-case are converted to
snake_casefor idiomatic Python. Round-trip the original wire-format withField(alias="originalKey")andmodel_config = ConfigDict(populate_by_name=True).PEP 8PascalCasesnake_caseField(alias=...)nested modelsnaming · Root → UserPascalCaseclass User(BaseModel): name: str age: int49 B · 3 lines · 1 classPEP 8 · ready - 03
Pick Pydantic v2 or v1
Defaults to v2 — the current, Rust-powered (
pydantic-core) release used by FastAPI ≥ 0.100, LangChain, and Anthropic / OpenAI tool definitions. v2 is ~5–50× faster than v1 and supports JSON Schema 2020-12 out of the box.Both versions inherit from
BaseModel. v1 usesConfigclasses andparse_obj(); v2 swaps these formodel_config,model_validate(), and a redesignedField(...)signature with named constraints (min_length,ge,le,pattern).Stay on v1 only for legacy codebases pinned to the old API. Otherwise default to v2.
v2 (pydantic-core)v1 (legacy)BaseModelField(...)model_configversion · v2 defaultimportsfrom pydantic import BaseModel from typing import Optional, List, Any
65 B · 2 linesv2 · ready - 04
Copy or use with FastAPI
One click copies to your clipboard or download
models.py. Drop into FastAPI route handlers (every endpoint gets validation, docs, and OpenAPI schema for free), Celery / RQ workers, LangChain agents, or any Python data-validation context.For LLM tool definitions, call
Model.model_json_schema()— Pydantic v2 emits the exact JSON Schema that OpenAItoolsand Anthropicinput_schemaexpect.Need TypeScript on the front-end too? Pair with JSON to TypeScript from the same sample.
FastAPImodel_json_schema()Celery / RQLangChaintool definitionsusage · FastAPIvalidated@app.post("/user") def create_user(user: User): return userFastAPI-readyPydantic v2 · success
Production-grade Pydantic generation
Add Optional[T] for nullable fields
The generator marks every field required. Add Optional + = None for fields that may be missing.
Use Field() for constraints
Add Field(..., min_length=1, max_length=255) for validation rules. Edit the generated output to add these.
Annotated unions
For mixed-type fields, use Union[A, B] or Annotated[A, B, Discriminator(...)] manually.
Enum support
For closed-set fields (status, role), define a StrEnum and reference it in the model.
v2 model_config
v2 lets you set model_config = ConfigDict(strict=True, populate_by_name=True) for stricter behavior.
Validators
Add @field_validator for cross-field logic. The generator can't infer business rules.
When to generate Pydantic models
Pydantic is everywhere in modern Python. Here's where auto-generation pays off.
FastAPI request/response
Type every endpoint with a Pydantic model — get docs, validation, and IDE autocomplete for free. Output round-trips losslessly through JSON.parse + JSON.stringify, so the file you save is byte-identical to what you see. Streaming parsers, jq pipelines, and Postgres jsonb columns all accept the result without complaint.
OpenAPI readyLLM tool definitions
OpenAI / Anthropic tools accept JSON Schema. Pydantic v2 model_json_schema() emits it directly.
Data pipelines
Validate input batches at the edge of your pipeline. Pandas, Polars, and PyArrow integrate cleanly with Pydantic.
RFC 8259 validCelery / RQ jobs
Type job arguments so workers validate input on pickup — bad jobs surface in DLQ, not at runtime.
round-trip safeWebhook handlers
Validate Stripe, Slack, GitHub payloads at the FastAPI boundary. Errors return 422 automatically.
validated payloadsConfig & secrets
Use BaseSettings for env-var-driven config with full type validation.
Frequently asked questions
About generating Pydantic models.
Optional[Any] = None. Edit to Optional[T] = None with the specific T once you know the non-null type.Field(alias="originalKey").Something missing?
Tell us what you need. We ship the top requests every two weeks.