[!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.
✨ What it does
Pick any one of the supported inputs and pick the Python model style you want as output. From OpenAPI (and, for
clients, AsyncAPI), the same run can also write a typed client or a FastAPI server package (experimental).
Generation is deterministic with a preset, which turns the header timestamp off, and
exits with 1 when the files on disk differ from what the schema generates, so CI catches drift.
can even retarget an existing Pydantic, dataclass, or TypedDict class defined
in another Python file to a different output type.
datamodel-codegen --check
--input-model path/to/file.py:ClassName
📄 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 a typed HTTPX2 client (--generate-client httpx2, from OpenAPI and AsyncAPI) or a FastAPI server (--generate-server fastapi, from OpenAPI) together with the models (experimental)
🤖 Turns the generated client into tools an agent searches, reads the schemas of, and calls, with an MCP server over them (--client-tools functions or mcp, experimental)
📝 Writes the recommended options into pyproject.toml (--recommend-options --write-pyproject-config, experimental)
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)".
This quick start uses standard-py312-20261127 as the modern Python 3.12 baseline.
Preset names include the target Python version: py312 means Python 3.12.
For more schema-aware output that preserves schema-authored names, reuses models, and embeds generated
documentation, use practical-py312-20261127.
Not sure which options fit your schema? Add --recommend-options to the command above (experimental). It
analyses the schema and prints the options to add on top of the latest preset with the reason for each, and a ready
command and pyproject.toml block. See
Option recommendations.
# 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. The
[jinja2] (custom templates), [genson] (JSON, YAML, CSV and dict data input) and [argcomplete] (shell
completion) extras do the same for those 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.
🌐 Generate a FastAPI server or an HTTP client (experimental)
[!WARNING]
Server and client generation are experimental since 0.84.0: their options and generated packages may change.
See Experimental Features.
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.
# 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-20261127 \
--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-20261127 \
--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.
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'
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.
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, --input-file-type, --output.
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.
For a personal install, add --skill-scope user. Existing skills are preserved
unless you explicitly add --overwrite-skill.
To install without the Python package, for example in Claude Code, run claude plugin marketplace add datamodel-code-generator/datamodel-code-generator and then claude plugin install datamodel-code-generator@datamodel-code-generator. See Install from the repository for other agents.
Check your agent's current documentation for exact search paths.
fastapi-code-generator - Generate FastAPI app from OpenAPI. To generate a FastAPI server with this project, see --generate-server fastapi and the migration guide