datamodel-codegen: OpenAPI/JSON Schema to Pydantic
datamodel-codegen generates Python data models (Pydantic v1/v2, dataclasses, TypedDict) from OpenAPI, JSON Schema, or JSON.
Python services that consume an OpenAPI or JSON Schema use datamodel-code-generator to keep typed request/response models in sync with the spec, regenerated in CI to prevent drift.
What it does
The datamodel-codegen command reads an input (--input) of a declared --input-file-type (openapi, jsonschema, json), then emits Python models to --output. It supports Pydantic v1 and v2 and other output model types via --output-model-type.
Common usage
datamodel-codegen --input openapi.yaml \
--input-file-type openapi --output models.py
# Pydantic v2 from JSON Schema
datamodel-codegen --input schema.json \
--input-file-type jsonschema \
--output-model-type pydantic_v2.BaseModel \
--output models.pyOptions
| Flag | What it does |
|---|---|
| --input <path> | Input file, directory, URL, or stdin |
| --input-file-type <type> | openapi, jsonschema, json, dict, csv, graphql |
| --output <path> | Output file or directory |
| --output-model-type <type> | pydantic.BaseModel, pydantic_v2.BaseModel, dataclasses.dataclass, typing.TypedDict |
| --field-constraints | Emit Field(...) constraints from the schema |
| --use-standard-collections | Use list/dict instead of List/Dict |
In CI
Run datamodel-codegen and git diff --exit-code models.py so a spec change without a regen fails the build. Pin --output-model-type to your Pydantic major version; regenerating with the wrong version produces churn that looks like drift.
Common errors in CI
"Input file type is not specified" (or an unexpected guess) means you omitted --input-file-type. "Error: Invalid file format" or a yaml.scanner.ScannerError means the input is malformed. "ValidationError" from Pydantic at import time on the generated file usually means a --output-model-type mismatch with the installed Pydantic version. A $ref that cannot be resolved raises "Could not resolve ...".