Skip to content

🐍 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

datamodel-codegen --input-model ./mymodule.py:User --output model.py

Format

--input-model <path/to/file.py>:<ObjectName>

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:

datamodel-codegen --input-model ./mymodule.py:Model


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

from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

datamodel-codegen --input-model ./mymodule.py:User --output model.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

from dataclasses import dataclass

@dataclass
class User:
    name: str
    age: int

datamodel-codegen --input-model ./mymodule.py:User --output model.py

TypedDict

mymodule.py

from typing import TypedDict

class User(TypedDict):
    name: str
    age: int

datamodel-codegen --input-model ./mymodule.py:User --output model.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

datamodel-codegen --input-model ./mymodule.py:Config --output-model-type typing.TypedDict

✨ 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