Skip to content

🎨 Template Customization

📋 Options

Option Description
--additional-imports Add custom imports to generated output files.
--custom-file-header Add custom header text to the generated file.
--custom-file-header-path Add custom header content from file to generated code.
--custom-formatters Apply custom Python code formatters to generated output.
--custom-formatters-kwargs Pass custom arguments to custom formatters via JSON file.
--custom-template-dir Use custom Jinja2 templates for model generation.
--disable-appending-item-suffix Disable appending 'Item' suffix to array item types.
--disable-timestamp Disable timestamp in generated file header for reproducible ...
--enable-version-header Include tool version information in file header.
--extra-template-data Pass custom template variables from JSON file for code gener...
--formatters Specify code formatters to apply to generated output.
--treat-dot-as-module Treat dots in schema names as module separators.
--use-double-quotes Use double quotes for string literals in generated code.
--use-exact-imports Import exact types instead of modules.
--wrap-string-literal Wrap long string literals across multiple lines.

--additional-imports

Add custom imports to generated output files.

The --additional-imports flag allows you to specify custom imports as a comma-delimited list that will be added to the generated output file. This is useful when using custom types defined in external modules (e.g., "datetime.datetime,datetime.date,mymodule.myclass.MyCustomPythonClass").

Usage

datamodel-codegen --input schema.json --additional-imports datetime.datetime,datetime.date,mymodule.myclass.MyCustomPythonClass # (1)!
  1. --additional-imports - the option documented here
Input Schema
scalar Date

"DateTime (ISO8601, example: 2020-01-01T10:11:12+00:00)"
scalar DateTime

scalar MyCustomClass

type A {
  a: Date!
  b: DateTime!
  c: MyCustomClass!
}
Output
# generated by datamodel-codegen:
#   filename:  additional-imports.graphql
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from datetime import date, datetime
from typing import Literal, Optional

from mymodule.myclass import MyCustomPythonClass
from pydantic import BaseModel, Field
from typing_extensions import TypeAlias

Boolean: TypeAlias = bool
"""
The `Boolean` scalar type represents `true` or `false`.
"""


Date: TypeAlias = date


DateTime: TypeAlias = datetime
"""
DateTime (ISO8601, example: 2020-01-01T10:11:12+00:00)
"""


MyCustomClass: TypeAlias = MyCustomPythonClass


String: TypeAlias = str
"""
The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
"""


class A(BaseModel):
    a: Date
    b: DateTime
    c: MyCustomClass
    typename__: Optional[Literal['A']] = Field('A', alias='__typename')

--custom-file-header

Add custom header text to the generated file.

The --custom-file-header flag replaces the default "generated by datamodel-codegen" header with custom text. This is useful for adding copyright notices, license headers, or other metadata to generated files.

Usage

datamodel-codegen --input schema.json --custom-file-header "# Copyright 2024 MyCompany" # (1)!
  1. --custom-file-header - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Person",
  "type": "object",
  "properties": {
    "first-name": {
      "type": "string"
    },
    "last-name": {
      "type": "string"
    },
    "email_address": {
      "type": "string"
    }
  },
  "required": ["first-name", "last-name"]
}
Output
# Copyright 2024 MyCompany

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel, Field


class Person(BaseModel):
    first_name: str = Field(..., alias='first-name')
    last_name: str = Field(..., alias='last-name')
    email_address: Optional[str] = None
# generated by datamodel-codegen:
#   filename:  no_alias.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel, Field


class Person(BaseModel):
    first_name: str = Field(..., alias='first-name')
    last_name: str = Field(..., alias='last-name')
    email_address: Optional[str] = None

--custom-file-header-path

Add custom header content from file to generated code.

The --custom-file-header-path flag allows you to specify a file containing custom header content (like copyright notices, linting directives, or module docstrings) to be inserted at the top of generated Python files.

Usage

datamodel-codegen --input schema.json --custom-file-header-path custom_file_header.txt # (1)!
  1. --custom-file-header-path - the option documented here
Input Schema
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
          default: 1
        name:
          type: string
        tag:
          type: string
    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"
    Users:
      type: array
      items:
        required:
          - id
          - name
        properties:
          id:
            type: integer
            format: int64
          name:
            type: string
          tag:
            type: string
    Id:
      type: string
    Rules:
      type: array
      items:
        type: string
    Error:
      description: error result
      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
    Event:
      type: object
      description: Event object
      properties:
        name:
          type: string
    Result:
        type: object
        properties:
          event:
            $ref: '#/components/schemas/Event'
Output
# multiline custom ;
# header ;
# file ;

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 User(BaseModel):
    id: int
    name: str
    tag: Optional[str] = None


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


class Id(BaseModel):
    __root__: str


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


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]


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


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

--custom-formatters

Apply custom Python code formatters to generated output.

The --custom-formatters flag allows you to specify custom Python functions that will be applied to format the generated code. The formatter is specified as a module path (e.g., "mymodule.formatter_function"). This is useful for adding custom comments, modifying code structure, or applying project-specific formatting rules beyond what black/isort provide.

Usage

datamodel-codegen --input schema.json --custom-formatters tests.data.python.custom_formatters.add_comment # (1)!
  1. --custom-formatters - the option documented here
Input Schema
scalar Long

type A {
  id: ID!
  duration: Long!
}
Output
# generated by datamodel-codegen:
#   filename:  custom-scalar-types.graphql
#   timestamp: 2019-07-26T00:00:00+00:00

# a comment
from __future__ import annotations

from typing import Literal, Optional

from pydantic import BaseModel, Field
from typing_extensions import TypeAlias

Boolean: TypeAlias = bool
"""
The `Boolean` scalar type represents `true` or `false`.
"""


ID: TypeAlias = str
"""
The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.
"""


Long: TypeAlias = str


String: TypeAlias = str
"""
The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
"""


class A(BaseModel):
    duration: Long
    id: ID
    typename__: Optional[Literal['A']] = Field('A', alias='__typename')

--custom-formatters-kwargs

Pass custom arguments to custom formatters via JSON file.

The --custom-formatters-kwargs flag accepts a path to a JSON file containing custom configuration for custom formatters (used with --custom-formatters). The file should contain a JSON object mapping formatter names to their kwargs.

Note: This option is primarily used with --custom-formatters to pass configuration to user-defined formatter modules.

Usage

datamodel-codegen --input schema.json --custom-formatters-kwargs formatter_kwargs.json # (1)!
  1. --custom-formatters-kwargs - 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

--custom-template-dir

Use custom Jinja2 templates for model generation.

The --custom-template-dir option allows you to specify a directory containing custom Jinja2 templates to override the default templates used for generating data models. This enables full customization of the generated code structure and formatting. Use with --extra-template-data to pass additional data to the templates.

Usage

datamodel-codegen --input schema.json --custom-template-dir templates --extra-template-data openapi/extra_data.json # (1)!
  1. --custom-template-dir - the option documented here
Input Schema
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
          default: 1
        name:
          type: string
        tag:
          type: string
    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"
    Users:
      type: array
      items:
        required:
          - id
          - name
        properties:
          id:
            type: integer
            format: int64
          name:
            type: string
          tag:
            type: string
    Id:
      type: string
    Rules:
      type: array
      items:
        type: string
    Error:
      description: error result
      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
    Event:
      type: object
      description: Event object
      properties:
        name:
          type: string
    Result:
        type: object
        properties:
          event:
            $ref: '#/components/schemas/Event'
Output
# generated by datamodel-codegen:
#   filename:  api.yaml
#   timestamp: 1985-10-26T08:21:00+00:00

from __future__ import annotations

from typing import List, Optional

from pydantic import AnyUrl, BaseModel, Field


class Pet(BaseModel):  # 1 2, 1 2, this is just a pet
    id: int
    name: str
    tag: Optional[str] = None


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


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


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


class Id(BaseModel):
    __root__: str


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


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


class Api(BaseModel):
    apiKey: Optional[str] = None
    apiVersionNumber: Optional[str] = None
    apiUrl: Optional[AnyUrl] = None
    apiDocumentationUrl: Optional[AnyUrl] = None


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


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


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

--disable-appending-item-suffix

Disable appending 'Item' suffix to array item types.

The --disable-appending-item-suffix flag configures the code generation behavior.

Usage

datamodel-codegen --input schema.json --disable-appending-item-suffix --field-constraints # (1)!
  1. --disable-appending-item-suffix - the option documented here
Input Schema
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
            minimum: 0
            maximum: 100
      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
          minimum: 0
          maximum: 9223372036854775807
        name:
          type: string
          maxLength: 256
        tag:
          type: string
          maxLength: 64
    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"
      maxItems: 10
      minItems: 1
      uniqueItems: true
    UID:
      type: integer
      minimum: 0
    Users:
      type: array
      items:
        required:
          - id
          - name
          - uid
        properties:
          id:
            type: integer
            format: int64
            minimum: 0
          name:
            type: string
            maxLength: 256
          tag:
            type: string
            maxLength: 64
          uid:
            $ref: '#/components/schemas/UID'
          phones:
            type: array
            items:
              type: string
              minLength: 3
            maxItems: 10
          fax:
            type: array
            items:
              type: string
              minLength: 3
          height:
            type:
              - integer
              - number
            minimum: 1
            maximum: 300
          weight:
            type:
              - number
              - integer
            minimum: 1.0
            maximum: 1000.0
          age:
            type: integer
            minimum: 0.0
            maximum: 200.0
            exclusiveMinimum: true
          rating:
            type: number
            minimum: 0
            exclusiveMinimum: True
            maximum: 5

    Id:
      type: string
    Rules:
      type: array
      items:
        type: string
    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
            minLength: 1
            description: "The URL describing the dataset's fields"
          apiDocumentationUrl:
            type: string
            format: uri
            description: A URL to the API console for each API
    Event:
      type: object
      properties:
        name:
          type: string
    Result:
        type: object
        properties:
          event:
            $ref: '#/components/schemas/Event'
Output
# generated by datamodel-codegen:
#   filename:  api_constrained.yaml
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import List, Optional, Union

from pydantic import AnyUrl, BaseModel, Field


class Pet(BaseModel):
    id: int = Field(..., ge=0, le=9223372036854775807)
    name: str = Field(..., max_length=256)
    tag: Optional[str] = Field(None, max_length=64)


class Pets(BaseModel):
    __root__: List[Pet] = Field(..., max_items=10, min_items=1, unique_items=True)


class UID(BaseModel):
    __root__: int = Field(..., ge=0)


class Phone(BaseModel):
    __root__: str = Field(..., min_length=3)


class Fax(BaseModel):
    __root__: str = Field(..., min_length=3)


class User(BaseModel):
    id: int = Field(..., ge=0)
    name: str = Field(..., max_length=256)
    tag: Optional[str] = Field(None, max_length=64)
    uid: UID
    phones: Optional[List[Phone]] = Field(None, max_items=10)
    fax: Optional[List[Fax]] = None
    height: Optional[Union[int, float]] = Field(None, ge=1.0, le=300.0)
    weight: Optional[Union[float, int]] = Field(None, ge=1.0, le=1000.0)
    age: Optional[int] = Field(None, gt=0, le=200)
    rating: Optional[float] = Field(None, gt=0.0, le=5.0)


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


class Id(BaseModel):
    __root__: str


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


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]


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


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

--disable-timestamp

Disable timestamp in generated file header for reproducible output.

The --disable-timestamp flag configures the code generation behavior.

Usage

datamodel-codegen --input schema.json --disable-timestamp # (1)!
  1. --disable-timestamp - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Info",
  "type": "object",
  "properties": {
    "hostName": {
      "type": "string",
      "format": "hostname"
    },
    "arn": {
      "type": "string",
      "pattern": "(^arn:([^:]*):([^:]*):([^:]*):(|\\*|[\\d]{12}):(.+)$)|^\\*$"
    },
    "tel": {
      "type": "string",
      "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
    },
    "comment": {
        "type": "string",
        "pattern": "[^\b\f\n\r\t\\\\a+.?'\"|()]+$"
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  pattern.json

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel, constr


class Info(BaseModel):
    hostName: Optional[
        constr(
            regex=r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9])\Z'
        )
    ] = None
    arn: Optional[
        constr(regex=r'(^arn:([^:]*):([^:]*):([^:]*):(|\*|[\d]{12}):(.+)$)|^\*$')
    ] = None
    tel: Optional[constr(regex=r'^(\([0-9]{3}\))?[0-9]{3}-[0-9]{4}$')] = None
    comment: Optional[constr(regex=r'[^\b\f\n\r\t\\a+.?\'"|()]+$')] = None

--enable-version-header

Include tool version information in file header.

The --enable-version-header flag configures the code generation behavior.

Usage

datamodel-codegen --input schema.json --enable-version-header # (1)!
  1. --enable-version-header - the option documented here
Input Schema
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
          default: 1
        name:
          type: string
        tag:
          type: string
    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"
    Users:
      type: array
      items:
        required:
          - id
          - name
        properties:
          id:
            type: integer
            format: int64
          name:
            type: string
          tag:
            type: string
    Id:
      type: string
    Rules:
      type: array
      items:
        type: string
    Error:
      description: error result
      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
    Event:
      type: object
      description: Event object
      properties:
        name:
          type: string
    Result:
        type: object
        properties:
          event:
            $ref: '#/components/schemas/Event'
Output
# generated by datamodel-codegen:
#   filename:  api.yaml
#   timestamp: 2019-07-26T00:00:00+00:00
#   version:   0.0.0

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 User(BaseModel):
    id: int
    name: str
    tag: Optional[str] = None


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


class Id(BaseModel):
    __root__: str


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


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]


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


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

--extra-template-data

Pass custom template variables from JSON file for code generation.

The --extra-template-data flag allows you to provide additional variables (from a JSON file) that can be used in custom templates to configure generated model settings like Config classes, enabling customization beyond standard options.

Usage

datamodel-codegen --input schema.json --extra-template-data openapi/extra_data.json # (1)!
  1. --extra-template-data - the option documented here
Input Schema
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
          default: 1
        name:
          type: string
        tag:
          type: string
    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"
    Users:
      type: array
      items:
        required:
          - id
          - name
        properties:
          id:
            type: integer
            format: int64
          name:
            type: string
          tag:
            type: string
    Id:
      type: string
    Rules:
      type: array
      items:
        type: string
    Error:
      description: error result
      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
    Event:
      type: object
      description: Event object
      properties:
        name:
          type: string
    Result:
        type: object
        properties:
          event:
            $ref: '#/components/schemas/Event'
Output
# generated by datamodel-codegen:
#   filename:  api.yaml
#   timestamp: 1985-10-26T08:21:00+00:00

from __future__ import annotations

from typing import List, Optional

from pydantic import AnyUrl, BaseModel, Field


class Pet(BaseModel):  # 1 2, 1 2, this is just a pet
    class Config:
        arbitrary_types_allowed = True

    id: int
    name: str
    tag: Optional[str] = None


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


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


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


class Id(BaseModel):
    __root__: str


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


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]


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


class Result(BaseModel):
    event: Optional[Event] = None
# generated by datamodel-codegen:
#   filename:  api.yaml
#   timestamp: 1985-10-26T08:21:00+00:00

from __future__ import annotations

from typing import List, Optional

from pydantic import AnyUrl, BaseModel, ConfigDict, Field, RootModel


class Pet(BaseModel):  # 1 2, 1 2, this is just a pet
    model_config = ConfigDict(
        arbitrary_types_allowed=True,
        coerce_numbers_to_str=True,
    )
    id: int
    name: str
    tag: Optional[str] = None


class Pets(RootModel[List[Pet]]):
    root: List[Pet]


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


class Users(RootModel[List[User]]):
    root: List[User]


class Id(RootModel[str]):
    root: str


class Rules(RootModel[List[str]]):
    root: List[str]


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(RootModel[List[Api]]):
    root: List[Api]


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


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

--formatters

Specify code formatters to apply to generated output.

The --formatters flag specifies which code formatters to apply to the generated Python code. Available formatters are: black, isort, ruff, yapf, autopep8, autoflake. Default is [black, isort]. Use this to customize formatting or disable formatters entirely.

Usage

datamodel-codegen --input schema.json --formatters isort # (1)!
  1. --formatters - 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

--treat-dot-as-module

Treat dots in schema names as module separators.

The --treat-dot-as-module flag configures the code generation behavior.

Usage

datamodel-codegen --input schema.json --treat-dot-as-module # (1)!
  1. --treat-dot-as-module - the option documented here
Input Schema
# model.schema.json
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "User",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer"
    }
  },
  "required": ["name"]
}
Output
# __init__.py
# generated by datamodel-codegen:
#   filename:  treat_dot_as_module_single
#   timestamp: 2019-07-26T00:00:00+00:00

# model/__init__.py
# generated by datamodel-codegen:
#   filename:  treat_dot_as_module_single
#   timestamp: 2019-07-26T00:00:00+00:00

# model/schema.py
# generated by datamodel-codegen:
#   filename:  model.schema.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


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

--use-double-quotes

Use double quotes for string literals in generated code.

The --use-double-quotes option formats all string literals in the generated Python code with double quotes instead of the default single quotes. This helps maintain consistency with codebases that prefer double-quote formatting.

Usage

datamodel-codegen --input schema.json --use-double-quotes # (1)!
  1. --use-double-quotes - the option documented here
Input Schema
{
  "$id": "https://example.com/schemas/MapState.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "MapState",
  "allOf": [
    {
      "anyOf": [
        {
          "type": "object",
          "properties": {
            "latitude": {"type": "number", "minimum": -90, "maximum": 90},
            "longitude": {"type": "number", "minimum": -180, "maximum": 180},
            "zoom": {"type": "number", "minimum": 0, "maximum": 25, "default": 0},
            "bearing": {"type": "number"},
            "pitch": {"type": "number", "minimum": 0, "exclusiveMaximum": 90},
            "dragRotate": {"type": "boolean"},
            "mapSplitMode": {"type": "string", "const": "SINGLE_MAP"},
            "isSplit": {"type": "boolean", "const": false, "default": false}
          },
          "required": ["latitude", "longitude", "pitch", "mapSplitMode"]
        },
        {
          "type": "object",
          "properties": {
            "latitude": {"$ref": "#/allOf/0/anyOf/0/properties/latitude"},
            "longitude": {"$ref": "#/allOf/0/anyOf/0/properties/longitude"},
            "zoom": {"$ref": "#/allOf/0/anyOf/0/properties/zoom"},
            "bearing": {"$ref": "#/allOf/0/anyOf/0/properties/bearing"},
            "pitch": {"$ref": "#/allOf/0/anyOf/0/properties/pitch"},
            "dragRotate": {"$ref": "#/allOf/0/anyOf/0/properties/dragRotate"},
            "mapSplitMode": {"type": "string", "const": "SWIPE_COMPARE"},
            "isSplit": {"type": "boolean", "const": true, "default": true}
          },
          "required": ["latitude", "longitude", "pitch", "mapSplitMode"]
        }
      ]
    },
    {
      "anyOf": [
        {
          "type": "object",
          "properties": {
            "mapViewMode": {"type": "string", "const": "MODE_2D"}
          },
          "required": ["mapViewMode"]
        },
        {
          "type": "object",
          "properties": {
            "mapViewMode": {"type": "string", "const": "MODE_3D"}
          },
          "required": ["mapViewMode"]
        }
      ]
    }
  ]
}
Output
# generated by datamodel-codegen:
#   filename:  all_of_any_of_base_class_ref.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional, Union

from pydantic import BaseModel, Field, confloat


class MapState1(BaseModel):
    map_view_mode: str = Field("MODE_2D", alias="mapViewMode", const=True)


class MapState2(BaseModel):
    latitude: Latitude
    longitude: Longitude
    zoom: Optional[Zoom] = Field(default_factory=lambda: Zoom.parse_obj(0))
    bearing: Optional[Bearing] = None
    pitch: Pitch
    drag_rotate: Optional[DragRotate] = Field(None, alias="dragRotate")
    map_split_mode: str = Field("SWIPE_COMPARE", alias="mapSplitMode", const=True)
    is_split: bool = Field(True, alias="isSplit", const=True)


class MapState3(BaseModel):
    pass


class MapState4(MapState1, MapState3):
    pass


class MapState5(MapState2, MapState3):
    pass


class MapState6(MapState4):
    pass


class MapState7(MapState5):
    pass


class MapState(BaseModel):
    __root__: Union[MapState4, MapState5, MapState6, MapState7] = Field(
        ..., title="MapState"
    )


class Bearing(BaseModel):
    __root__: float


class DragRotate(BaseModel):
    __root__: bool


class Latitude(BaseModel):
    __root__: confloat(ge=-90.0, le=90.0)


class Longitude(BaseModel):
    __root__: confloat(ge=-180.0, le=180.0)


class Pitch(BaseModel):
    __root__: confloat(ge=0.0, lt=90.0)


class Zoom(BaseModel):
    __root__: confloat(ge=0.0, le=25.0)

--use-exact-imports

Import exact types instead of modules.

The --use-exact-imports flag changes import style from module imports to exact type imports. For example, instead of from . import foo then foo.Bar, it generates from .foo import Bar. This can make the generated code more explicit and easier to read.

Note: This option primarily affects modular output where imports between modules are generated. For single-file output, the difference is minimal.

Usage

datamodel-codegen --input schema.json --use-exact-imports # (1)!
  1. --use-exact-imports - 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

--wrap-string-literal

Wrap long string literals across multiple lines.

The --wrap-string-literal flag breaks long string literals (like descriptions) across multiple lines for better readability, instead of having very long single-line strings in the generated code.

Usage

datamodel-codegen --input schema.json --wrap-string-literal # (1)!
  1. --wrap-string-literal - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "LongDescription",
  "type": "object",
  "properties": {
    "summary": {
      "type": "string",
      "description": "summary for object"
    },
    "description": {
      "type": "string",
      "description": "datamodel-code-generator. This code generator creates pydantic model from an openapi file and others."
    },
    "multi_line": {
      "description": "datamodel-code-generator\nThis code generator creates pydantic model from an openapi file and others.\n\n\nSupported source types\nOpenAPI 3 (YAML/JSON, OpenAPI Data Type)\nJSON Schema (JSON Schema Core/JSON Schema Validation)\nJSON/YAML/CSV Data (it will be converted to JSON Schema)\nPython dictionary (it will be converted to JSON Schema)",
      "type": "string"
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  long_description.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel, Field


class LongDescription(BaseModel):
    summary: Optional[str] = Field(None, description='summary for object')
    description: Optional[str] = Field(
        None,
        description=(
            'datamodel-code-generator. This code generator creates pydantic model from'
            ' an openapi file and others.'
        ),
    )
    multi_line: Optional[str] = Field(
        None,
        description=(
            'datamodel-code-generator\nThis code generator creates pydantic model from'
            ' an openapi file and others.\n\n\nSupported source types\nOpenAPI 3'
            ' (YAML/JSON, OpenAPI Data Type)\nJSON Schema (JSON Schema Core/JSON Schema'
            ' Validation)\nJSON/YAML/CSV Data (it will be converted to JSON'
            ' Schema)\nPython dictionary (it will be converted to JSON Schema)'
        ),
    )