Skip to main content

datamodel-code-generator

🚀 Generate Python data models from schema definitions in seconds.

📚 Documentation · 🧪 Playground · 💼 Lead maintainer available for work

PyPI version Conda-forge Downloads PyPI - Python Version codecov license Pydantic v2

✨ What it does

Schema files, raw data, and existing Python models flow through datamodel-code-generator into Python model output types

Pick any one of the supported inputs and pick the Python model style you want as output. --input-model path/to/file.py:ClassName can even retarget an existing Pydantic, dataclass, or TypedDict class defined in another Python file to a different output type.

  • 📄 Converts OpenAPI 3, AsyncAPI, JSON Schema, Apache Avro, XML Schema, Protocol Buffers/gRPC, GraphQL, MCP tool schemas, and raw data (JSON/YAML/CSV) into Python models
  • 🐍 Generates from existing Python types (Pydantic, dataclass, TypedDict) via --input-model
  • 🎯 Generates Pydantic v2, Pydantic v2 dataclass, dataclasses, TypedDict, or msgspec output
  • 🔗 Handles complex schemas: $ref, allOf, oneOf, anyOf, enums, and nested types
  • ✅ Produces type-safe, validated code ready for your IDE and type checker

📦 Installation

Recommended for standalone CLI use:

uv tool install datamodel-code-generator

Conda users can install from conda-forge:

conda install -c conda-forge datamodel-code-generator

For projects that should pin the generator version, add it as a development dependency instead:

uv add --dev datamodel-code-generator
Other installation methods

pip:

pip install datamodel-code-generator

uv (run without adding to project):

uv run --with datamodel-code-generator datamodel-codegen --help

With stable HTTP support (for resolving remote $ref):

pip install 'datamodel-code-generator[http]'

The http extra is supported and is not deprecated. To require the experimental HTTPX2 backend instead, install datamodel-code-generator[httpx2] and pass --http-backend httpx2. The experimental extra is not included in datamodel-code-generator[all]. See HTTP backend selection for automatic and explicit selection behavior.

With GraphQL support:

pip install 'datamodel-code-generator[graphql]'

With Protocol Buffers support:

pip install 'datamodel-code-generator[protobuf]'

Docker:

docker pull koxudaxi/datamodel-code-generator

Published Docker images run as a non-root appuser. When writing generated files to a bind-mounted directory, make sure the directory is writable by the container user or pass an explicit Docker user, for example --user "$(id -u):$(id -g)".


🏃 Quick Start

Command

datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output-model-type pydantic_v2.BaseModel \
  --preset standard-py312-20260909 \
  --output model.py

This quick start uses standard-py312-20260909 as the modern Python 3.12 baseline. Preset names include the target Python version: py312 means Python 3.12.

See CLI Reference for all options. See Presets, --preset, --input-file-type, and --output-model-type for this command.

For more schema-aware output that preserves schema-authored names, reuses models, and embeds generated documentation, use practical-py312-20260909.

Input (schema.json)
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Pet",
  "type": "object",
  "required": ["name"],
  "properties": {
    "name": {
      "type": "string",
      "description": "The pet's name"
    },
    "species": {
      "type": "string",
      "enum": ["dog", "cat", "bird", "fish"],
      "default": "dog"
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "description": "Age in years"
    },
    "vaccinated": {
      "type": "boolean",
      "default": false
    }
  }
}

Output (model.py)

# generated by datamodel-codegen:
#   filename:  schema.json

from __future__ import annotations

from enum import StrEnum
from typing import Annotated

from pydantic import BaseModel, ConfigDict, Field


class Species(StrEnum):
    dog = 'dog'
    cat = 'cat'
    bird = 'bird'
    fish = 'fish'


class Pet(BaseModel):
    model_config = ConfigDict(
        populate_by_name=True,
    )
    name: Annotated[str, Field(description="The pet's name")]
    species: Species = Species.dog
    age: Annotated[int | None, Field(description='Age in years', ge=0)] = None
    vaccinated: bool = False

Choose a formatter

Choose a formatter to match your project and generation priorities:

  • Projects using Ruff: use --formatters ruff-check ruff-format to keep generated code consistent with the project's formatting and lint policy. Install it with pip install 'datamodel-code-generator[ruff]'.
  • No Ruff, Black, or isort, or generation speed is the priority: use --formatters builtin to avoid running external formatters on standard generated model modules.
  • Projects using Black/isort: keep --formatters black isort to preserve the project's formatting and existing generated output.

The current default remains Black/isort, which are still required dependencies. Omitting formatter options continues normal generation. The future builtin default is intended to reduce required installation dependencies and version constraints; Ruff will still be recommended for projects that use Ruff. Formatters are never selected automatically based on installed packages or Ruff configuration. The new [black] and [isort] extras prepare for later optional installation; their ranges and environment markers match the current required dependencies. Selecting only a formatter preserves your other generation settings; a preset also supplies model-generation options. Explicit formatter selection does not pin formatter versions or guarantee byte-for-byte output stability.

Custom templates can emit Python outside the standard generated model patterns covered by builtin, so custom-template output is not exhaustively validated. If --formatters builtin produces invalid or poorly formatted output with a custom template, please open an issue with a small reproducer. See Formatter Behavior for details.

See Performance Benchmarks for release benchmark data and interactive charts.


🌐 Generate a FastAPI server or an HTTP client (experimental)

From one OpenAPI document, --generate-server fastapi writes a FastAPI server package and --generate-client httpx2 an HTTPX2 client package, in the same run as the models. The models stay the runtime contract: routes and client methods take and return the generated models, so the server and the client parse and produce the same classes you already use. Every generated file is regenerated on each run; keep your own code outside the generated packages. The commands put everything in one application package, app: the generated app/models.py, app/server/, and app/client/, and your app/services/, so no generic top-level name such as models or server is taken.

This example is the FastAPI server tutorial, and the tests of this project run it as shown.

Input (openapi.yaml)
openapi: 3.1.0
info:
  title: Pets
  version: "1.0"
servers:
  - url: http://localhost:8000
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - name: limit
          in: query
          schema: {type: integer, minimum: 1, maximum: 100, default: 20}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pets"}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/NewPet"}
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{petId}:
    get:
      operationId: getPet
      tags: [pets]
      parameters:
        - name: petId
          in: path
          required: true
          schema: {type: integer}
      responses:
        "200":
          description: The pet.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "404":
          description: No pet has this ID.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Error"}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: array
      items: {$ref: "#/components/schemas/Pet"}
    Error:
      type: object
      required: [message]
      properties:
        message: {type: string}

Commands

# The application package app, which the generated packages go into
mkdir -p app && touch app/__init__.py

# FastAPI server package in app/server/
datamodel-codegen \
  --input openapi.yaml \
  --input-file-type openapi \
  --openapi-scopes schemas api \
  --output-model-type pydantic_v2.BaseModel \
  --preset standard-py312-20260909 \
  --output app/models.py \
  --generate-server fastapi \
  --server-output app/server \
  --server-package app.server \
  --server-model-package app.models

# HTTPX2 client package in app/client/
datamodel-codegen \
  --input openapi.yaml \
  --input-file-type openapi \
  --openapi-scopes schemas api \
  --output-model-type pydantic_v2.BaseModel \
  --preset standard-py312-20260909 \
  --output app/models.py \
  --generate-client httpx2 \
  --client-output app/client \
  --client-package app.client \
  --client-model-package app.models

--openapi-scopes must include api, and both need Python 3.11 or later, to run and as the target version (the preset sets 3.12); left unset, the run sets them and says how. Each run ends by printing the runtime dependencies of its package to stderr:

Add the runtime dependencies of app.server to your project:
  uv add "fastapi>=0.141.1" "pydantic>=2.14.0" "typing-extensions>=4.16"
Next steps: implement the stubs in app/services/pets.py, then run the server:
  uv add uvicorn && uv run uvicorn app.server.main:app --reload
or: uv add "fastapi[standard]" && uv run fastapi dev --entrypoint app.server.main:app
See app/server/README.md.
Add the runtime dependencies of app.client to your project:
  uv add "httpx2>=2.13.0" "typing-extensions>=4.16" "pydantic>=2.14.0"
Next steps: call the API with the client:
  from app.client import Client

  with Client(base_url=...) as client:
      client.pets.list_pets(...)
See app/client/README.md.

Generated files (trimmed)

app/
├── __init__.py
├── models.py
├── server/
├── services/
└── client/

Implement the server in app/services/pets.py, which generation wrote once with stubs, by replacing the stubs of the Pets class that subclasses the generated service Protocol; type checkers report a missing method or a mismatched signature:

from app import models
from app.server import HTTPResult
from app.server.services import PetsService


class Pets(PetsService):
    def __init__(self) -> None:
        self.pets: dict[int, models.Pet] = {}

    def list_pets(self, *, limit: int) -> models.Pets:
        return models.Pets(list(self.pets.values())[:limit])

    def create_pet(self, *, body: models.NewPet) -> models.Pet:
        pet = models.Pet(id=len(self.pets) + 1, name=body.name, tag=body.tag)
        self.pets[pet.id] = pet
        return pet

    def get_pet(self, *, pet_id: int) -> models.Pet | HTTPResult[models.Error]:
        if (pet := self.pets.get(pet_id)) is None:
            return HTTPResult(404, models.Error(message=f"Pet {pet_id} not found"))
        return pet
uv add uvicorn
uv run uvicorn app.server.main:app

Call it with the client in call.py, which sends to the document's server URL by default:

from app.client import Client
from app.client.errors import NotFoundError
from app.models import NewPet

with Client() as client:
    pet = client.pets.create_pet(body=NewPet(name="Mimi", tag="cat"))
    print(pet)
    for listed in client.pets.list_pets(limit=10).root:
        print(listed.name)
    try:
        client.pets.get_pet(pet_id=99)
    except NotFoundError as error:
        print(error.status_code, error.body)

It prints:

id=1 name='Mimi' tag='cat'
Mimi
404 message='Pet 99 not found'

AsyncClient offers the same methods as coroutines. See FastAPI Server Generation and Python Client Generation for every option, the pyproject.toml settings, authentication, and the Python API.


📖 Documentation

👉 Read the full documentation →


📥 Supported Input

  • OpenAPI 3 (YAML/JSON)
  • AsyncAPI (YAML/JSON)
  • JSON Schema
  • MCP tool schemas
  • XML Schema (XSD)
  • Protocol Buffers / gRPC (.proto)
  • Apache Avro schema (AVSC)
  • JSON data
  • YAML data
  • Python dictionary
  • CSV data
  • GraphQL schema
  • Python types (Pydantic, dataclass, TypedDict) via --input-model

📤 Supported Output

✅ Conformance Signals

CI exercises datamodel-code-generator against pinned external corpora for XML Schema, JSON Schema, AsyncAPI, Apache Avro, and Protocol Buffers. See the Conformance Dashboard for the generated summary of runner scripts, tox environments, CI jobs, expected corpus counts, and upstream sources.


🍳 Common Recipes

CLI option quick starts

Use these starting points when combining options; each option links to the generated CLI reference for details and examples.

See the CLI Reference for the full option list and category-specific recipes.

🤖 Get CLI Help from LLMs

Generate a prompt to ask LLMs about CLI options:

datamodel-codegen --generate-prompt "Best options for Pydantic v2?" | claude -p

See LLM Integration for more examples.

🌐 Generate from URL

pip install 'datamodel-code-generator[http]'
datamodel-codegen --url https://example.com/api/openapi.yaml --output model.py

The http extra is the stable, non-deprecated backend. For the experimental HTTPX2 alternative, pass --http-backend httpx2; see HTTP backend selection.

⚙️ Use with pyproject.toml

[tool.datamodel-codegen]
input = "schema.yaml"
output = "src/models.py"
output-model-type = "pydantic_v2.BaseModel"

Then simply run:

datamodel-codegen

See pyproject.toml Configuration for more options.

🔄 CI/CD Integration

Validate generated models in your CI pipeline:

# Replace vX.Y.Z with a released action version.
- uses: datamodel-code-generator/datamodel-code-generator@vX.Y.Z
  with:
    input: schemas/api.yaml
    output: src/models/api.py

See CI/CD Integration for more options.


Coding agent skill

This repository includes an experimental Agent Skill that teaches compatible coding agents to run datamodel-codegen when generating Python models from OpenAPI, AsyncAPI, JSON Schema, GraphQL, JSON/YAML/CSV sample data, MCP tool schemas, Protocol Buffers, XML Schema, Apache Avro, or existing Python model objects.

See Coding Agent Skill for detailed guidance and troubleshooting.

Install the bundled skill directly from the CLI:

# Codex, project-local
datamodel-codegen --install-skill codex

# Claude Code, project-local
datamodel-codegen --install-skill claude-code

For a personal install, add --skill-scope user. Existing skills are preserved unless you explicitly add --overwrite-skill.

Check your agent's current documentation for exact search paths.


💖 Sponsors

OpenAI Logo

OpenAI


🏢 Projects that use datamodel-code-generator

These public examples are grouped by how each project uses datamodel-code-generator.

Code generation and runtime integration

Development, testing, and evaluation

See all dependents →



🤝 Contributing

See Development & Contributing for how to get started!


👥 Maintainers


📄 License

MIT License - see LICENSE for details.

Metadata

Release files for datamodel-code-generator 0.84.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 datamodel-code-generator 0.84.0
File Size Uploaded
datamodel_code_generator-0.84.0.tar.gz 5.6 MB Details

Built distribution (wheel)

Table of built distributions (wheels) for datamodel-code-generator 0.84.0
File Interpreter ABI Platform
datamodel_code_generator-0.84.0-py3-none-any.whl Python 3 none any Details

Total release size: 7.1 MB

Release files / datamodel_code_generator-0.84.0.tar.gz

Download URL datamodel_code_generator-0.84.0.tar.gz
Size 5.6 MB
Tags Source
SHA-256 checksum
How to use checksums
bb3d44d8e4d89f2fc17c5af3f5b64eb662f46bdb10e4f126e62bd44e67d0d4bc
BLAKE2b-256 checksum
How to use checksums
b5644235e7e4e6ac6a6c76516f09cbb6a86269d7dc3891f2701a19478ea76693
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 15, 2026.

Transparency log

Release files / datamodel_code_generator-0.84.0-py3-none-any.whl

Download URL datamodel_code_generator-0.84.0-py3-none-any.whl
Size 1.5 MB
Tags Python 3
SHA-256 checksum
How to use checksums
b887be83ad9c810fbaca642622724eb02d0a4f0c857e0fc57829dbec53460adf
BLAKE2b-256 checksum
How to use checksums
edb07af5ffc79e3dcd0925f1865b9902e5c0751383e73fe48435420e889c7cf3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 15, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.84.0 This release

2 release files

0.83.0

2 release files

0.82.0

2 release files

0.81.0

2 release files

0.80.0

2 release files

0.79.0

2 release files

0.76.0

2 release files

0.75.1

2 release files

0.75.0

2 release files

0.74.0

2 release files

0.73.0

2 release files

0.72.4

2 release files

0.72.3

2 release files

0.71.0

2 release files

0.70.0

2 release files

0.69.0

2 release files

0.66.1

2 release files

0.66.0

2 release files

0.65.1

2 release files

0.65.0

2 release files

0.64.1

2 release files

0.64.0

2 release files

0.63.0

2 release files

0.62.0

2 release files

0.59.0

2 release files

0.58.0

2 release files

0.56.1

2 release files

0.55.0

2 release files

0.54.0

2 release files

0.53.0

2 release files

0.50.0

2 release files

0.49.0

2 release files

0.48.0

2 release files

0.47.0

2 release files

0.46.0

2 release files

0.45.0

2 release files

0.44.0

2 release files

0.43.1

2 release files

0.43.0

2 release files

0.36.0

2 release files

0.34.0

2 release files

0.33.0

2 release files

0.32.0

2 release files

0.31.2

2 release files

0.31.1

2 release files

0.31.0

2 release files

0.30.1

2 release files

0.30.0

2 release files

0.29.0

2 release files

0.28.5

2 release files

0.28.4

2 release files

0.28.3

2 release files

0.28.2

2 release files

0.28.1

2 release files

0.28.0

2 release files

0.27.3

2 release files

0.26.5

2 release files

0.26.4

2 release files

0.26.3

2 release files

0.26.2

2 release files

0.26.1

2 release files

0.25.7

2 release files

0.25.6

2 release files

0.25.5

2 release files

0.25.4

2 release files

0.25.2

2 release files

0.25.1

2 release files

0.25.0

2 release files

0.24.2

2 release files

0.24.1

2 release files

0.24.0

2 release files

0.22.0

2 release files

0.21.2

2 release files

0.19.0

2 release files

0.18.1

2 release files

0.18.0

2 release files

0.17.2

2 release files

0.17.0

2 release files

0.16.1

2 release files

0.16.0

2 release files

0.14.1

2 release files

0.14.0

2 release files

0.13.4

2 release files

0.13.3

2 release files

0.13.2

2 release files

0.13.1

2 release files

0.13.0

2 release files

0.12.3

2 release files

0.12.2

2 release files

0.12.1

2 release files

0.12.0

2 release files

0.11.9

2 release files

0.11.8

2 release files

0.11.6

2 release files

0.11.5

2 release files

0.11.3

2 release files

0.11.2

2 release files

0.11.1

2 release files

0.11.0

2 release files

0.10.3

2 release files

0.10.1

2 release files

0.10.0

2 release files

0.9.4

2 release files

0.9.3

2 release files

0.9.2

2 release files

0.9.1

2 release files

0.9.0

2 release files

0.8.3

2 release files

0.8.2

2 release files

0.8.1

2 release files

0.8.0

2 release files

0.7.3

2 release files

0.7.2

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.26

2 release files

0.6.25

2 release files

0.6.24

2 release files

0.6.23

2 release files

0.6.22

2 release files

0.6.21

2 release files

0.6.20

2 release files

0.6.19

2 release files

0.6.16

2 release files

0.6.15

2 release files

0.6.14

2 release files

0.6.13

2 release files

0.6.12

2 release files

0.6.11

2 release files

0.6.9

2 release files

0.6.8

2 release files

0.6.7

2 release files

0.6.6

2 release files

0.6.5

2 release files

0.6.4

2 release files

0.6.3

2 release files

0.6.2

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.35

2 release files

0.5.34

2 release files

0.5.33

2 release files

0.5.32

2 release files

0.5.31

2 release files

0.5.29

2 release files

0.5.28

2 release files

0.5.27

2 release files

0.5.26

2 release files

0.5.25

2 release files

0.5.22

2 release files

0.5.21

2 release files

0.5.20

2 release files

0.5.19

2 release files

0.5.18

2 release files

0.5.17

2 release files

0.5.16

2 release files

0.5.15

2 release files

0.5.14

2 release files

0.5.13

2 release files

0.5.12

2 release files

0.5.11

2 release files

0.5.10

2 release files

0.5.9

2 release files

0.5.8

2 release files

0.5.7

2 release files

0.5.6

2 release files

0.5.5

2 release files

0.5.4

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.11

2 release files

0.4.9

2 release files

0.4.8

2 release files

0.4.7

2 release files

0.4.6

2 release files

0.4.5

2 release files

0.4.4

2 release files

0.4.3

2 release files

0.4.2

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.3

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.16

2 release files

0.2.14

2 release files

0.2.13

2 release files

0.2.11

2 release files

0.2.10

2 release files

0.2.9

2 release files

0.2.8

2 release files

0.2.7

2 release files

0.2.6

2 release files

0.2.5

2 release files

0.2.4

2 release files

0.2.3

2 release files

0.2.2

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.0

2 release files

0.0.6

2 release files

0.0.5

2 release files

0.0.4

2 release files

0.0.3

2 release files

0.0.2

2 release files

0.0.1

2 release files

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