ランキングに戻る

koxudaxi/datamodel-code-generator

Pythondatamodel-code-generator.koxudaxi.dev

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

openapicode-generatorpythonpydanticgeneratorfastapijson-schemadatamodelswaggeryamlcsvopenapi-codegen
スター成長
スター
4k
フォーク
450
週間成長
Issue
18
1k2k3k
2023年1月2024年3月2025年5月2026年7月
成果物PyPIpip install datamodel-code-generator
README

datamodel-code-generator

🚀 Generate Python data models from schema definitions in seconds.

🧪 Try it in your browser: Playground

[!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

📣 💼 Maintainer update: Open to opportunities. 🔗 koxudaxi.dev

✨ 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

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

conda:

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

With HTTP support (for resolving remote $ref):

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

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-20260619 \
  --output model.py

This quick start uses standard-py312-20260619 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-20260619.

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

⚡ Speed up generation

By default, generated Python is currently formatted with black and isort. For faster generation without external formatter dependencies, add --formatters builtin for standard generated model modules. In a future version, the Black/isort dependencies will become opt-in and the default formatter will change to builtin.

If you prefer Ruff, install it with pip install 'datamodel-code-generator[ruff]' and use --formatters ruff-check ruff-format for a fast external formatter.

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

👉 datamodel-code-generator.koxudaxi.dev


📥 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

⚙️ 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: koxudaxi/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 directory for your agent:

# Codex, project-local
mkdir -p .agents/skills
cp -R skills/datamodel-code-generator .agents/skills/datamodel-code-generator

# Claude Code, project-local
mkdir -p .claude/skills
cp -R skills/datamodel-code-generator .claude/skills/datamodel-code-generator

For a personal install, copy the same directory to $HOME/.agents/skills/datamodel-code-generator/ for Codex or ~/.claude/skills/datamodel-code-generator/ for Claude Code.

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


💖 Sponsors

Astral Logo

Astral

OpenAI Logo

OpenAI


🏢 Projects that use datamodel-code-generator

These projects use datamodel-code-generator. See the linked examples for real-world usage.

See all dependents →



🤝 Contributing

See Development & Contributing for how to get started!


👤 Maintainer

Koudai Aono (@koxudaxi)


📄 License

MIT License - see LICENSE for details.

関連リポジトリ
open-webui/open-webui

User-friendly AI Interface (Supports Ollama, OpenAI API, ...)

PythonPyPIOtherollamaollama-webui
openwebui.com
146.3k21.2k
fastapi/fastapi

FastAPI framework, high performance, easy to learn, fast to code, ready for production

PythonPyPIMIT Licensepythonjson
fastapi.tiangolo.com
100.8k9.7k
usebruno/bruno

Opensource IDE For Exploring and Testing API's (lightweight alternative to Postman/Insomnia)

JavaScriptnpmMIT Licenseapi-clientgit
usebruno.com
45.8k2.7k
fastapi/full-stack-fastapi-template

Full stack, modern web application template. Using FastAPI, React, SQLModel, PostgreSQL, Docker, GitHub Actions, automatic HTTPS and more.

TypeScriptnpmMIT Licensepythonjson
44.4k8.8k
OAI/OpenAPI-Specification

The OpenAPI Specification Repository

MarkdownApache License 2.0openapiopenapi-specification
openapis.org
31.1k9.2k
swagger-api/swagger-ui

Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.

JavaScriptnpmApache License 2.0swaggerswagger-ui
swagger.io
28.9k9.3k
OpenAPITools/openapi-generator

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

JavaMavenApache License 2.0rest-apirest-client
openapi-generator.tech
26.6k7.6k
Redocly/redoc

📘 OpenAPI/Swagger-generated API Reference Documentation

TypeScriptnpmMIT Licenseopenapiswagger
redocly.github.io/redoc/
25.8k2.4k
grpc-ecosystem/grpc-gateway

gRPC to JSON proxy generator following the gRPC HTTP spec

GoGo ModulesBSD 3-Clause "New" or "Revised" Licensegogrpc
grpc-ecosystem.github.io/grpc-gateway/
20k2.4k
scalar/scalar

Scalar is an open-source API platform:                                       🌐 Modern REST API Client                                        📖 Beautiful API References                                        ✨ 1st-Class OpenAPI/Swagger Support

TypeScriptnpmMIT Licenseapidocs
scalar.com
15.7k902
swaggo/swag

Automatically generate RESTful API documentation with Swagger 2.0 for Go.

GoGo ModulesMIT Licensegolangswagger
12.9k1.4k
tadata-org/fastapi_mcp

Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!

PythonPyPIMIT Licenseaiclaude
fastapi-mcp.tadata.com
12k950