Datamodel Code Generator Agent Skill

by datamodel-code-generator• 4k•• Scanned•Claim this listing•Request removal
Data Science & MLagent skillscode generatorcsvdataclassdatamodel

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

Datamodel Code Generator is an open-source agent skill by datamodel-code-generator, written mainly in Python, with 4,048 GitHub stars and the MIT license. Its code was last updated Nov 1, 2026. The latest PyPI release is datamodel-code-generator 0.96.0, published Nov 13, 2026, with 4,059,396 downloads last week.

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

<!-- Source of truth: docs/assets/diagrams/hero.mmd — regenerate with `tox run -e diagrams` --> <p align="center"> <picture> <source media="(prefers-color-scheme: dark)" srcset="docs/assets/diagrams/hero-dark.svg"> <img alt="Schema files, raw data, and existing Python models flow through datamodel-code-generator into Python model output types and experimental HTTPX2 client and FastAPI server packages" src="docs/assets/diagrams/hero-light.svg" width="760"> </picture> </p>

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
  • 🌐 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)
  • 🔗 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.

<details> <summary>Other installation methods</summary>

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)".

</details>

🏃 Quick Start

<!-- BEGIN AUTO-GENERATED PRESET QUICK START -->

Command

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

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

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.

<details> <summary>Input (<code>schema.json</code>)</summary>
{
  "$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
    }
  }
}
</details>

Output (model.py)

<!-- fmt: off -->
# 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
<!-- fmt: on -->

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.

See Performance Benchmarks for release benchmark data and interactive charts.

<!-- END AUTO-GENERATED PRESET QUICK START -->

🌐 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.

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

<!-- BEGIN AUTO-GENERATED DOC EXAMPLE: readme.server-client.openapi --> <details> <summary>Input (<code>openapi.yaml</code>)</summary> <!-- fmt: off -->
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}
<!-- fmt: on --> </details> <!-- END AUTO-GENERATED DOC EXAMPLE: readme.server-client.openapi -->

Commands

<!-- BEGIN AUTO-GENERATED DOC EXAMPLE: readme.server-client.commands --> <!-- fmt: off -->
# 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-20261113 \
  --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-20261113 \
  --output app/models.py \
  --generate-client httpx2 \
  --client-output app/client \
  --client-package app.client \
  --client-model-package app.models
<!-- fmt: on --> <!-- END AUTO-GENERATED DOC EXAMPLE: readme.server-client.commands -->

--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:

<!-- BEGIN AUTO-GENERATED DOC EXAMPLE: readme.server-client.notice --> <!-- fmt: off -->
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.
<!-- fmt: on --> <!-- END AUTO-GENERATED DOC EXAMPLE: readme.server-client.notice -->

Generated files (trimmed)

<!-- BEGIN AUTO-GENERATED DOC EXAMPLE: readme.server-client.tree --> <!-- fmt: off -->
app/
├── __init__.py
├── models.py
├── server/
├── services/
└── client/
<!-- fmt: on --> <!-- END AUTO-GENERATED DOC EXAMPLE: readme.server-client.tree -->

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:

<!-- BEGIN AUTO-GENERATED DOC EXAMPLE: readme.server-client.app --> <!-- fmt: off -->
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
<!-- fmt: on --> <!-- END AUTO-GENERATED DOC EXAMPLE: readme.server-client.app -->
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:

<!-- BEGIN AUTO-GENERATED DOC EXAMPLE: readme.server-client.call --> <!-- fmt: off -->
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)
<!-- fmt: on --> <!-- END AUTO-GENERATED DOC EXAMPLE: readme.server-client.call -->

It prints:

<!-- BEGIN AUTO-GENERATED DOC EXAMPLE: readme.server-client.output --> <!-- fmt: off -->
id=1 name='Mimi' tag='cat'
Mimi
404 message='Pet 99 not found'
<!-- fmt: on --> <!-- END AUTO-GENERATED DOC EXAMPLE: readme.server-client.output -->

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

<!-- BEGIN AUTO-GENERATED README 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
<!-- END AUTO-GENERATED README SUPPORTED INPUT -->

📤 Supported Output

<!-- BEGIN AUTO-GENERATED README SUPPORTED OUTPUT --> <!-- END AUTO-GENERATED README 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

<!-- BEGIN AUTO-GENERATED CLI RECIPE QUICK STARTS -->

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.

<!-- END AUTO-GENERATED CLI RECIPE QUICK STARTS -->

🤖 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.

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.


💖 Sponsors

<table> <tr> <td valign="top" align="center"> <a href="https://github.com/openai"> <img src="https://avatars.githubusercontent.com/u/14957082?s=200&v=4" alt="OpenAI Logo" style="width: 100px;"> <p>OpenAI</p> </a> </td> </tr> </table>

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

Datamodel Code Generator alternatives

View more →

Similar agent skills in Data Science & ML, ranked by GitHub stars. Compare licence, recent activity and scan status before you choose.

NameStarsLicenceLast updatedScan
Datamodel Code Generator (this page)
datamodel-code-generator
4kMITNov 1, 2026Scanned, no flagged issues
Elephant Goldfish Model
google
8.4kApache-2.0Oct 30, 2026Scanned, no flagged issues
Knowhere
Ontos-AI
3.9kApache-2.0Oct 31, 2026Scanned, no flagged issues
Natively Cluely AI Assistant
Natively-AI-assistant
3.1kNone foundNov 1, 2026Not scanned yet
J Space Cognition Suite
Tiger3807861189
3kApache-2.0Sep 14, 2026Scanned, no flagged issues
Fable Method
Sahir619
2.3kMITOct 3, 2026Scanned, no flagged issues