Datamodel Code Generator

0.56.0 · active · verified Mon Apr 06

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

Install

Imports

Quickstart

This example demonstrates how to programmatically generate Pydantic v2 models from a JSON Schema string. The `generate` function takes the schema content and a `GenerateConfig` object to specify input/output types.

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)

view raw JSON →