Pydantic v2 · FastAPI ready · client-side

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.

JSON → Pydantic Workspace
Input size
217 B
11 lines
Output size
331 B
3 models
Root class
Root
Pydantic v2
Status
Valid
FastAPI ready
Root classVersion
input · json sample
output · pydantic
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: str
Step-by-step Tutorial

How 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.

  1. 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 one BaseModel class per nested object.

    If a field can be null or missing in production, include a sample row where it is — single-sample inference can't see what isn't there. Edit the output to add Optional[T] after generation.

    Need to clean malformed JSON first? Pipe it through JSON Repair before pasting.

    API responsewebhook payloadFastAPI examplesingle-sample inferenceOpenAPI
    input · json sample2 keys
    {"name":"Ada","age":36}
    21 B · 1 linevalid · loaded
  2. 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_case for idiomatic Python. Round-trip the original wire-format with Field(alias="originalKey") and model_config = ConfigDict(populate_by_name=True).

    PEP 8PascalCasesnake_caseField(alias=...)nested models
    naming · Root → UserPascalCase
    class User(BaseModel):
        name: str
        age: int
    49 B · 3 lines · 1 classPEP 8 · ready
  3. 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 uses Config classes and parse_obj(); v2 swaps these for model_config, model_validate(), and a redesigned Field(...) 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_config
    version · v2 defaultimports
    from pydantic import BaseModel
    from typing import Optional, List, Any
    65 B · 2 linesv2 · ready
  4. 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 OpenAI tools and Anthropic input_schema expect.

    Need TypeScript on the front-end too? Pair with JSON to TypeScript from the same sample.

    FastAPImodel_json_schema()Celery / RQLangChaintool definitions
    usage · FastAPIvalidated
    @app.post("/user")
    def create_user(user: User):
        return user
    FastAPI-readyPydantic v2 · success
Pro tips

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.

Use Cases

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 ready

LLM tool definitions

OpenAI / Anthropic tools accept JSON Schema. Pydantic v2 model_json_schema() emits it directly.

tool-call native

Data pipelines

Validate input batches at the edge of your pipeline. Pandas, Polars, and PyArrow integrate cleanly with Pydantic.

RFC 8259 valid

Celery / RQ jobs

Type job arguments so workers validate input on pickup — bad jobs surface in DLQ, not at runtime.

round-trip safe

Webhook handlers

Validate Stripe, Slack, GitHub payloads at the FastAPI boundary. Errors return 422 automatically.

validated payloads

Config & secrets

Use BaseSettings for env-var-driven config with full type validation.

production-ready
FAQ

Frequently asked questions

About generating Pydantic models.

Yes — v2 is the default. v1 is also available for legacy projects.
Null becomes Optional[Any] = None. Edit to Optional[T] = None with the specific T once you know the non-null type.
Yes — Python convention. If you need to round-trip with the original camelCase, add Field(alias="originalKey").
The generator picks the first array element's type. For genuinely mixed unions, edit to Union[A, B] manually.
No. Parsing and codegen run locally.
Suggest a tool

Something missing?

Tell us what you need. We ship the top requests every two weeks.

Sent straight to the maintainers · no account needed
47 in queue·8 shipped this month
Request queued. Thanks!