🐍 Generate from Python Models¶
Generate code from existing Python types: Pydantic models, dataclasses, TypedDict, or dict schemas. This is useful for converting between model types or generating from programmatically-defined schemas.
🚀 Quick Start¶
Format¶
Simply specify the file path and object name separated by :.
Example¶
myproject/
├── src/
│ └── models/
│ └── user.py # class User(BaseModel): ...
└── schemas.py # USER_SCHEMA = {...}
# From file path (recommended - easy to copy-paste)
datamodel-codegen --input-model src/models/user.py:User --output model.py
datamodel-codegen --input-model ./schemas.py:USER_SCHEMA --input-file-type jsonschema
# Windows paths also work
datamodel-codegen --input-model src\models\user.py:User
Copy-paste friendly
Just copy the file path from your editor or file explorer, add :ClassName, and you're done!
Module format (alternative)¶
You can also use Python module notation with dots:
datamodel-codegen --input-model src.models.user:User
datamodel-codegen --input-model schemas:USER_SCHEMA --input-file-type jsonschema
Current directory is auto-added to sys.path
No PYTHONPATH configuration needed.
File and package name conflict
If both mymodule.py and mymodule/ directory exist, use ./ prefix:
Supported Input Types¶
| Type | Description | Requires |
|---|---|---|
| Pydantic BaseModel | Pydantic v2 models with model_json_schema() |
Pydantic v2 |
| dataclass | Standard library @dataclass |
Pydantic v2 (for TypeAdapter) |
| Pydantic dataclass | @pydantic.dataclasses.dataclass |
Pydantic v2 |
| TypedDict | typing.TypedDict subclasses |
Pydantic v2 (for TypeAdapter) |
| dict | Dict containing JSON Schema or OpenAPI spec | - |
Pydantic v2 Required
All Python type inputs (except raw dict) require Pydantic v2 runtime to convert to JSON Schema.
📝 Examples¶
Pydantic BaseModel¶
mymodule.py
✨ Generated model.py
from __future__ import annotations
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
Convert Pydantic to TypedDict¶
datamodel-codegen --input-model ./mymodule.py:User --output-model-type typing.TypedDict --output model.py
✨ Generated model.py
from __future__ import annotations
from typing import TypedDict
class User(TypedDict):
name: str
age: int
Standard dataclass¶
mymodule.py
TypedDict¶
mymodule.py
Dict Schema (JSON Schema)¶
mymodule.py
USER_SCHEMA = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"required": ["name", "age"],
}
datamodel-codegen --input-model ./mymodule.py:USER_SCHEMA --input-file-type jsonschema --output model.py
Dict requires --input-file-type
When using a dict schema, you must specify --input-file-type (e.g., jsonschema, openapi).
Dict Schema (OpenAPI)¶
mymodule.py
OPENAPI_SPEC = {
"openapi": "3.0.0",
"info": {"title": "API", "version": "1.0.0"},
"paths": {},
"components": {
"schemas": {
"User": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
}
}
},
}
datamodel-codegen --input-model ./mymodule.py:OPENAPI_SPEC --input-file-type openapi --output model.py
Custom Python Types with x-python-type¶
When using x-python-type in JSON Schema (via WithJsonSchema in Pydantic), the generator automatically resolves and generates the required imports.
Automatic Import Resolution¶
The generator supports many common Python types out of the box:
| Module | Supported Types |
|---|---|
typing |
Any, Union, Optional, Literal, Final, ClassVar, Annotated, TypeVar, TypeAlias, Never, NoReturn, Self, LiteralString, TypeGuard, Type |
collections |
defaultdict, OrderedDict, Counter, deque, ChainMap |
collections.abc |
Callable, Iterable, Iterator, Generator, Awaitable, Coroutine, AsyncIterable, AsyncIterator, AsyncGenerator, Mapping, MutableMapping, Sequence, MutableSequence, Set, MutableSet, Collection, Reversible |
pathlib |
Path, PurePath |
decimal |
Decimal |
uuid |
UUID |
datetime |
datetime, date, time, timedelta |
enum |
Enum, IntEnum, StrEnum, Flag, IntFlag |
re |
Pattern, Match |
For types not in this list, the generator dynamically searches common modules to resolve imports.
Example¶
mymodule.py
from collections import defaultdict
from typing import Any, Annotated
from pydantic import BaseModel, Field, WithJsonSchema
class Config(BaseModel):
data: Annotated[
defaultdict[str, Annotated[dict[str, Any], Field(default_factory=dict)]],
WithJsonSchema({'type': 'object', 'x-python-type': 'defaultdict[str, dict[str, Any]]'})
] | None = None
✨ Generated output
from __future__ import annotations
from collections import defaultdict
from typing import Any, TypedDict
from typing_extensions import NotRequired
class Config(TypedDict):
data: NotRequired[defaultdict[str, dict[str, Any]] | None]
Fully Qualified Paths
You can also use fully qualified paths in x-python-type (e.g., collections.defaultdict), which are always resolved correctly regardless of the static mapping.
Mutual Exclusion¶
--input-model cannot be used with:
--input(file input)--url(URL input)--watch(file watching)
📖 See Also¶
- 🖥️ CLI Reference - Complete CLI options reference
- 📁 CLI Reference: Base Options -
--input-modeloption details - 📋 Generate from JSON Schema - JSON Schema input documentation