# datamodel-code-generator
π Generate Python data models from schema definitions in seconds.
π [Documentation](https://datamodel-code-generator.koxudaxi.dev/) Β·
π§ͺ [Playground](https://datamodel-code-generator.koxudaxi.dev/playground/) Β·
πΌ [Lead maintainer available for work](https://koxudaxi.dev/?utm_source=github_readme&utm_medium=top&utm_campaign=open_to_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.
[](https://pypi.python.org/pypi/datamodel-code-generator)
[](https://anaconda.org/conda-forge/datamodel-code-generator)
[](https://pepy.tech/projects/datamodel-code-generator)
[](https://pypi.python.org/pypi/datamodel-code-generator)
[](https://codecov.io/gh/koxudaxi/datamodel-code-generator)

[](https://pydantic.dev)
## β¨ 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:
```bash
uv tool install datamodel-code-generator
```
Conda users can install from conda-forge:
```bash
conda install -c conda-forge datamodel-code-generator
```
For projects that should pin the generator version, add it as a development dependency instead:
```bash
uv add --dev datamodel-code-generator
```
> [!NOTE]
> Community-maintained distribution packages are also available from
> [Debian](https://packages.debian.org/search?keywords=datamodel-codegen&searchon=names&suite=all§ion=all),
> [Ubuntu](https://packages.ubuntu.com/search?keywords=datamodel-codegen&searchon=names&suite=all§ion=all),
> [nixpkgs](https://search.nixos.org/packages?query=datamodel-code-generator), and
> [openSUSE Tumbleweed](https://software.opensuse.org/package/python-datamodel-code-generator).
> Availability and versions vary by distribution.
Other installation methods
**pip:**
```bash
pip install datamodel-code-generator
```
**uv (run without adding to project):**
```bash
uv run --with datamodel-code-generator datamodel-codegen --help
```
**With stable HTTP support** (for resolving remote `$ref`):
```bash
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](https://datamodel-code-generator.koxudaxi.dev/faq/#http-backend-selection)
for automatic and explicit selection behavior.
**With GraphQL support:**
```bash
pip install 'datamodel-code-generator[graphql]'
```
**With Protocol Buffers support:**
```bash
pip install 'datamodel-code-generator[protobuf]'
```
**Docker:**
```bash
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**
```bash
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](https://datamodel-code-generator.koxudaxi.dev/cli-reference/) for all options. See [Presets](https://datamodel-code-generator.koxudaxi.dev/presets/),
[`--preset`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/base-options/#preset), [`--input-file-type`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/base-options/#input-file-type), and
[`--output-model-type`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/model-customization/#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`](https://datamodel-code-generator.koxudaxi.dev/presets/#practical-py312-20260619).
Input (schema.json)
```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`)**
```python
# 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](https://datamodel-code-generator.koxudaxi.dev/formatter-behavior/) for details.
See [Performance Benchmarks](https://datamodel-code-generator.koxudaxi.dev/performance-benchmarks/) for release benchmark data and interactive charts.
---
## π Documentation
**π [Read the full documentation β](https://datamodel-code-generator.koxudaxi.dev/)**
- π§° [Presets](https://datamodel-code-generator.koxudaxi.dev/presets/) - Recommended option bundles for modern output
- π [Getting Started](https://datamodel-code-generator.koxudaxi.dev/getting-started/) - Installation and first model
- π₯οΈ [CLI Reference](https://datamodel-code-generator.koxudaxi.dev/cli-reference/) - All command-line options
- π§ͺ [Playground](https://datamodel-code-generator.koxudaxi.dev/playground/) - Try generation in your browser
- βοΈ [pyproject.toml](https://datamodel-code-generator.koxudaxi.dev/pyproject_toml/) - Configuration file
- π [CI/CD Integration](https://datamodel-code-generator.koxudaxi.dev/ci-cd/) - GitHub Actions, pre-commit hooks
- β [Conformance Dashboard](https://datamodel-code-generator.koxudaxi.dev/conformance/) - External corpus coverage signals
- π [Performance Benchmarks](https://datamodel-code-generator.koxudaxi.dev/performance-benchmarks/) - Release benchmark tables and interactive charts
- π§ [Architecture](https://datamodel-code-generator.koxudaxi.dev/architecture/) - Generation pipeline and synchronized component inventory
- π [One-liner Usage](https://datamodel-code-generator.koxudaxi.dev/oneliner/) - uvx, pipx, clipboard integration
- β [FAQ](https://datamodel-code-generator.koxudaxi.dev/faq/) - Common questions
---
## π₯ 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
- [pydantic v2](https://docs.pydantic.dev/) BaseModel
- [pydantic v2](https://docs.pydantic.dev/) dataclass
- [dataclasses](https://docs.python.org/3/library/dataclasses.html)
- [TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict)
- [msgspec](https://github.com/jcrist/msgspec) Struct
## β 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](https://datamodel-code-generator.koxudaxi.dev/conformance/)
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.
- **Generate a local schema file:** Pin the input type and destination when the source extension is ambiguous or generated output needs a stable path. Options: [`--input`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/base-options/#input), [`--input-file-type`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/base-options/#input-file-type), [`--output`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/base-options/#output).
- **Target Pydantic v2 on modern Python:** Set the output model family and Python/Pydantic compatibility targets together. Options: [`--output-model-type`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/model-customization/#output-model-type), [`--target-python-version`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/model-customization/#target-python-version), [`--target-pydantic-version`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/model-customization/#target-pydantic-version).
- **Use modern Python annotations:** Target a recent Python version and prefer built-in collection and union syntax in generated types. Options: [`--target-python-version`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/model-customization/#target-python-version), [`--use-union-operator`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/typing-customization/#use-union-operator), [`--use-standard-collections`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/typing-customization/#use-standard-collections).
- **Normalize incoming field names:** Convert source names to Python identifiers while preserving explicit alias data for runtime IO. Options: [`--snake-case-field`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/field-customization/#snake-case-field), [`--original-field-name-delimiter`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/field-customization/#original-field-name-delimiter), [`--aliases`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/field-customization/#aliases).
- **Generate operation-focused models:** Limit OpenAPI output to operation shapes and name models from operation IDs and status codes. Options: [`--openapi-scopes`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/openapi-only-options/#openapi-scopes), [`--use-operation-id-as-name`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/openapi-only-options/#use-operation-id-as-name), [`--use-status-code-in-response-name`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/openapi-only-options/#use-status-code-in-response-name).
- **Resolve remote references deliberately:** Enable remote `$ref` loading and configure request metadata, timeouts, or local ref roots. Options: [`--allow-remote-refs`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/general-options/#allow-remote-refs), [`--http-headers`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/general-options/#http-headers), [`--http-timeout`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/general-options/#http-timeout), [`--http-local-ref-path`](https://datamodel-code-generator.koxudaxi.dev/cli-reference/general-options/#http-local-ref-path).
See the [CLI Reference](https://datamodel-code-generator.koxudaxi.dev/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:
```bash
datamodel-codegen --generate-prompt "Best options for Pydantic v2?" | claude -p
```
See [LLM Integration](https://datamodel-code-generator.koxudaxi.dev/llm-integration/) for more examples.
### π Generate from URL
```bash
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](https://datamodel-code-generator.koxudaxi.dev/faq/#http-backend-selection).
### βοΈ Use with pyproject.toml
```toml
[tool.datamodel-codegen]
input = "schema.yaml"
output = "src/models.py"
output-model-type = "pydantic_v2.BaseModel"
```
Then simply run:
```bash
datamodel-codegen
```
See [pyproject.toml Configuration](https://datamodel-code-generator.koxudaxi.dev/pyproject_toml/) for more options.
### π CI/CD Integration
Validate generated models in your CI pipeline:
```yaml
# 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](https://datamodel-code-generator.koxudaxi.dev/ci-cd/) 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](docs/coding-agent-skill.md) for detailed guidance and troubleshooting.
Install the directory for your agent:
```bash
# 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