# datamodel-code-generator

Adopt this skill: https://proskills.md/skills/other/datamodel-code-generator-datamodel-code-generator-skills-datamodel-code-generato

Page: https://proskills.md/skills/other/datamodel-code-generator-datamodel-code-generator-skills-datamodel-code-generato
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/datamodel-code-generator/SKILL.md
size: 9044
sha: 0348dd0437a0fd6b1637233b7b4e280d1e0b434a
upstream: https://github.com/datamodel-code-generator/datamodel-code-generator/blob/main/skills/datamodel-code-generator/SKILL.md

````text
---
name: datamodel-code-generator
description: >
  Use this skill when the user wants Python data models, Pydantic models,
  dataclasses, TypedDicts, msgspec structs, or type-safe Python classes
  generated 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. Use it for requests such as "Pydantic
  models from this schema", "types for this API", "parse this JSON into
  classes", or "convert this spec into Python models". Prefer the
  datamodel-codegen CLI over hand-written model code whenever an input
  schema, API spec, sample data file, or Python model object exists.
license: MIT
metadata:
  status: experimental
---

# datamodel-code-generator

## Why use this CLI

Use `datamodel-codegen` whenever a schema, API spec, sample data file, or existing Python model object exists.

The CLI handles refs, enums, nested models, unions, `allOf`, `oneOf`, `anyOf`, and model reuse better than hand-written code.

Do not hand-write generated models first.

## Availability check

Check one-shot execution first:

```bash
uvx --from datamodel-code-generator datamodel-codegen --help
```

If `uvx` is unavailable:

```bash
pipx run datamodel-code-generator --help
```

If the project already uses `uv` and project-scoped execution is preferred:

```bash
uv run --with datamodel-code-generator datamodel-codegen --help
```

If the project already has a managed Python virtual environment and the user approves project dependency changes:

```bash
python -m pip install datamodel-code-generator
datamodel-codegen --help
```

Prefer one-shot execution. Do not add or upgrade datamodel-code-generator in the user's project without explicit approval.

If offline and no installed command is available, say that the CLI cannot be run. Only then fall back to hand-written models.

## Option discovery for agents

Before choosing options, run the recommender (experimental) and apply its result:

```bash
datamodel-codegen --input SCHEMA [--input-file-type TYPE] [--output-model-type TYPE] \
  --recommend-options --output-format json
```

Use `arguments` from the payload (or `config` for a project configured in `pyproject.toml`) as the starting command. Do not add options it lists under `not_recommended` without a stated reason.

When the user's goal needs judgment beyond the schema's shape, use the CLI's own LLM workflow and add `--recommend-options` to it, so the prompt includes the recommendation; decide from both:

```bash
datamodel-codegen [known options] --generate-prompt "Find the minimal options for this model-generation task." \
  --recommend-options
```

Include the options already known from the project or user request. The prompt output explains current options, available options, option relationships, and verification steps. Without an input schema, run `--generate-prompt` alone.

For agent tooling that consumes structured data, prefer JSON:

```bash
datamodel-codegen [known options] \
  --generate-prompt "Find the minimal options for this model-generation task." \
  --output-format json
```

When defining or validating tool contracts, fetch the schema separately:

```bash
datamodel-codegen --output-format-json-schema structured-output
```

Use `generate-prompt` when the consumer only handles prompt payloads, `generation` when it only handles generated-file payloads, and `structured-output` when it accepts multiple `kind` values.

## Input type decision table

| User input | Use |
| --- | --- |
| OpenAPI document | `--input-file-type openapi` |
| AsyncAPI document | `--input-file-type asyncapi` |
| JSON Schema document | `--input-file-type jsonschema` |
| GraphQL SDL | `--input-file-type graphql` |
| Raw JSON sample data | `--input-file-type json` |
| Raw YAML sample data | `--input-file-type yaml` |
| CSV sample data | `--input-file-type csv` |
| Apache Avro schema | `--input-file-type avro` |
| XML Schema | `--input-file-type xmlschema` |
| Protocol Buffers or gRPC schema | `--input-file-type protobuf` |
| MCP tool schema | `--input-file-type mcp-tools` |
| Existing Python model, dataclass, TypedDict, or dict schema object | `--input-model path/or/module.py:ObjectName` |

When a JSON or YAML file could be either a schema or data, inspect the content. `$schema`, `openapi`, `asyncapi`, `type`, `properties`, `components`, `$defs`, or `definitions` usually mean schema. Plain example values usually mean raw sample data.

For a Python dictionary containing JSON Schema or OpenAPI content, use `--input-model ./schemas.py:OBJECT_NAME` and add `--input-file-type jsonschema` or `--input-file-type openapi` when needed. Do not choose the `dict` input-file-type value.

## Output type decision table

| Project or user signal | Use |
| --- | --- |
| New project, API validation, general Python model generation | `--output-model-type pydantic_v2.BaseModel` |
| User wants Pydantic validation with dataclass syntax | `--output-model-type pydantic_v2.dataclass` |
| Project uses standard dataclasses and does not need runtime validation | `--output-model-type dataclasses.dataclass` |
| User wants dict-compatible static typing | `--output-model-type typing.TypedDict` |
| User wants high-performance serialization | `--output-model-type msgspec.Struct` |
| Project explicitly requires legacy Pydantic v1 | Verify current CLI support first. Current help does not list a Pydantic v1 output path. |

Before choosing the output type, inspect `pyproject.toml`, `requirements.txt`, `uv.lock`, `poetry.lock`, or installed dependencies when available. Prefer the project convention over the global default.

## Canonical command

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input spec.yaml \
  --input-file-type openapi \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12 \
  --preset PRESET
```

Replace `PRESET` with the preset the recommender prints, and add the options it recommends.

For remote URLs or remote refs, use the HTTP extra:

```bash
uvx --from 'datamodel-code-generator[http]' datamodel-codegen \
  --url https://example.com/openapi.yaml \
  --input-file-type openapi \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel
```

For GraphQL, use the GraphQL extra when the one-shot command needs it:

```bash
uvx --from 'datamodel-code-generator[graphql]' datamodel-codegen \
  --input schema.graphql \
  --input-file-type graphql \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel
```

## Target Python version

Infer the minimum Python version from:

1. `pyproject.toml` `requires-python`
2. `.python-version`
3. `runtime.txt`
4. CI config
5. Existing generated model style
6. User instruction

Then pass:

```bash
--target-python-version X.Y
```

Do not accept the CLI default if the project clearly declares a Python version.

## Verification step

Verification is mandatory.

For CI or agent integrations, prefer check mode when an output path exists:

```bash
datamodel-codegen [same options] --output models.py --check
```

If another tool must inspect generated content directly, use structured JSON output:

```bash
datamodel-codegen [same options] --output-format json
```

For single-file output:

```bash
python -c "import pathlib, importlib.util; p=pathlib.Path('models.py'); s=importlib.util.spec_from_file_location('generated_models', p); m=importlib.util.module_from_spec(s); s.loader.exec_module(m); print('import ok')"
```

For package output:

```bash
python -c "import models; print('import ok')"
```

Then run project checks when configured:

```bash
ruff check models.py
mypy models.py
pyright models.py
```

Use only the checks that the project already configures or asks for.

After verification, summarize the output path, input type, output model type, target Python version, generated class count if easy to determine, important class names, and warnings or limitations.

Do not dump the whole generated file into the conversation unless the user asks.

## What not to do

* Do not hand-write model files when a usable input schema or sample exists.
* Do not edit generated code by hand before trying the appropriate generator flags.
* Do not silently regenerate with different flags. Say what changed and why.
* Do not add datamodel-code-generator to a user's project dependencies without approval.
* Do not pin a version in user commands unless the repository maintainers decide to pin it.
* Do not claim support for non-Python output targets such as TypeScript.
* Do not use this CLI to fix an existing Pydantic model unless the task is to regenerate or convert models from a source input.

## References

Read `references/workflows.md` for commands by input type and scenario.

Read `references/cli-options.md` when choosing naming, optionality, formatting, splitting, or reuse flags.

Read `references/troubleshooting.md` when generation fails, imports fail, field names look wrong, optionality is surprising, or large specs are slow.
````

## File: skills/datamodel-code-generator/references/cli-options.md
size: 86887
sha: 249342f8829474a5899aa3d208d0fb7dcdc1ef56
upstream: https://github.com/datamodel-code-generator/datamodel-code-generator/blob/main/skills/datamodel-code-generator/references/cli-options.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/datamodel-code-generator/datamodel-code-generator/blob/main/skills/datamodel-code-generator/references/cli-options.md

## File: skills/datamodel-code-generator/references/troubleshooting.md
size: 6099
sha: 23b7669ca6b951b4ba92d919d64c13ee29906190
upstream: https://github.com/datamodel-code-generator/datamodel-code-generator/blob/main/skills/datamodel-code-generator/references/troubleshooting.md

````text
# Troubleshooting

## Symptom: The command is not found

Cause: The package is not installed or the user ran the package name as the command.

Fix:

```bash
uvx --from datamodel-code-generator datamodel-codegen --help
```

Notes:

* The package name is `datamodel-code-generator`.
* The CLI command is `datamodel-codegen`.

## Symptom: JSON or YAML was parsed as sample data but it was really a schema

Cause: The wrong `--input-file-type` value was used.

Fix:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.yaml \
  --input-file-type jsonschema \
  --output models.py
```

or:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input openapi.yaml \
  --input-file-type openapi \
  --output models.py
```

Notes:

* Inspect the file before choosing raw sample data mode.

## Symptom: Raw sample data produced surprising optional fields or unions

Cause: Types were inferred from incomplete or inconsistent examples.

Fix:

* Use a fuller sample.
* Prefer the real JSON Schema or OpenAPI spec.
* Review generated optionality and unions.
* Use documented flags only after checking help.

Notes:

* Sample inference cannot know fields missing from the sample.

## Symptom: oneOf or anyOf produced unexpected unions

Cause: The schema allows multiple alternatives.

Fix:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --union-mode smart \
  --output-model-type pydantic_v2.BaseModel \
  --output models.py
```

Notes:

* Verify `--union-mode` values against current help.

## Symptom: allOf did not merge fields as expected

Cause: `allOf` merge behavior depends on schema shape and merge mode.

Fix:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output models.py \
  --allof-merge-mode all
```

Notes:

* Try `--allof-class-hierarchy` when class inheritance is the desired output.

## Symptom: Import errors after directory output

Cause: Module exports or circular imports may not match the application's import style.

Fix:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schemas/ \
  --output models/ \
  --all-exports-scope children
```

Notes:

* For large trees, try recursive exports only after child exports import cleanly.

## Symptom: Duplicate class names or export collisions

Cause: Multiple schemas produce the same class name.

Fix:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schemas/ \
  --output models/ \
  --all-exports-scope recursive \
  --all-exports-collision-strategy minimal-prefix
```

Notes:

* Prefer generator naming flags before editing generated classes by hand.

## Symptom: Enum member names look wrong

Cause: Enum values may not be valid Python identifiers or may conflict with naming conventions.

Fix:

* Check enum-related flags in current help.
* Use the exact supported enum naming flag.
* Do not rename generated enum members by hand unless the user accepts divergence from the schema.

Notes:

* Current help supports `--capitalise-enum-members` and `--capitalize-enum-members`.

## Symptom: Fields with `class`, `from`, or special characters changed names

Cause: Python identifiers cannot use reserved words or invalid characters.

Fix:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output models.py \
  --special-field-name-prefix field
```

For camelCase to snake_case:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output models.py \
  --snake-case-field
```

Notes:

* Keep aliases unless the project explicitly does not want them.

## Symptom: Generated output changes on every run

Cause: Timestamp headers or environment-dependent formatting.

Fix:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output models.py \
  --disable-timestamp
```

Notes:

* Set `--formatters` explicitly when the project needs reproducibility.

## Symptom: Large specs are slow or produce too much duplicate code

Cause: Large schemas can create many repeated models.

Fix:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input openapi.yaml \
  --input-file-type openapi \
  --output models/ \
  --reuse-model \
  --disable-warnings
```

Notes:

* Use directory output when a single file becomes too large.

## Symptom: Remote URL or remote refs fail

Cause: Missing HTTP extra, authentication, local ref path, TLS, or network access.

Fix:

```bash
uvx --from 'datamodel-code-generator[http]' datamodel-codegen \
  --url https://example.com/openapi.yaml \
  --input-file-type openapi \
  --output models.py
```

For authenticated endpoints:

```bash
uvx --from 'datamodel-code-generator[http]' datamodel-codegen \
  --url https://example.com/openapi.yaml \
  --http-headers "Authorization:Bearer $TOKEN" \
  --input-file-type openapi \
  --output models.py
```

Notes:

* Use `--http-ignore-tls` only in trusted development or testing environments.

## Symptom: Generated code does not match installed Pydantic version

Cause: Output model type does not match project dependency versions.

Fix:

```bash
python -c "import pydantic; print(pydantic.VERSION)"
```

Notes:

* Default to `pydantic_v2.BaseModel` for new projects.
* Regenerate with the matching supported output model type.

## Symptom: Type checker complains about constraints

Cause: Some constrained types or field metadata may not be understood by the configured type checker.

Fix:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output models.py \
  --field-constraints
```

or:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output models.py \
  --use-annotated
```

Notes:

* Verify both flags against current help.
````

## File: skills/datamodel-code-generator/references/workflows.md
size: 12932
sha: 655cfd5e7a3b027f8935a149aaacce7e6d3cbd1f
upstream: https://github.com/datamodel-code-generator/datamodel-code-generator/blob/main/skills/datamodel-code-generator/references/workflows.md

````text
# Workflows

## Contents

1. OpenAPI to Pydantic v2
2. OpenAPI to a FastAPI server or Python client (experimental)
3. AsyncAPI to Pydantic v2
4. JSON Schema to Pydantic v2
5. JSON Schema split across files
6. Raw JSON sample to models
7. Raw YAML sample to models
8. CSV sample to models
9. GraphQL SDL to models
10. Apache Avro schema to models
11. XML Schema to models
12. Protocol Buffers to models
13. MCP tool schemas to models
14. Remote URL input
15. Existing Python model or dict schema object
16. Multiple modules for large specs
17. Output as dataclasses, TypedDict, or msgspec

## OpenAPI to Pydantic v2

Use this for OpenAPI schemas when the user wants validation models or API payload types.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input openapi.yaml \
  --input-file-type openapi \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Common flags: `--read-only-write-only-model-type request-response`, `--openapi-scopes`, `--use-operation-id-as-name`, `--use-status-code-in-response-name`.

Verify with:

```bash
python -c "import pathlib, importlib.util; p=pathlib.Path('models.py'); s=importlib.util.spec_from_file_location('generated_models', p); m=importlib.util.module_from_spec(s); s.loader.exec_module(m); print('import ok')"
```

Expect Pydantic v2 model classes for schema components, and optionally request, response, parameter, or path models when OpenAPI scopes include them.

## OpenAPI to a FastAPI server or Python client (experimental)

Use this when the user wants a FastAPI server or an HTTPX2 client generated from an OpenAPI document, on top of the models.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input openapi.yaml \
  --input-file-type openapi \
  --openapi-scopes schemas api \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12 \
  --output app/models.py \
  --generate-server fastapi \
  --server-output app/server \
  --server-package app.server \
  --server-model-package app.models
```

Generation overwrites the models and the server package on every run: never edit them. Write the implementation of each router group in `app/services/<group>.py`, as class `<Group>` subclassing the `<Group>Service` Protocol of `app.server.services`; with `--server-layout single`, write `app/services/service.py` with class `Operations` subclassing the `Service` Protocol. A secured document adds `app/services/authorize.py` with `authorize`. Generation writes each missing module once with stubs and never overwrites it. Give each server package a parent package of its own. `app/server/main.py` imports them and defines `app`. The run prints the `uv add` command for the runtime dependencies and the next steps; `--output-format json` reports them under `target`.

For a client, use `--generate-client httpx2 --client-output app/client --client-package app.client --client-model-package app.models` instead, and call it as `with Client(base_url=...) as client: client.<group>.<method>(...)`.

Verify with:

```bash
uv add uvicorn
uv run uvicorn app.server.main:app
```

Expect the README of the generated package to list the operations and, under Next steps, the modules to implement.

## AsyncAPI to Pydantic v2

Use this for AsyncAPI message schemas.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input asyncapi.yaml \
  --input-file-type asyncapi \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

This generates data models from schema-bearing fields. It does not generate producers, consumers, clients, servers, brokers, or runtime protocol adapters.

Verify with:

```bash
python -c "import pathlib, importlib.util; p=pathlib.Path('models.py'); s=importlib.util.spec_from_file_location('generated_models', p); m=importlib.util.module_from_spec(s); s.loader.exec_module(m); print('import ok')"
```

Expect models for payload schemas and reusable schema components.

## JSON Schema to Pydantic v2

Use this for JSON Schema files or JSON Schema written as YAML.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Common flags: `--schema-version`, `--schema-version-mode`, `--class-name`, `--use-title-as-name`.

Verify with:

```bash
python -c "import pathlib, importlib.util; p=pathlib.Path('models.py'); s=importlib.util.spec_from_file_location('generated_models', p); m=importlib.util.module_from_spec(s); s.loader.exec_module(m); print('import ok')"
```

Expect a root class and nested classes for object definitions.

## JSON Schema split across files

Use this when schemas are stored in a directory or reference each other across files.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schemas/ \
  --input-file-type jsonschema \
  --output models/ \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Common flags: `--external-ref-mapping`, `--reuse-model`, `--reuse-scope`, `--shared-module-name`, `--all-exports-scope`.

Verify with:

```bash
python -c "import models; print('import ok')"
```

Expect a Python package with one or more generated modules and package exports when export flags are enabled.

## Raw JSON sample to models

Use this when the input is example JSON data and not a schema.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input sample.json \
  --input-file-type json \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Types are inferred from the sample. The output is only as representative as the sample data. Review optionality, unions, numeric types, and missing fields.

Verify with the single-file import command. Expect a root model class and nested model classes inferred from sample keys.

## Raw YAML sample to models

Use this when the input is example YAML data and not a schema.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input sample.yaml \
  --input-file-type yaml \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Use `yaml` only for raw YAML data. If the YAML file is an OpenAPI document, AsyncAPI document, or JSON Schema written as YAML, use `openapi`, `asyncapi`, or `jsonschema`.

Verify with the single-file import command. Expect model classes inferred from YAML mapping keys.

## CSV sample to models

Use this when rows in a CSV sample should define a model shape.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input sample.csv \
  --input-file-type csv \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

CSV inference depends on available rows and values.

Verify with the single-file import command. Expect one model class with fields from the CSV header.

## GraphQL SDL to models

Use this for GraphQL schema definition language.

```bash
uvx --from 'datamodel-code-generator[graphql]' datamodel-codegen \
  --input schema.graphql \
  --input-file-type graphql \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Common flags: `--graphql-no-typename`, `--type-mappings`, `--field-extra-keys`.

Verify with the single-file import command. Expect Pydantic models for GraphQL object and input types.

## Apache Avro schema to models

Use this for Avro `.avsc` schema files.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.avsc \
  --input-file-type avro \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Avro support generates Python models from schemas. It does not provide Avro runtime encoding or decoding.

Verify with the single-file import command. Expect model classes for Avro records, enums, fixed values, maps, arrays, and unions when present in the schema.

## XML Schema to models

Use this for XSD documents.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.xsd \
  --input-file-type xmlschema \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Common flags: `--schema-version`, `--schema-version-mode`, `--class-name`, `--use-title-as-name`.

Verify with the single-file import command. Expect model classes for XML elements and complex types. The CLI does not replace an XML parser or full XML instance validator.

## Protocol Buffers to models

Use this for `.proto` schemas when the user wants Python data models, not generated protobuf runtime classes or gRPC stubs.

```bash
uvx --from 'datamodel-code-generator[protobuf]' datamodel-codegen \
  --input schema.proto \
  --input-file-type protobuf \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Common flags: `--schema-version`, `--schema-version-mode`, `--class-name`, `--type-mappings`.

Verify with the single-file import command. Expect model classes for messages and enums. Use protobuf tooling separately for serialization, descriptors, and gRPC code.

## MCP tool schemas to models

Use this for MCP tool schema exports containing `inputSchema` and optional `outputSchema` objects.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input mcp-tools.json \
  --input-file-type mcp-tools \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

MCP tool schemas are converted into JSON Schema definitions before normal model generation.

Verify with the single-file import command. Expect input and output model classes named from tool names and schema roles.

## Remote URL input

Use this for specs fetched by URL or specs that contain remote refs.

```bash
uvx --from 'datamodel-code-generator[http]' datamodel-codegen \
  --url https://example.com/openapi.yaml \
  --input-file-type openapi \
  --output models.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Common flags: `--http-headers`, `--http-query-parameters`, `--http-timeout`, `--http-local-ref-path`, `--allow-remote-refs`.

Use `--http-ignore-tls` only in trusted development or testing environments.

Verify with the single-file import command. Expect the same shape as local file input after the URL is fetched.

## Existing Python model or dict schema object

Use this to retarget existing Python models or schema dictionaries.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input-model ./models.py:User \
  --output user_model.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

For dict schema objects:

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input-model ./schemas.py:USER_SCHEMA \
  --input-file-type jsonschema \
  --output user_model.py \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12
```

Common flag: `--input-model-ref-strategy`.

Verify with the single-file import command. Expect models generated from the Python object's schema.

## Multiple modules for large specs

Use this when one file is too large or the project wants a package.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input openapi.yaml \
  --input-file-type openapi \
  --output models/ \
  --output-model-type pydantic_v2.BaseModel \
  --target-python-version 3.12 \
  --all-exports-scope recursive
```

Common flags: `--all-exports-scope`, `--all-exports-collision-strategy`, `--treat-dot-as-module`,
`--strict-dotted-module-names`, `--reuse-model`, `--reuse-scope`.

Verify with:

```bash
python -c "import models; print('import ok')"
```

Expect a package with generated modules and `__all__` exports.

## Output as dataclasses, TypedDict, or msgspec

Use these when the user wants non-Pydantic output.

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output models.py \
  --output-model-type dataclasses.dataclass \
  --target-python-version 3.12
```

```bash
uvx --from datamodel-code-generator datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output types.py \
  --output-model-type typing.TypedDict \
  --target-python-version 3.12
```

```bash
uvx --with msgspec datamodel-codegen \
  --input schema.json \
  --input-file-type jsonschema \
  --output structs.py \
  --output-model-type msgspec.Struct \
  --target-python-version 3.12
```

Common flags: `--frozen-dataclasses`, `--keyword-only`, `--strict-nullable`, `--use-frozen-field`.

Verify with the single-file import command. Expect plain dataclasses, TypedDict classes, or msgspec structs instead of Pydantic models.
````

## File: README.md
upstream: https://github.com/datamodel-code-generator/datamodel-code-generator/blob/main/README.md

````text
# 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.

[![PyPI version](https://img.shields.io/pypi/v/datamodel-code-generator.svg)](https://pypi.python.org/pypi/datamodel-code-generator)
[![Conda-forge](https://img.shields.io/conda/v/conda-forge/datamodel-code-generator)](https://anaconda.org/conda-forge/datamodel-code-generator)
[![Downloads](https://api.pepy.tech/badge/datamodel-code-generator/month)](https://pepy.tech/projects/datamodel-code-generator)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/datamodel-code-generator)](https://pypi.python.org/pypi/datamodel-code-generator)
[![codecov](https://codecov.io/gh/datamodel-code-generator/datamodel-code-generator/graph/badge.svg?token=plzSSFb9Li)](https://codecov.io/gh/datamodel-code-generator/datamodel-code-generator)
![license](https://img.shields.io/github/license/datamodel-code-generator/datamodel-code-generator.svg)
[![Pydantic v2](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pydantic/pydantic/main/docs/badge/v2.json)](https://pydantic.dev)

## ✨ 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" 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
- 🔗 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&section=all),
> [Ubuntu](https://packages.ubuntu.com/search?keywords=datamodel-codegen&searchon=names&suite=all&section=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.

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

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

</details>

---

## 🏃 Quick Start

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

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

This quick start uses `standard-py312-20261104` 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-20261104`](https://datamodel-code-generator.koxudaxi.dev/presets/#practical-py312-20261104).

**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](https://datamodel-code-generator.koxudaxi.dev/recommend-options/).

<details>
<summary>Input (<code>schema.json</code>)</summary>

```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
    }
  }
}
```

</details>

**Output (`model.py`)**

<!-- fmt: off -->

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

<!-- fmt: on --
````
