datamodel-code-generator is a free, open source api development & testing project written in Python and released under MIT. It has 4,047 GitHub stars, 484 forks and 23 open issues, and was last pushed 14 hours ago. On this registry it ranks #62 of 187 tracked projects in API Development & Testing, with 5 head-to-head comparisons available. It gained 20 stars over the last 30 tracked days.

What is datamodel-code-generator?

datamodel-code-generator is an MIT-licensed Python code generator that turns OpenAPI 3, AsyncAPI, JSON Schema, Apache Avro, XML Schema, Protocol Buffers/gRPC, GraphQL, MCP tool schemas, and raw JSON/YAML/CSV into type-safe Pydantic v2 models, Pydantic v2 dataclasses, dataclasses, TypedDict, or msgspec.Struct classes, for Python developers who need models that match an external schema without writing them by hand.

What it is

The project ships a command-line tool, datamodel-codegen, distributed as the Python package datamodel-code-generator on PyPI and conda-forge. It lives squarely in the Python data-validation ecosystem: its topics include pydantic, fastapi, and msgspec, and it emits code targeting Pydantic v2 as a first-class output. The documentation and a browser playground are hosted at datamodel-code-generator.koxudaxi.dev. A maintainer is listed as available for work in the README header, and the repository carries 4,019 stars, 460 forks, and 23 open issues, with the last push on 17 September 2026.

The concrete problem it solves is the hand-written, hand-maintained model class. When a schema lives somewhere else — an OpenAPI 3 document, a JSON Schema file, an Avro or Protobuf definition, a GraphQL schema — the Python classes that mirror it are normally written manually and drift out of sync as the schema changes. This tool generates them instead, resolving $ref, allOf, oneOf, anyOf, enums, and nested types along the way, and producing code meant to pass an IDE and a type checker. It can also retarget existing Python classes: --input-model path/to/file.py:ClassName reads a Pydantic, dataclass, or TypedDict class defined in another file and re-emits it in a different output style.

Key capabilities

  • Converts OpenAPI 3, AsyncAPI, JSON Schema, Apache Avro, XML Schema, Protocol Buffers/gRPC, GraphQL, MCP tool schemas, and raw JSON, YAML, or CSV input into Python models.
  • Generates Pydantic v2, Pydantic v2 dataclass, dataclasses, TypedDict, or msgspec output from a single chosen input.
  • Handles $ref, allOf, oneOf, anyOf, enums, and nested types.
  • Retargets existing Python types with --input-model path/to/file.py:ClassName, converting between Pydantic, dataclass, and TypedDict shapes.
  • Resolves remote $ref through the http extra, installed as datamodel-code-generator[http]; --http-backend httpx2 selects the experimental HTTPX2 backend instead, which is not included in datamodel-code-generator[all].
  • Offers a browser playground that runs generation locally with Pyodide, sending no schema to a backend; shared reproduction URLs encode options in the #state=... fragment, which browsers do not transmit to the server.
  • Exposes the CLI entry point datamodel-codegen, runnable without installation as uv run --with datamodel-code-generator datamodel-codegen --help.

Who uses it and how

  • Teams that need reproducible code generation pin the generator as a development dependency with uv add --dev datamodel-code-generator rather than tracking the latest release.
  • Individual developers installing for standalone CLI use run uv tool install datamodel-code-generator.
  • Conda users install from conda-forge with conda install -c conda-forge datamodel-code-generator; community-maintained distribution packages also exist for Debian, Ubuntu, nixpkgs, and openSUSE Tumbleweed, though availability and versions vary by distribution.
  • Python API developers, including the FastAPI users implied by the project topics, generate request and response models from an OpenAPI 3 document.
  • Evaluation is supported without any install through the playground, where generation runs in the browser via Pyodide.

Getting started

Install the CLI with uv tool install datamodel-code-generator, or with pip install datamodel-code-generator; add the http extra when remote $ref resolution is needed. Then invoke datamodel-codegen against a schema file.

How it compares

The facts provided name no comparable tools and no paid products that this project replaces, so datamodel-code-generator stands alone in this registry rather than sitting within a documented field of alternatives. What distinguishes it here is what is recorded above: an MIT licence, a published Python package with a CLI entry point, and breadth across many input schema formats with several selectable Python output styles.

When to use it — and when not to

There is no service to operate: this is a command-line tool and a Python package, so the operational burden is a Python toolchain rather than a database, storage layer, or mail server. Teams that want a hosted generation API, or that are not working in Python, should look elsewhere, since the only hosted surface is a browser playground that runs generation locally. One honest caveat from the material here: the README excerpt is truncated mid-way through the GraphQL installation section, so the full setup for that input is not visible in this entry, and the HTTPX2 backend remains experimental.

project readme (upstream, from github) — read inline

datamodel-code-generator

🚀 Generate Python data models from schema definitions in seconds.

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

[!NOTE] Playground privacy: Generation runs locally in your browser with Pyodide. Your schema and options are not sent to a backend. Shared repro URLs encode them in the URL fragment (#state=...), which browsers do not send to the server; the full URL can still be stored in your browser history or wherever you share it.

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

✨ What it does

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

[!NOTE] Community-maintained distribution packages are also available from Debian, Ubuntu, nixpkgs, and openSUSE Tumbleweed. Availability and versions vary by distribution.

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.


📖 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


🏢 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 →


🔗 Related Projects


🤝 Contributing

See Development & Contributing for how to get started!


👥 Maintainers


📄 License

MIT License - see LICENSE for details.

Frequently asked questions

Is datamodel-code-generator free to use?

datamodel-code-generator is open source under the MIT licence. There is no licence fee and no seat count — you can self-host it or, where the project offers one, pay a vendor for a managed version instead.

What does datamodel-code-generator do?

Generate Pydantic v2 models, dataclasses, TypedDict, and msgspec.Struct from OpenAPI, JSON Schema, GraphQL, Avro, Protobuf, and raw JSON/YAML/CSV.

What is datamodel-code-generator written in?

datamodel-code-generator is primarily written in Python. Its source is publicly available at https://github.com/datamodel-code-generator/datamodel-code-generator, and it has 4,047 GitHub stars.