Datamodel Code Generator
Datamodel Code Generator is a Python library and command-line utility for generating data models from various structured input formats like OpenAPI, JSON Schema, GraphQL, and raw data (JSON/YAML/CSV). It supports outputting models for Pydantic v2, dataclasses, TypedDict, and msgspec. Currently at version 0.56.0, it maintains an active development pace with frequent releases addressing new features and breaking changes, particularly around Pydantic compatibility.
Warnings
- breaking Pydantic v1 runtime support has been completely removed in version 0.55.0. All generated models and internal operations now require Pydantic v2 or newer. Attempting to use the generator or its output with Pydantic v1 will result in errors.
- breaking As of version 0.56.0, the generated syntax for fields with structured defaults (dicts, lists, model references) has changed. They now use `Field(default_value, validate_default=True)` instead of `default_factory=lambda: ...`. This change simplifies the output but may require adjustments if you were relying on the previous factory-based default initialization behavior.
- deprecated Omitting the `--output-model-type` option when using the CLI (or `output_model_type` in `GenerateConfig`) has been deprecated since version 0.53.0. The default output model type switched from Pydantic v1 to Pydantic v2 in 0.55.0.
- breaking In version 0.54.0, enum member names derived from `oneOf`/`anyOf` const constructs now correctly utilize the `title` field from the schema. Previously, `title` was ignored, and names were generated as `{type}_{value}`. This can change generated enum member names.
Install
-
pip install datamodel-code-generator -
pip install 'datamodel-code-generator[http]' -
pip install 'datamodel-code-generator[graphql]'
Imports
- generate
from datamodel_code_generator import generate
- GenerateConfig
from datamodel_code_generator import GenerateConfig
- InputFileType
from datamodel_code_generator import InputFileType
- DataModelType
from datamodel_code_generator import DataModelType
Quickstart
from datamodel_code_generator import InputFileType, generate, GenerateConfig, DataModelType
json_schema: str = """{
"type": "object",
"properties": {
"number": {"type": "number"},
"street_name": {"type": "string"},
"street_type": {"type": "string", "enum": ["Street", "Avenue", "Boulevard"]}
}
}"""
config = GenerateConfig(
input_file_type=InputFileType.JsonSchema,
input_filename="example.json",
output_model_type=DataModelType.PydanticV2BaseModel,
)
result = generate(json_schema, config=config)
print(result)