Skip to content

⚙️ General Options

📋 Options

Option Description
--all-exports-collision-strategy Handle name collisions when exporting recursive module hiera...
--all-exports-scope Generate all exports for child modules in init.py fi...
--check Verify generated code matches existing output without modify...
--disable-warnings Suppress warning messages during code generation.
--generate-cli-command Generate CLI command from pyproject.toml configuration.
--generate-pyproject-config Generate pyproject.toml configuration from CLI arguments.
--http-headers Fetch schema from URL with custom HTTP headers.
--http-ignore-tls Disable TLS certificate verification for HTTPS requests.
--http-query-parameters Add query parameters to HTTP requests for remote schemas.
--ignore-pyproject Ignore pyproject.toml configuration file.
--shared-module-name Customize the name of the shared module for deduplicated mod...

--all-exports-collision-strategy

Handle name collisions when exporting recursive module hierarchies.

The --all-exports-collision-strategy flag determines how to resolve naming conflicts when using --all-exports-scope=recursive. The 'minimal-prefix' strategy adds the minimum module path prefix needed to disambiguate colliding names, while 'full-prefix' uses the complete module path. Requires --all-exports-scope=recursive.

Related: --all-exports-scope

Usage

datamodel-codegen --input schema.json --all-exports-scope recursive --all-exports-collision-strategy minimal-prefix # (1)!
  1. --all-exports-collision-strategy - the option documented here
Input Schema
openapi: "3.0.0"
info:
  version: 1.0.0
  title: Modular 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/collections.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/collections.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:
    models.Species:
      type: string
      enum:
        - dog
        - cat
        - snake
    models.Pet:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string
        species:
          $ref: '#/components/schemas/models.Species'
    models.User:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string
    collections.Pets:
      type: array
      items:
        $ref: "#/components/schemas/models.Pet"
    collections.Users:
      type: array
      items:
        $ref: "#/components/schemas/models.User"
    optional:
      type: string
    Id:
      type: string
    collections.Rules:
      type: array
      items:
        type: string
    Error:
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
    collections.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
          stage:
            type: string
            enum: [
              "test",
              "dev",
              "stg",
              "prod"
            ]
    models.Event:
      type: object
      properties:
        name:
          anyOf:
            - type: string
            - type: number
            - type: integer
            - type: boolean
            - type: object
            - type: array
              items:
                type: string
    Result:
      type: object
      properties:
        event:
          $ref: '#/components/schemas/models.Event'
    foo.bar.Thing:
      properties:
        attributes:
          type: object
    foo.bar.Thang:
      properties:
        attributes:
          type: array
          items:
            type: object
    foo.bar.Clone:
      allOf:
        - $ref: '#/components/schemas/foo.bar.Thing'
        - type: object
          properties:
            others:
              type: object
              properties:
                 name:
                   type: string

    foo.Tea:
      properties:
        flavour:
          type: string
        id:
          $ref: '#/components/schemas/Id'
    Source:
      properties:
        country:
          type: string
    foo.Cocoa:
      properties:
        quality:
          type: integer
    bar.Field:
      type: string
      example: green
    woo.boo.Chocolate:
      properties:
        flavour:
          type: string
        source:
          $ref: '#/components/schemas/Source'
        cocoa:
          $ref: '#/components/schemas/foo.Cocoa'
        field:
          $ref: '#/components/schemas/bar.Field'
    differentTea:
      type: object
      properties:
        foo:
          $ref: '#/components/schemas/foo.Tea'
        nested:
          $ref: '#/components/schemas/nested.foo.Tea'
    nested.foo.Tea:
      properties:
        flavour:
          type: string
        id:
          $ref: '#/components/schemas/Id'
        self:
          $ref: '#/components/schemas/nested.foo.Tea'
        optional:
          type: array
          items:
            $ref: '#/components/schemas/optional'
    nested.foo.TeaClone:
      properties:
        flavour:
          type: string
        id:
          $ref: '#/components/schemas/Id'
        self:
          $ref: '#/components/schemas/nested.foo.Tea'
        optional:
          type: array
          items:
            $ref: '#/components/schemas/optional'
    nested.foo.List:
      type: array
      items:
        $ref: '#/components/schemas/nested.foo.Tea'
Output
# __init__.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from ._internal import DifferentTea, Error, Id, OptionalModel, Result, Source

__all__ = ["DifferentTea", "Error", "Id", "OptionalModel", "Result", "Source"]

# _internal.py
# generated by datamodel-codegen:
#   filename:  _internal

from __future__ import annotations

from typing import List, Optional

from pydantic import BaseModel

from . import models


class OptionalModel(BaseModel):
    __root__: str


class Id(BaseModel):
    __root__: str


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


class Result(BaseModel):
    event: Optional[models.Event] = None


class Source(BaseModel):
    country: Optional[str] = None


class DifferentTea(BaseModel):
    foo: Optional[Tea] = None
    nested: Optional[Tea_1] = None


class Tea(BaseModel):
    flavour: Optional[str] = None
    id: Optional[Id] = None


class Cocoa(BaseModel):
    quality: Optional[int] = None


class Tea_1(BaseModel):
    flavour: Optional[str] = None
    id: Optional[Id] = None
    self: Optional[Tea_1] = None
    optional: Optional[List[OptionalModel]] = None


class TeaClone(BaseModel):
    flavour: Optional[str] = None
    id: Optional[Id] = None
    self: Optional[Tea_1] = None
    optional: Optional[List[OptionalModel]] = None


class ListModel(BaseModel):
    __root__: List[Tea_1]


Tea_1.update_forward_refs()

# bar.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from pydantic import BaseModel, Field


class FieldModel(BaseModel):
    __root__: str = Field(..., example='green')

# collections.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from enum import Enum
from typing import List, Optional

from pydantic import AnyUrl, BaseModel, Field

from . import models


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


class Users(BaseModel):
    __root__: List[models.User]


class Rules(BaseModel):
    __root__: List[str]


class Stage(Enum):
    test = 'test'
    dev = 'dev'
    stg = 'stg'
    prod = 'prod'


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'
    )
    stage: Optional[Stage] = None


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

# foo/__init__.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from .._internal import Cocoa, Tea

__all__ = ["Cocoa", "Tea"]

# foo/bar.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from typing import Any, Dict, List, Optional

from pydantic import BaseModel


class Thing(BaseModel):
    attributes: Optional[Dict[str, Any]] = None


class Thang(BaseModel):
    attributes: Optional[List[Dict[str, Any]]] = None


class Others(BaseModel):
    name: Optional[str] = None


class Clone(Thing):
    others: Optional[Others] = None

# models.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from enum import Enum
from typing import Any, Dict, List, Optional, Union

from pydantic import BaseModel


class Species(Enum):
    dog = 'dog'
    cat = 'cat'
    snake = 'snake'


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


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


class Event(BaseModel):
    name: Optional[Union[str, float, int, bool, Dict[str, Any], List[str]]] = None

# nested/__init__.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

# nested/foo.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from .._internal import ListModel
from .._internal import Tea_1 as Tea
from .._internal import TeaClone

__all__ = ["ListModel", "Tea", "TeaClone"]

# woo/__init__.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from .boo import Chocolate

__all__ = [
    "Chocolate",
]

# woo/boo.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel

from .. import bar
from .._internal import Cocoa, Source


class Chocolate(BaseModel):
    flavour: Optional[str] = None
    source: Optional[Source] = None
    cocoa: Optional[Cocoa] = None
    field: Optional[bar.FieldModel] = None

--all-exports-scope

Generate all exports for child modules in init.py files.

The --all-exports-scope=children flag adds all to each init.py containing exports from direct child modules. This improves IDE autocomplete and explicit exports. Use 'recursive' to include all descendant exports with collision handling.

Related: --all-exports-collision-strategy

Usage

datamodel-codegen --input schema.json --all-exports-scope children # (1)!
  1. --all-exports-scope - the option documented here
Input Schema
openapi: "3.0.0"
info:
  version: 1.0.0
  title: Modular 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/collections.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/collections.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:
    models.Species:
      type: string
      enum:
        - dog
        - cat
        - snake
    models.Pet:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string
        species:
          $ref: '#/components/schemas/models.Species'
    models.User:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string
    collections.Pets:
      type: array
      items:
        $ref: "#/components/schemas/models.Pet"
    collections.Users:
      type: array
      items:
        $ref: "#/components/schemas/models.User"
    optional:
      type: string
    Id:
      type: string
    collections.Rules:
      type: array
      items:
        type: string
    Error:
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
    collections.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
          stage:
            type: string
            enum: [
              "test",
              "dev",
              "stg",
              "prod"
            ]
    models.Event:
      type: object
      properties:
        name:
          anyOf:
            - type: string
            - type: number
            - type: integer
            - type: boolean
            - type: object
            - type: array
              items:
                type: string
    Result:
      type: object
      properties:
        event:
          $ref: '#/components/schemas/models.Event'
    foo.bar.Thing:
      properties:
        attributes:
          type: object
    foo.bar.Thang:
      properties:
        attributes:
          type: array
          items:
            type: object
    foo.bar.Clone:
      allOf:
        - $ref: '#/components/schemas/foo.bar.Thing'
        - type: object
          properties:
            others:
              type: object
              properties:
                 name:
                   type: string

    foo.Tea:
      properties:
        flavour:
          type: string
        id:
          $ref: '#/components/schemas/Id'
    Source:
      properties:
        country:
          type: string
    foo.Cocoa:
      properties:
        quality:
          type: integer
    bar.Field:
      type: string
      example: green
    woo.boo.Chocolate:
      properties:
        flavour:
          type: string
        source:
          $ref: '#/components/schemas/Source'
        cocoa:
          $ref: '#/components/schemas/foo.Cocoa'
        field:
          $ref: '#/components/schemas/bar.Field'
    differentTea:
      type: object
      properties:
        foo:
          $ref: '#/components/schemas/foo.Tea'
        nested:
          $ref: '#/components/schemas/nested.foo.Tea'
    nested.foo.Tea:
      properties:
        flavour:
          type: string
        id:
          $ref: '#/components/schemas/Id'
        self:
          $ref: '#/components/schemas/nested.foo.Tea'
        optional:
          type: array
          items:
            $ref: '#/components/schemas/optional'
    nested.foo.TeaClone:
      properties:
        flavour:
          type: string
        id:
          $ref: '#/components/schemas/Id'
        self:
          $ref: '#/components/schemas/nested.foo.Tea'
        optional:
          type: array
          items:
            $ref: '#/components/schemas/optional'
    nested.foo.List:
      type: array
      items:
        $ref: '#/components/schemas/nested.foo.Tea'
Output
# __init__.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from ._internal import DifferentTea, Error, Id, OptionalModel, Result, Source

__all__ = ["DifferentTea", "Error", "Id", "OptionalModel", "Result", "Source"]

# _internal.py
# generated by datamodel-codegen:
#   filename:  _internal

from __future__ import annotations

from typing import List, Optional

from pydantic import BaseModel

from . import models


class OptionalModel(BaseModel):
    __root__: str


class Id(BaseModel):
    __root__: str


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


class Result(BaseModel):
    event: Optional[models.Event] = None


class Source(BaseModel):
    country: Optional[str] = None


class DifferentTea(BaseModel):
    foo: Optional[Tea] = None
    nested: Optional[Tea_1] = None


class Tea(BaseModel):
    flavour: Optional[str] = None
    id: Optional[Id] = None


class Cocoa(BaseModel):
    quality: Optional[int] = None


class Tea_1(BaseModel):
    flavour: Optional[str] = None
    id: Optional[Id] = None
    self: Optional[Tea_1] = None
    optional: Optional[List[OptionalModel]] = None


class TeaClone(BaseModel):
    flavour: Optional[str] = None
    id: Optional[Id] = None
    self: Optional[Tea_1] = None
    optional: Optional[List[OptionalModel]] = None


class ListModel(BaseModel):
    __root__: List[Tea_1]


Tea_1.update_forward_refs()

# bar.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from pydantic import BaseModel, Field


class FieldModel(BaseModel):
    __root__: str = Field(..., example='green')

# collections.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from enum import Enum
from typing import List, Optional

from pydantic import AnyUrl, BaseModel, Field

from . import models


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


class Users(BaseModel):
    __root__: List[models.User]


class Rules(BaseModel):
    __root__: List[str]


class Stage(Enum):
    test = 'test'
    dev = 'dev'
    stg = 'stg'
    prod = 'prod'


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'
    )
    stage: Optional[Stage] = None


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

# foo/__init__.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from .._internal import Cocoa, Tea

__all__ = ["Cocoa", "Tea"]

# foo/bar.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from typing import Any, Dict, List, Optional

from pydantic import BaseModel


class Thing(BaseModel):
    attributes: Optional[Dict[str, Any]] = None


class Thang(BaseModel):
    attributes: Optional[List[Dict[str, Any]]] = None


class Others(BaseModel):
    name: Optional[str] = None


class Clone(Thing):
    others: Optional[Others] = None

# models.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from enum import Enum
from typing import Any, Dict, List, Optional, Union

from pydantic import BaseModel


class Species(Enum):
    dog = 'dog'
    cat = 'cat'
    snake = 'snake'


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


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


class Event(BaseModel):
    name: Optional[Union[str, float, int, bool, Dict[str, Any], List[str]]] = None

# nested/__init__.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

# nested/foo.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from .._internal import ListModel
from .._internal import Tea_1 as Tea
from .._internal import TeaClone

__all__ = ["ListModel", "Tea", "TeaClone"]

# woo/__init__.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from .boo import Chocolate

__all__ = [
    "Chocolate",
]

# woo/boo.py
# generated by datamodel-codegen:
#   filename:  modular.yaml

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel

from .. import bar
from .._internal import Cocoa, Source


class Chocolate(BaseModel):
    flavour: Optional[str] = None
    source: Optional[Source] = None
    cocoa: Optional[Cocoa] = None
    field: Optional[bar.FieldModel] = None

--check

Verify generated code matches existing output without modifying files.

The --check flag compares the generated output with existing files and exits with a non-zero status if they differ. Useful for CI/CD validation to ensure schemas and generated code stay in sync. Works with both single files and directory outputs.

Usage

datamodel-codegen --input schema.json --disable-timestamp --check # (1)!
  1. --check - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Person",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string",
      "description": "The person's first name."
    },
    "lastName": {
      "type": ["string", "null"],
      "description": "The person's last name."
    },
    "age": {
      "description": "Age in years which must be equal to or greater than zero.",
      "type": "integer",
      "minimum": 0
    },
    "friends": {
      "type": "array"
    },
    "comment": {
      "type": "null"
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  person.json

from __future__ import annotations

from typing import Any, List, Optional

from pydantic import BaseModel, Field, conint


class Person(BaseModel):
    firstName: Optional[str] = Field(None, description="The person's first name.")
    lastName: Optional[str] = Field(None, description="The person's last name.")
    age: Optional[conint(ge=0)] = Field(
        None, description='Age in years which must be equal to or greater than zero.'
    )
    friends: Optional[List[Any]] = None
    comment: None = None

--disable-warnings

Suppress warning messages during code generation.

The --disable-warnings option silences all warning messages that the generator might emit during processing (e.g., about unsupported features, ambiguous schemas, or potential issues). Useful for clean output in CI/CD pipelines.

Usage

datamodel-codegen --input schema.json --disable-warnings # (1)!
  1. --disable-warnings - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Pet",
  "allOf": [
    {
      "$ref": "#/definitions/Home"
    },
    {
      "$ref": "#/definitions/Kind"
    },
    {
      "$ref": "#/definitions/Id"
    },
    {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        }
      }
    }
  ],
  "type": [
    "object"
  ],
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer"
    }
  },
  "definitions": {
    "Home": {
      "type": "object",
      "properties": {
        "address": {
          "type": "string"
        },
        "zip": {
          "type": "string"
        }
      }
    },
    "Kind": {
      "type": "object",
      "properties": {
        "description": {
          "type": "string"
        }
      }
    },
    "Id": {
      "type": "object",
      "properties": {
        "id": {
          "type": "integer"
        }
      }
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  all_of_with_object.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


class Home(BaseModel):
    address: Optional[str] = None
    zip: Optional[str] = None


class Kind(BaseModel):
    description: Optional[str] = None


class Id(BaseModel):
    id: Optional[int] = None


class Pet(Home, Kind, Id):
    name: Optional[str] = None
    age: Optional[int] = None

--generate-cli-command

Generate CLI command from pyproject.toml configuration.

The --generate-cli-command flag reads your pyproject.toml configuration and outputs the equivalent CLI command. This is useful for debugging configuration issues or sharing commands with others.

Usage

datamodel-codegen --generate-cli-command # (1)!
  1. --generate-cli-command - the option documented here
Configuration (pyproject.toml)
[tool.datamodel-codegen]
input = "schema.yaml"
output = "model.py"
Output
datamodel-codegen --input schema.yaml --output model.py

--generate-pyproject-config

Generate pyproject.toml configuration from CLI arguments.

The --generate-pyproject-config flag outputs a pyproject.toml configuration snippet based on the provided CLI arguments. This is useful for converting a working CLI command into a reusable configuration file.

Usage

datamodel-codegen --input schema.json --generate-pyproject-config --input schema.yaml --output model.py # (1)!
  1. --generate-pyproject-config - the option documented here
Output
[tool.datamodel-codegen]
input = "schema.yaml"
output = "model.py"

--http-headers

Fetch schema from URL with custom HTTP headers.

The --url flag specifies a remote URL to fetch the schema from instead of a local file. The --http-headers flag adds custom HTTP headers to the request, useful for authentication (e.g., Bearer tokens) or custom API requirements. Format: HeaderName:HeaderValue.

Usage

datamodel-codegen --input schema.json --url https://api.example.com/schema.json --http-headers "Authorization:Bearer token" # (1)!
  1. --http-headers - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Pet",
  "type": "object",
  "properties": {
    "id": {
      "type": "integer"
    },
    "name": {
      "type": "string"
    },
    "tag": {
      "type": "string"
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  https://api.example.com/schema.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


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

--http-ignore-tls

Disable TLS certificate verification for HTTPS requests.

The --http-ignore-tls flag disables SSL/TLS certificate verification when fetching schemas from HTTPS URLs. This is useful for development environments with self-signed certificates. Not recommended for production.

Usage

datamodel-codegen --input schema.json --url https://api.example.com/schema.json --http-ignore-tls # (1)!
  1. --http-ignore-tls - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Pet",
  "type": "object",
  "properties": {
    "id": {
      "type": "integer"
    },
    "name": {
      "type": "string"
    },
    "tag": {
      "type": "string"
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  https://api.example.com/schema.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


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

--http-query-parameters

Add query parameters to HTTP requests for remote schemas.

The --http-query-parameters flag adds query parameters to HTTP requests when fetching schemas from URLs. Useful for APIs that require version or format parameters. Format: key=value. Multiple parameters can be specified: --http-query-parameters version=v2 format=json.

Usage

datamodel-codegen --input schema.json --url https://api.example.com/schema.json --http-query-parameters version=v2 format=json # (1)!
  1. --http-query-parameters - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Pet",
  "type": "object",
  "properties": {
    "id": {
      "type": "integer"
    },
    "name": {
      "type": "string"
    },
    "tag": {
      "type": "string"
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  https://api.example.com/schema.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


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

--ignore-pyproject

Ignore pyproject.toml configuration file.

The --ignore-pyproject flag tells datamodel-codegen to ignore any [tool.datamodel-codegen] configuration in pyproject.toml. This is useful when you want to override project defaults with CLI arguments, or when testing without project configuration.

Usage

datamodel-codegen --input schema.json --ignore-pyproject # (1)!
  1. --ignore-pyproject - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "firstName": {"type": "string"},
    "lastName": {"type": "string"}
  }
}
Output
# generated by datamodel-codegen:
#   filename:  schema.json

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


class Model(BaseModel):
    firstName: Optional[str] = None
    lastName: Optional[str] = None
# generated by datamodel-codegen:
#   filename:  schema.json

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel, Field


class Model(BaseModel):
    first_name: Optional[str] = Field(None, alias='firstName')
    last_name: Optional[str] = Field(None, alias='lastName')

--shared-module-name

Customize the name of the shared module for deduplicated models.

The --shared-module-name flag sets the name of the shared module created when using --reuse-model with --reuse-scope=tree. This module contains deduplicated models that are referenced from multiple files. Default is shared. Use this if your schema already has a file named shared.

Note: This option only affects modular output with tree-level model reuse.

Usage

datamodel-codegen --input schema.json --shared-module-name my_shared # (1)!
  1. --shared-module-name - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Pet",
  "type": "object",
  "properties": {
    "id": {
      "type": "integer"
    },
    "name": {
      "type": "string"
    },
    "tag": {
      "type": "string"
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  pet_simple.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


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