Skip to main content

JSON Schema to Pydantic

A Python library for automatically generating Pydantic v2 models from JSON Schema definitions.

PyPI - Version PyPI - Downloads codecov

Features

  • Converts JSON Schema to Pydantic v2 models
  • Supports complex schema features including:
    • References ($ref) with circular reference detection
    • Combiners (allOf, anyOf, oneOf) with discriminated unions where possible
    • Type constraints and validations
    • Array and object validations
    • Enums and constants (as Literal types)
    • Format validations (email, uri, uuid, date, time, date-time)
    • Top-level arrays and scalar types (not just objects)
    • Underscore-prefixed fields (common in OpenAPI specs)
  • Reuse of existing Pydantic models and types for $refs
  • Custom base model class for generated models
  • Full type hinting support
  • Clean, simple API

Installation

pip install json-schema-to-pydantic

Development Setup

  1. Clone the repository
  2. Install development dependencies:
# Using uv (recommended)
uv sync --extra dev

# Or using pip
pip install -e ".[dev]"
  1. Run tests and linters:
uv run pytest
uvx ruff check .

Quick Start

from json_schema_to_pydantic import create_model

# Define your JSON Schema
schema = {
    "title": "User",
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "email": {"type": "string", "format": "email"},
        "age": {"type": "integer", "minimum": 0}
    },
    "required": ["name", "email"]
}

# Generate your Pydantic model
UserModel = create_model(schema)

# Use the model
user = UserModel(
    name="John Doe",
    email="john@example.com",
    age=30
)

# Example with relaxed validation
RelaxedModel = create_model(
    {
        "type": "object",
        "properties": {
            "tags": {"type": "array"},  # Array without items schema
            "metadata": {}  # Field without type
        }
    },
    allow_undefined_array_items=True,  # Allows arrays without items schema
    allow_undefined_type=True  # Allows fields without type (defaults to Any)
)
relaxed_instance = RelaxedModel(
    tags=[1, "two", True],
    metadata={"custom": "data"}
)

# Example with underscore-prefixed fields (common in OpenAPI)
OpenAPIModel = create_model(
    {
        "type": "object",
        "properties": {
            "_links": {"type": "object"},
            "_embedded": {"type": "object"}
        }
    },
    populate_by_name=True  # Allows access via both '_links' and 'links'
)

Advanced Usage

For more complex scenarios, you can use the PydanticModelBuilder directly:

from pydantic import BaseModel
from typing_extensions import TypeAliasType
from json_schema_to_pydantic import PydanticModelBuilder

class PetModel(BaseModel):
    name: str
    type: str

SomeType = TypeAliasType("SomeType", list[str])

schema = {
    "type": "object",
    "properties": {
        "pet": {"$ref": "#/definitions/Pet"},
        "tags": {"$ref": "#/definitions/SomeType"},
    },
    "definitions": {
        "Pet": {
            "type": "object",
            "properties": {"name": {"type": "string"}, "type": {"type": "string"}},
        },
        "SomeType": {"type": "array", "items": {"type": "string"}},
    },
}

builder = PydanticModelBuilder(
    predefined_models={"#/definitions/Pet": PetModel},
    predefined_refs={"#/definitions/SomeType": SomeType},
)
model = builder.create_pydantic_model(schema)

predefined_models and predefined_refs can also be passed to create_model(...) directly. When a $ref key matches an entry in predefined_models, that class is reused instead of generating a new class. For non-model aliases (such as list[str] or TypeAliasType), use predefined_refs.

To give all generated models a common base class (shared config or methods), pass base_model_type:

from pydantic import BaseModel, ConfigDict

class FrozenBase(BaseModel):
    model_config = ConfigDict(frozen=True)

UserModel = create_model(schema, base_model_type=FrozenBase)

Error Handling

The library provides specific exceptions for different error cases:

from json_schema_to_pydantic import (
    SchemaError,     # Base class for all schema errors
    TypeError,       # Invalid or unsupported type
    CombinerError,   # Error in schema combiners
    ReferenceError,  # Error in schema references
)

try:
    model = create_model(schema)
except TypeError as e:
    print(f"Invalid type in schema: {e}")
except ReferenceError as e:
    print(f"Invalid reference: {e}")

Documentation

See docs/features.md for detailed documentation of supported JSON Schema features.

Contributing

  1. Fork the repository
  2. Create a new branch for your feature
  3. Make your changes
  4. Run tests and ensure they pass
  5. Submit a pull request

License

This project is licensed under the MIT License.

Metadata

Release files for json-schema-to-pydantic 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for json-schema-to-pydantic 0.5.0
File Size Uploaded Provenance
json_schema_to_pydantic-0.5.0.tar.gz 55.0 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for json-schema-to-pydantic 0.5.0
File Interpreter ABI Platform
json_schema_to_pydantic-0.5.0-py3-none-any.whl Python 3 none any Details

Total release size: 73.3 kB

Release files / json_schema_to_pydantic-0.5.0.tar.gz

Download URL json_schema_to_pydantic-0.5.0.tar.gz
Size 55.0 kB
Tags Source
SHA-256 checksum
How to use checksums
fb115538fe32d28e5689632d0b61da8a4135bbe994313869372a57a3d0aa2cc9
BLAKE2b-256 checksum
How to use checksums
6ce25c5263ead9368da59121c83ab7a47f9206f70ba1c81d89084bfbe804e851
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 21, 2026.

Transparency log

Release files / json_schema_to_pydantic-0.5.0-py3-none-any.whl

Download URL json_schema_to_pydantic-0.5.0-py3-none-any.whl
Size 18.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c484aa2a0f05ac22bc1866762bdaf563faa13f7641ba59e89fb73ff7cb460a27
BLAKE2b-256 checksum
How to use checksums
3ab3c82dbd4872634405a07c281dd51b7bb175b4a762937f65ea0e4635da212b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 21, 2026.

Transparency log

Security for json-schema-to-pydantic 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for json_schema_to_pydantic-0.5.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 21, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page