datamodel-code-generator 0.35.0


pip install datamodel-code-generator

  Latest version

Released: Oct 09, 2025

Project Links

Meta
Author: Koudai Aono
Requires Python: >=3.9

Classifiers

Development Status
  • 4 - Beta

License
  • OSI Approved :: MIT License

Natural Language
  • English

Programming Language
  • Python :: 3 :: Only
  • Python :: 3.9
  • Python :: 3.10
  • Python :: 3.11
  • Python :: 3.12
  • Python :: 3.13
  • Python :: 3.14
  • Python :: Implementation :: CPython

datamodel-code-generator

This code generator creates pydantic v1 and v2 model, dataclasses.dataclass, typing.TypedDict and msgspec.Struct from an openapi file and others.

PyPI version Conda-forge Downloads PyPI - Python Version codecov license Ruff Pydantic v1 Pydantic v2

Help

See documentation for more details.

Quick Installation

To install datamodel-code-generator:

$ pip install datamodel-code-generator

Simple Usage

You can generate models from a local file.

$ datamodel-codegen --input api.yaml --output model.py
api.yaml
openapi: "3.0.0"
info:
  version: 1.0.0
  title: Swagger Petstore
  license:
    name: MIT
servers:
  - url: http://petstore.swagger.io/v1
paths:
  /pets:
    get:
      summary: List all pets
      operationId: listPets
      tags:
        - pets
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
            format: int32
      responses:
        '200':
          description: A paged array of pets
          headers:
            x-next:
              description: A link to the next page of responses
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pets"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
                x-amazon-apigateway-integration:
                  uri:
                    Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
                  passthroughBehavior: when_no_templates
                  httpMethod: POST
                  type: aws_proxy
    post:
      summary: Create a pet
      operationId: createPets
      tags:
        - pets
      responses:
        '201':
          description: Null response
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
                x-amazon-apigateway-integration:
                  uri:
                    Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
                  passthroughBehavior: when_no_templates
                  httpMethod: POST
                  type: aws_proxy
  /pets/{petId}:
    get:
      summary: Info for a specific pet
      operationId: showPetById
      tags:
        - pets
      parameters:
        - name: petId
          in: path
          required: true
          description: The id of the pet to retrieve
          schema:
            type: string
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pets"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    x-amazon-apigateway-integration:
      uri:
        Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
      passthroughBehavior: when_no_templates
      httpMethod: POST
      type: aws_proxy
components:
  schemas:
    Pet:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string
    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"
    Error:
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
    apis:
      type: array
      items:
        type: object
        properties:
          apiKey:
            type: string
            description: To be used as a dataset parameter value
          apiVersionNumber:
            type: string
            description: To be used as a version parameter value
          apiUrl:
            type: string
            format: uri
            description: "The URL describing the dataset's fields"
          apiDocumentationUrl:
            type: string
            format: uri
            description: A URL to the API console for each API
model.py
# generated by datamodel-codegen:
#   filename:  api.yaml
#   timestamp: 2020-06-02T05:28:24+00:00

from __future__ import annotations

from typing import List, Optional

from pydantic import AnyUrl, BaseModel, Field


class Pet(BaseModel):
    id: int
    name: str
    tag: Optional[str] = None


class Pets(BaseModel):
    __root__: List[Pet]


class Error(BaseModel):
    code: int
    message: str


class Api(BaseModel):
    apiKey: Optional[str] = Field(
        None, description='To be used as a dataset parameter value'
    )
    apiVersionNumber: Optional[str] = Field(
        None, description='To be used as a version parameter value'
    )
    apiUrl: Optional[AnyUrl] = Field(
        None, description="The URL describing the dataset's fields"
    )
    apiDocumentationUrl: Optional[AnyUrl] = Field(
        None, description='A URL to the API console for each API'
    )


class Apis(BaseModel):
    __root__: List[Api]

Supported input types

Supported output types

Sponsors

JetBrains Logo

JetBrains

Astral Logo

Astral

Projects that use datamodel-code-generator

These OSS projects use datamodel-code-generator to generate many models. See the following linked projects for real world examples and inspiration.

Installation

To install datamodel-code-generator:

$ pip install datamodel-code-generator

http extra option

If you want to resolve $ref for remote files then you should specify http extra option.

$ pip install 'datamodel-code-generator[http]'

graphql extra option

If you want to generate data model from a GraphQL schema then you should specify graphql extra option.

$ pip install 'datamodel-code-generator[graphql]'

Docker Image

The docker image is in Docker Hub

$ docker pull koxudaxi/datamodel-code-generator

Advanced Uses

You can generate models from a URL.

$ datamodel-codegen --url https://<INPUT FILE URL> --output model.py

This method needs the http extra option

All Command Options

The datamodel-codegen command:

usage: 
  datamodel-codegen [options]

Generate Python data models from schema definitions or structured data

Options:
  --additional-imports ADDITIONAL_IMPORTS
                        Custom imports for output (delimited list input). For example
                        "datetime.date,datetime.datetime"
  --custom-formatters CUSTOM_FORMATTERS
                        List of modules with custom formatter (delimited list input).
  --formatters {black,isort,ruff-check,ruff-format} [{black,isort,ruff-check,ruff-format} ...]
                        Formatters for output (default: [black, isort])
  --http-headers HTTP_HEADER [HTTP_HEADER ...]
                        Set headers in HTTP requests to the remote host. (example:
                        "Authorization: Basic dXNlcjpwYXNz")
  --http-ignore-tls     Disable verification of the remote host''s TLS certificate
  --http-query-parameters HTTP_QUERY_PARAMETERS [HTTP_QUERY_PARAMETERS ...]
                        Set query parameters in HTTP requests to the remote host. (example:
                        "ref=branch")
  --input INPUT         Input file/directory (default: stdin)
  --input-file-type {auto,openapi,jsonschema,json,yaml,dict,csv,graphql}
                        Input file type (default: auto)
  --output OUTPUT       Output file (default: stdout)
  --output-model-type {pydantic.BaseModel,pydantic_v2.BaseModel,dataclasses.dataclass,typing.TypedDict,msgspec.Struct}
                        Output model type (default: pydantic.BaseModel)
  --url URL             Input file URL. `--input` is ignored when `--url` is used

Typing customization:
  --base-class BASE_CLASS
                        Base Class (default: pydantic.BaseModel)
  --disable-future-imports
                        Disable __future__ imports
  --enum-field-as-literal {all,one}
                        Parse enum field as literal. all: all enum field type are Literal.
                        one: field type is Literal when an enum has only one possible value
  --field-constraints   Use field constraints and not con* annotations
  --set-default-enum-member
                        Set enum members as default values for enum field
  --strict-types {str,bytes,int,float,bool} [{str,bytes,int,float,bool} ...]
                        Use strict types
  --use-annotated       Use typing.Annotated for Field(). Also, `--field-constraints` option
                        will be enabled.
  --use-generic-container-types
                        Use generic container types for type hinting (typing.Sequence,
                        typing.Mapping). If `--use-standard-collections` option is set, then
                        import from collections.abc instead of typing
  --use-non-positive-negative-number-constrained-types
                        Use the Non{Positive,Negative}{FloatInt} types instead of the
                        corresponding con* constrained types.
  --use-one-literal-as-default
                        Use one literal as default value for one literal field
  --use-standard-collections
                        Use standard collections for type hinting (list, dict)
  --use-subclass-enum   Define Enum class as subclass with field type when enum has type
                        (int, float, bytes, str)
  --use-union-operator  Use | operator for Union type (PEP 604).
  --use-unique-items-as-set
                        define field type as `set` when the field attribute has
                        `uniqueItems`

Field customization:
  --capitalise-enum-members, --capitalize-enum-members
                        Capitalize field names on enum
  --empty-enum-field-name EMPTY_ENUM_FIELD_NAME
                        Set field name when enum value is empty (default: `_`)
  --field-extra-keys FIELD_EXTRA_KEYS [FIELD_EXTRA_KEYS ...]
                        Add extra keys to field parameters
  --field-extra-keys-without-x-prefix FIELD_EXTRA_KEYS_WITHOUT_X_PREFIX [FIELD_EXTRA_KEYS_WITHOUT_X_PREFIX ...]
                        Add extra keys with `x-` prefix to field parameters. The extra keys
                        are stripped of the `x-` prefix.
  --field-include-all-keys
                        Add all keys to field parameters
  --force-optional      Force optional for required fields
  --no-alias            Do not add a field alias. E.g., if --snake-case-field is used along
                        with a base class, which has an alias_generator
  --original-field-name-delimiter ORIGINAL_FIELD_NAME_DELIMITER
                        Set delimiter to convert to snake case. This option only can be used
                        with --snake-case-field (default: `_` )
  --remove-special-field-name-prefix
                        Remove field name prefix if it has a special meaning e.g.
                        underscores
  --snake-case-field    Change camel-case field name to snake-case
  --special-field-name-prefix SPECIAL_FIELD_NAME_PREFIX
                        Set field name prefix when first character can''t be used as Python
                        field name (default: `field`)
  --strip-default-none  Strip default None on fields
  --union-mode {smart,left_to_right}
                        Union mode for only pydantic v2 field
  --use-default         Use default value even if a field is required
  --use-default-kwarg   Use `default=` instead of a positional argument for Fields that have
                        default values.
  --use-field-description
                        Use schema description to populate field docstring

Model customization:
  --allow-extra-fields  Deprecated: Allow passing extra fields. This flag is deprecated. Use
                        `--extra-fields=allow` instead.
  --allow-population-by-field-name
                        Allow population by field name
  --class-name CLASS_NAME
                        Set class name of root model
  --collapse-root-models
                        Models generated with a root-type field will be merged into the
                        models using that root-type model
  --disable-appending-item-suffix
                        Disable appending `Item` suffix to model name in an array
  --disable-timestamp   Disable timestamp on file headers
  --enable-faux-immutability
                        Enable faux immutability
  --enable-version-header
                        Enable package version on file headers
  --extra-fields {allow,ignore,forbid}
                        Set the generated models to allow, forbid, or ignore extra fields.
  --frozen-dataclasses  Generate frozen dataclasses (dataclass(frozen=True)). Only applies
                        to dataclass output.
  --keep-model-order    Keep generated models'' order
  --keyword-only        Defined models as keyword only (for example
                        dataclass(kw_only=True)).
  --output-datetime-class {datetime,AwareDatetime,NaiveDatetime}
                        Choose Datetime class between AwareDatetime, NaiveDatetime or
                        datetime. Each output model has its default mapping (for example
                        pydantic: datetime, dataclass: str, ...)
  --parent-scoped-naming
                        Set name of models defined inline from the parent model
  --reuse-model         Reuse models on the field when a module has the model with the same
                        content
  --target-python-version {3.9,3.10,3.11,3.12,3.13,3.14}
                        target python version
  --treat-dot-as-module
                        treat dotted module names as modules
  --use-exact-imports   import exact types instead of modules, for example: "from .foo
                        import Bar" instead of "from . import foo" with "foo.Bar"
  --use-pendulum        use pendulum instead of datetime
  --use-schema-description
                        Use schema description to populate class docstring
  --use-title-as-name   use titles as class names of models

Template customization:
  --aliases ALIASES     Alias mapping file
  --custom-file-header CUSTOM_FILE_HEADER
                        Custom file header
  --custom-file-header-path CUSTOM_FILE_HEADER_PATH
                        Custom file header file path
  --custom-formatters-kwargs CUSTOM_FORMATTERS_KWARGS
                        A file with kwargs for custom formatters.
  --custom-template-dir CUSTOM_TEMPLATE_DIR
                        Custom template directory
  --encoding ENCODING   The encoding of input and output (default: utf-8)
  --extra-template-data EXTRA_TEMPLATE_DATA
                        Extra template data for output models. Input is supposed to be a
                        json/yaml file. For OpenAPI and Jsonschema the keys are the spec
                        path of the object, or the name of the object if you want to apply
                        the template data to multiple objects with the same name. If you are
                        using another input file type (e.g. GraphQL), the key is the name of
                        the object. The value is a dictionary of the template data to add.
  --use-double-quotes   Model generated with double quotes. Single quotes or your black
                        config skip_string_normalization value will be used without this
                        option.
  --wrap-string-literal
                        Wrap string literal by using black `experimental-string-processing`
                        option (require black 20.8b0 or later)

OpenAPI-only options:
  --include-path-parameters
                        Include path parameters in generated parameter models in addition to
                        query parameters (Only OpenAPI)
  --openapi-scopes {schemas,paths,tags,parameters} [{schemas,paths,tags,parameters} ...]
                        Scopes of OpenAPI model generation (default: schemas)
  --strict-nullable     Treat default field as a non-nullable field (Only OpenAPI)
  --use-operation-id-as-name
                        use operation id of OpenAPI as class names of models
  --validation          Deprecated: Enable validation (Only OpenAPI). this option is
                        deprecated. it will be removed in future releases

General options:
  --debug               show debug message (require "debug". `$ pip install ''datamodel-code-
                        generator[debug]''`)
  --disable-warnings    disable warnings
  --no-color            disable colorized output
  --version             show version
  -h, --help            show this help message and exit

Related projects

fastapi-code-generator

This code generator creates FastAPI app from an openapi file.

https://github.com/koxudaxi/fastapi-code-generator

pydantic-pycharm-plugin

A JetBrains PyCharm plugin for pydantic.

https://github.com/koxudaxi/pydantic-pycharm-plugin

PyPi

https://pypi.org/project/datamodel-code-generator

Contributing

See docs/development-contributing.md for how to get started!

License

datamodel-code-generator is released under the MIT License. http://www.opensource.org/licenses/mit-license

0.35.0 Oct 09, 2025
0.34.0 Sep 28, 2025
0.33.0 Aug 14, 2025
0.32.0 Jul 25, 2025
0.31.2 Jun 22, 2025
0.31.1 Jun 17, 2025
0.31.0 Jun 12, 2025
0.30.2 Jun 07, 2025
0.30.1 Apr 28, 2025
0.30.0 Apr 17, 2025
0.29.0 Apr 17, 2025
0.28.5 Mar 24, 2025
0.28.4 Mar 11, 2025
0.28.3 Mar 10, 2025
0.28.2 Feb 27, 2025
0.28.1 Feb 15, 2025
0.28.0 Feb 14, 2025
0.27.3 Feb 11, 2025
0.27.2 Feb 07, 2025
0.27.1 Feb 06, 2025
0.27.0 Feb 06, 2025
0.26.5 Jan 14, 2025
0.26.4 Dec 15, 2024
0.26.3 Nov 10, 2024
0.26.2 Oct 17, 2024
0.26.1 Sep 27, 2024
0.26.0 Sep 02, 2024
0.25.9 Aug 07, 2024
0.25.8 Jul 04, 2024
0.25.7 Jun 11, 2024
0.25.6 Apr 25, 2024
0.25.5 Mar 16, 2024
0.25.4 Feb 13, 2024
0.25.3 Feb 01, 2024
0.25.2 Dec 21, 2023
0.25.1 Nov 26, 2023
0.25.0 Nov 25, 2023
0.24.2 Nov 16, 2023
0.24.1 Nov 16, 2023
0.24.0 Nov 16, 2023
0.23.0 Nov 08, 2023
0.22.1 Oct 08, 2023
0.22.0 Sep 23, 2023
0.21.5 Sep 06, 2023
0.21.4 Aug 09, 2023
0.21.3 Aug 03, 2023
0.21.2 Jul 20, 2023
0.21.1 Jul 06, 2023
0.21.0 Jul 03, 2023
0.20.0 Jun 06, 2023
0.19.0 May 10, 2023
0.18.1 Apr 27, 2023
0.18.0 Apr 16, 2023
0.17.2 Mar 31, 2023
0.17.1 Feb 06, 2023
0.17.0 Jan 30, 2023
0.16.1 Jan 22, 2023
0.16.0 Jan 16, 2023
0.15.0 Jan 04, 2023
0.14.1 Dec 28, 2022
0.14.0 Nov 18, 2022
0.13.5 Nov 06, 2022
0.13.4 Oct 31, 2022
0.13.3 Oct 27, 2022
0.13.2 Oct 17, 2022
0.13.1 Aug 11, 2022
0.13.0 May 27, 2022
0.12.3 May 27, 2022
0.12.2 May 27, 2022
0.12.1 May 19, 2022
0.12.0 Apr 18, 2022
0.11.20 Mar 12, 2022
0.11.19 Feb 08, 2022
0.11.18 Feb 02, 2022
0.11.17 Jan 23, 2022
0.11.16 Jan 17, 2022
0.11.15 Nov 29, 2021
0.11.14 Sep 30, 2021
0.11.13 Sep 15, 2021
0.11.12 Aug 27, 2021
0.11.11 Aug 12, 2021
0.11.10 Aug 12, 2021
0.11.9 Jul 31, 2021
0.11.8 Jun 11, 2021
0.11.7 Jun 09, 2021
0.11.6 May 28, 2021
0.11.5 May 16, 2021
0.11.4 May 05, 2021
0.11.3 Apr 29, 2021
0.11.2 Apr 26, 2021
0.11.1 Apr 22, 2021
0.11.0 Apr 21, 2021
0.10.3 Apr 18, 2021
0.10.2 Apr 03, 2021
0.10.1 Mar 31, 2021
0.10.0 Mar 27, 2021
0.9.4 Mar 21, 2021
0.9.3 Mar 18, 2021
0.9.2 Mar 11, 2021
0.9.1 Mar 08, 2021
0.9.0 Mar 04, 2021
0.8.3 Feb 25, 2021
0.8.2 Feb 20, 2021
0.8.1 Feb 18, 2021
0.8.0 Feb 17, 2021
0.7.3 Feb 16, 2021
0.7.2 Feb 09, 2021
0.7.1 Feb 05, 2021
0.7.0 Jan 31, 2021
0.6.26 Jan 26, 2021
0.6.25 Jan 24, 2021
0.6.24 Jan 23, 2021
0.6.23 Jan 21, 2021
0.6.22 Jan 19, 2021
0.6.21 Jan 18, 2021
0.6.20 Jan 15, 2021
0.6.19 Jan 15, 2021
0.6.18 Jan 08, 2021
0.6.17 Jan 06, 2021
0.6.16 Dec 31, 2020
0.6.15 Dec 28, 2020
0.6.14 Dec 27, 2020
0.6.13 Dec 25, 2020
0.6.12 Dec 24, 2020
0.6.11 Dec 17, 2020
0.6.10 Dec 07, 2020
0.6.9 Dec 02, 2020
0.6.8 Nov 29, 2020
0.6.7 Nov 17, 2020
0.6.6 Nov 14, 2020
0.6.5 Nov 12, 2020
0.6.4 Nov 11, 2020
0.6.3 Nov 09, 2020
0.6.2 Nov 05, 2020
0.6.1 Nov 01, 2020
0.6.0 Oct 18, 2020
0.5.39 Oct 06, 2020
0.5.38 Oct 05, 2020
0.5.37 Oct 03, 2020
0.5.36 Oct 02, 2020
0.5.35 Sep 23, 2020
0.5.34 Sep 19, 2020
0.5.33 Sep 17, 2020
0.5.32 Sep 16, 2020
0.5.31 Sep 12, 2020
0.5.30 Sep 04, 2020
0.5.29 Aug 25, 2020
0.5.28 Aug 21, 2020
0.5.27 Aug 16, 2020
0.5.26 Aug 14, 2020
0.5.25 Aug 13, 2020
0.5.24 Aug 03, 2020
0.5.23 Aug 02, 2020
0.5.22 Jul 30, 2020
0.5.21 Jul 30, 2020
0.5.20 Jul 27, 2020
0.5.19 Jul 24, 2020
0.5.18 Jul 23, 2020
0.5.17 Jul 22, 2020
0.5.16 Jul 19, 2020
0.5.15 Jul 19, 2020
0.5.14 Jul 14, 2020
0.5.13 Jun 30, 2020
0.5.12 Jun 29, 2020
0.5.11 Jun 25, 2020
0.5.10 Jun 20, 2020
0.5.9 Jun 19, 2020
0.5.8 Jun 17, 2020
0.5.7 Jun 14, 2020
0.5.6 Jun 13, 2020
0.5.5 Jun 12, 2020
0.5.4 Jun 11, 2020
0.5.3 Jun 11, 2020
0.5.2 Jun 05, 2020
0.5.1 Jun 05, 2020
0.5.0 Jun 02, 2020
0.4.11 May 19, 2020
0.4.10 May 06, 2020
0.4.9 Apr 22, 2020
0.4.8 Apr 18, 2020
0.4.7 Apr 14, 2020
0.4.6 Apr 06, 2020
0.4.5 Apr 05, 2020
0.4.4 Apr 01, 2020
0.4.3 Mar 31, 2020
0.4.2 Mar 30, 2020
0.4.1 Mar 23, 2020
0.4.0 Mar 16, 2020
0.3.3 Feb 26, 2020
0.3.2 Feb 05, 2020
0.3.1 Feb 03, 2020
0.3.0 Jan 09, 2020
0.2.16 Dec 13, 2019
0.2.15 Dec 04, 2019
0.2.14 Nov 25, 2019
0.2.13 Nov 22, 2019
0.2.12 Nov 04, 2019
0.2.11 Oct 18, 2019
0.2.10 Oct 18, 2019
0.2.9 Oct 17, 2019
0.2.8 Oct 16, 2019
0.2.7 Oct 15, 2019
0.2.6 Oct 10, 2019
0.2.5 Oct 09, 2019
0.2.4 Sep 26, 2019
0.2.3 Sep 13, 2019
0.2.2 Sep 13, 2019
0.2.1 Sep 13, 2019
0.2.0 Sep 05, 2019
0.1.0 Aug 06, 2019
0.0.6 Jul 31, 2019
0.0.5 Jul 26, 2019
0.0.4 Jul 23, 2019
0.0.3 Jul 23, 2019
0.0.2 Jul 23, 2019
0.0.1 Jul 23, 2019
Extras:
Dependencies:
argcomplete (<4,>=2.10.1)
black (>=19.10b0)
genson (<2,>=1.2.1)
inflect (<8,>=4.1)
isort (<7,>=4.3.21)
jinja2 (<4,>=2.10.1)
packaging
pydantic (>=1.5)
pyyaml (>=6.0.1)
tomli (<3,>=2.2.1)