# 🎨 Template Customization

## 📋 Options

| Option | Description |
|--------|-------------|
| [`--additional-imports`](#additional-imports) | Add custom imports to generated output files. |
| [`--class-decorators`](#class-decorators) | Add custom decorators to generated model classes. |
| [`--custom-file-header`](#custom-file-header) | Add custom header text to the generated file. |
| [`--custom-file-header-path`](#custom-file-header-path) | Add custom header content from file to generated code. |
| [`--custom-formatters`](#custom-formatters) | Apply custom Python code formatters to generated output. |
| [`--custom-formatters-kwargs`](#custom-formatters-kwargs) | Pass custom arguments to custom formatters via inline JSON o... |
| [`--custom-template-dir`](#custom-template-dir) | Use custom Jinja2 templates for model generation. |
| [`--disable-appending-item-suffix`](#disable-appending-item-suffix) | Disable appending 'Item' suffix to array item types. |
| [`--disable-timestamp`](#disable-timestamp) | Disable timestamp in generated file header for reproducible ... |
| [`--enable-command-header`](#enable-command-header) | Include command-line options in file header for reproducibil... |
| [`--enable-generated-header-marker`](#enable-generated-header-marker) | Include the @generated marker in file header for generated-c... |
| [`--enable-version-header`](#enable-version-header) | Include tool version information in file header. |
| [`--extra-template-data`](#extra-template-data) | Pass custom template variables via inline JSON or a JSON fil... |
| [`--formatters`](#formatters) | Specify code formatters to apply to generated output. |
| [`--generate-schema-validators`](#generate-schema-validators) | Generate experimental Pydantic v2 model validators for JSON ... |
| [`--no-treat-dot-as-module`](#no-treat-dot-as-module) | Keep dots in schema names as underscores for flat output. |
| [`--no-use-type-checking-imports`](#no-use-type-checking-imports) | Keep generated model imports available at runtime when using... |
| [`--schema-validator-base-class-name`](#schema-validator-base-class-name) | Set the generated shared Pydantic v2 schema runtime validato... |
| [`--schema-validator-type`](#schema-validator-type) | Select the schema-derived runtime validator backend. |
| [`--treat-dot-as-module`](#treat-dot-as-module) | Treat dots in schema names as module separators. |
| [`--use-double-quotes`](#use-double-quotes) | Use double quotes for string literals in generated code. |
| [`--use-exact-imports`](#use-exact-imports) | Import exact types instead of modules. |
| [`--use-type-checking-imports`](#use-type-checking-imports) | Allow Ruff to move typing-only imports into TYPE_CHECKING bl... |
| [`--validators`](#validators) | Add custom field validators to generated Pydantic v2 models. |
| [`--wrap-string-literal`](#wrap-string-literal) | Wrap long string literals across multiple lines. |

---

## 🍳 Recipes

### Control generated file headers

Choose a header source and remove volatile timestamp content for reproducible output.

**Options:** [`--custom-file-header`](#custom-file-header), [`--custom-file-header-path`](#custom-file-header-path), [`--disable-timestamp`](#disable-timestamp)

### Inject project-specific code

Add imports, decorators, or custom templates when generated classes must fit local framework conventions.

**Options:** [`--additional-imports`](#additional-imports), [`--class-decorators`](#class-decorators), [`--custom-template-dir`](#custom-template-dir)

---

## `--additional-imports` {#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").

**See also:** [Custom Class Decorators](../class-decorators.md)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --additional-imports datetime.datetime,datetime.date,mymodule.myclass.MyCustomPythonClass # (1)!
    ```

    1. :material-arrow-left: `--additional-imports` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```graphql
    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:**

    ```python
    # 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

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

    Boolean = TypeAliasType("Boolean", bool)
    """
    The `Boolean` scalar type represents `true` or `false`.
    """


    Date = TypeAliasType("Date", date)


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


    MyCustomClass = TypeAliasType("MyCustomClass", MyCustomPythonClass)


    String = TypeAliasType("String", 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__: Literal['A'] | None = Field('A', alias='__typename')
    ```

---

## `--class-decorators` {#class-decorators}

Add custom decorators to generated model classes.

The `--class-decorators` option adds custom decorators to all generated model classes.
This is useful for integrating with serialization libraries like `dataclasses_json`.

Use with `--additional-imports` to add the required imports for the decorators.
The `@` prefix is optional and will be added automatically if missing.

**Related:** [`--additional-imports`](#additional-imports), [`--output-model-type`](model-customization.md#output-model-type)

**See also:** [Custom Class Decorators](../class-decorators.md)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --output-model-type dataclasses.dataclass --class-decorators @dataclass_json --additional-imports dataclasses_json.dataclass_json # (1)!
    ```

    1. :material-arrow-left: `--class-decorators` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "title": "User",
      "properties": {
        "name": {
          "type": "string"
        },
        "age": {
          "type": "integer"
        },
        "email": {
          "type": "string",
          "format": "email"
        }
      },
      "required": ["name", "age"]
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  simple_frozen_test.json
    #   timestamp: 1985-10-26T08:21:00+00:00

    from __future__ import annotations

    from dataclasses import dataclass

    from dataclasses_json import dataclass_json


    @dataclass_json
    @dataclass
    class User:
        name: str
        age: int
        email: str | None = None
    ```

---

## `--custom-file-header` {#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.

**Option relationships:**

- **Conflicts:** [`--custom-file-header-path`](template-customization.md#custom-file-header-path) - `--custom-file-header` can not be used with `--custom-file-header-path`.

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --custom-file-header "# Copyright 2024 MyCompany" # (1)!
    ```

    1. :material-arrow-left: `--custom-file-header` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$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:**

    === "With Option"

        ```python
        # Copyright 2024 MyCompany

        from __future__ import annotations

        from pydantic import BaseModel, Field


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

    === "Without Option"

        ```python
        # generated by datamodel-codegen:
        #   filename:  no_alias.json
        #   timestamp: 2019-07-26T00:00:00+00:00

        from __future__ import annotations

        from pydantic import BaseModel, Field


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

---

## `--custom-file-header-path` {#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.

**Option relationships:**

- **Conflicts:** [`--custom-file-header`](template-customization.md#custom-file-header) - `--custom-file-header-path` can not be used with `--custom-file-header`.

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --custom-file-header-path custom_file_header.txt # (1)!
    ```

    1. :material-arrow-left: `--custom-file-header-path` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```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
              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:**

    ```python
    # multiline custom ;
    # header ;
    # file ;

    from __future__ import annotations

    from pydantic import AnyUrl, BaseModel, Field, RootModel


    class Pet(BaseModel):
        id: int
        name: str
        tag: str | None = None


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


    class User(BaseModel):
        id: int
        name: str
        tag: str | None = 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: str | None = Field(
            None, description='To be used as a dataset parameter value'
        )
        apiVersionNumber: str | None = Field(
            None, description='To be used as a version parameter value'
        )
        apiUrl: AnyUrl | None = Field(
            None, description="The URL describing the dataset's fields"
        )
        apiDocumentationUrl: AnyUrl | None = Field(
            None, description='A URL to the API console for each API'
        )


    class Apis(RootModel[list[Api]]):
        root: list[Api]


    class Event(BaseModel):
        name: str | None = None


    class Result(BaseModel):
        event: Event | None = None
    ```

---

## `--custom-formatters` {#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.

**See also:** [Custom Code Formatters](../custom-formatters.md)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --custom-formatters tests.data.python.custom_formatters.add_comment # (1)!
    ```

    1. :material-arrow-left: `--custom-formatters` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```graphql
    scalar Long
    
    type A {
      id: ID!
      duration: Long!
    }
    ```

    **Output:**

    ```python
    # 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

    from pydantic import BaseModel, Field
    from typing_extensions import TypeAliasType

    Boolean = TypeAliasType("Boolean", bool)
    """
    The `Boolean` scalar type represents `true` or `false`.
    """


    ID = TypeAliasType("ID", 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 = TypeAliasType("Long", str)


    String = TypeAliasType("String", 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__: Literal['A'] | None = Field('A', alias='__typename')
    ```

---

## `--custom-formatters-kwargs` {#custom-formatters-kwargs}

Pass custom arguments to custom formatters via inline JSON or a JSON file path.

The `--custom-formatters-kwargs` flag accepts an inline JSON object or 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.

**See also:** [Custom Code Formatters](../custom-formatters.md)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --custom-formatters-kwargs formatter_kwargs.json # (1)!
    ```

    1. :material-arrow-left: `--custom-formatters-kwargs` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "Pet",
      "type": "object",
      "properties": {
        "id": {
          "type": "integer"
        },
        "name": {
          "type": "string"
        },
        "tag": {
          "type": "string"
        }
      }
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  pet_simple.json
    #   timestamp: 2019-07-26T00:00:00+00:00

    from __future__ import annotations

    from pydantic import BaseModel


    class Pet(BaseModel):
        id: int | None = None
        name: str | None = None
        tag: str | None = None
    ```

---

## `--custom-template-dir` {#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.

**See also:** [Custom Templates](../custom_template.md)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --custom-template-dir templates --extra-template-data openapi/extra_data.json # (1)!
    ```

    1. :material-arrow-left: `--custom-template-dir` - the option documented here

<!-- BEGIN AUTO-GENERATED DOC EXAMPLE: cli-reference.template-customization.custom-template-dir.example -->
??? example "Examples"

    **Input Schema (`api.yaml`):**
    ```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
              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'
    ```

    **Template (`templates/pydantic/BaseModel.jinja2`):**
    ```jinja2
    {% for decorator in decorators -%}
    {{ decorator }}
    {% endfor -%}
    class {{ class_name }}({{ base_class }}):{% if comment is defined %}  # {{ comment }}{% endif %}
    {%- if not fields %}
        pass
    {%- endif %}
    {%- for field in fields -%}
        {%- if field.required %}
        {{ field.name }}: {{ field.type_hint }}
        {%- else %}
        {{ field.name }}: {{ field.type_hint }} = {{ field.default }}
        {%- endif %}
        {%- if field.docstring %}
        """
        {{ field.docstring }}
        """
        {%- endif %}
    {%- endfor -%}
    ```

    **Extra Template Data (`openapi/extra_data.json`):**
    ```json
    {
      "Pet": {
        "comment": "1 2, 1 2, this is just a pet",
        "config":{
          "arbitrary_types_allowed": "True",
          "coerce_numbers_to_str": "True"}
      }
    }
    ```

    **Output:**
    ```python
    from __future__ import annotations

    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: str | None = None


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


    class User(BaseModel):
        id: int
        name: str
        tag: str | None = 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: str | None = Field(
            None, description='To be used as a dataset parameter value'
        )
        apiVersionNumber: str | None = Field(
            None, description='To be used as a version parameter value'
        )
        apiUrl: AnyUrl | None = Field(
            None, description="The URL describing the dataset's fields"
        )
        apiDocumentationUrl: AnyUrl | None = Field(
            None, description='A URL to the API console for each API'
        )


    class Apis(RootModel[list[Api]]):
        root: list[Api]


    class Event(BaseModel):
        name: str | None = None


    class Result(BaseModel):
        event: Event | None = None
    ```
<!-- END AUTO-GENERATED DOC EXAMPLE: cli-reference.template-customization.custom-template-dir.example -->

---

## `--disable-appending-item-suffix` {#disable-appending-item-suffix}

Disable appending 'Item' suffix to array item types.

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

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --disable-appending-item-suffix --field-constraints # (1)!
    ```

    1. :material-arrow-left: `--disable-appending-item-suffix` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```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
                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:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  api_constrained.yaml
    #   timestamp: 2019-07-26T00:00:00+00:00

    from __future__ import annotations

    from pydantic import AnyUrl, BaseModel, Field, RootModel


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


    class Pets(RootModel[list[Pet]]):
        root: list[Pet] = Field(..., max_length=10, min_length=1)


    class UID(RootModel[int]):
        root: int = Field(..., ge=0)


    class Phone(RootModel[str]):
        root: str = Field(..., min_length=3)


    class Fax(RootModel[str]):
        root: str = Field(..., min_length=3)


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


    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: str | None = Field(
            None, description='To be used as a dataset parameter value'
        )
        apiVersionNumber: str | None = Field(
            None, description='To be used as a version parameter value'
        )
        apiUrl: AnyUrl | None = Field(
            None, description="The URL describing the dataset's fields"
        )
        apiDocumentationUrl: AnyUrl | None = Field(
            None, description='A URL to the API console for each API'
        )


    class Apis(RootModel[list[Api]]):
        root: list[Api]


    class Event(BaseModel):
        name: str | None = None


    class Result(BaseModel):
        event: Event | None = None
    ```

---

## `--disable-timestamp` {#disable-timestamp}

Disable timestamp in generated file header for reproducible output.

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

**See also:** [CI/CD Integration](../ci-cd.md)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --disable-timestamp # (1)!
    ```

    1. :material-arrow-left: `--disable-timestamp` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$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": "[^\\x08\\f\\n\\r\\t\\\\a+.?'\"|()]+$"
        }
      }
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  pattern.json

    from __future__ import annotations

    from pydantic import BaseModel, constr


    class Info(BaseModel):
        hostName: (
            constr(
                pattern=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])$'
            )
            | None
        ) = None
        arn: (
            constr(pattern=r'(^arn:([^:]*):([^:]*):([^:]*):(|\*|[\d]{12}):(.+)$)|^\*$')
            | None
        ) = None
        tel: constr(pattern=r'^(\([0-9]{3}\))?[0-9]{3}-[0-9]{4}$') | None = None
        comment: constr(pattern=r'[^\x08\f\n\r\t\\a+.?\'"|()]+$') | None = None
    ```

---

## `--enable-command-header` {#enable-command-header}

Include command-line options in file header for reproducibility.

The `--enable-command-header` flag adds the full command-line used to generate
the file to the header, making it easy to reproduce the generation.

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --enable-command-header # (1)!
    ```

    1. :material-arrow-left: `--enable-command-header` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```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
              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:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  api.yaml
    #   timestamp: 2019-07-26T00:00:00+00:00
    #   command:   datamodel-codegen [COMMAND]

    from __future__ import annotations

    from pydantic import AnyUrl, BaseModel, Field, RootModel


    class Pet(BaseModel):
        id: int
        name: str
        tag: str | None = None


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


    class User(BaseModel):
        id: int
        name: str
        tag: str | None = 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: str | None = Field(
            None, description='To be used as a dataset parameter value'
        )
        apiVersionNumber: str | None = Field(
            None, description='To be used as a version parameter value'
        )
        apiUrl: AnyUrl | None = Field(
            None, description="The URL describing the dataset's fields"
        )
        apiDocumentationUrl: AnyUrl | None = Field(
            None, description='A URL to the API console for each API'
        )


    class Apis(RootModel[list[Api]]):
        root: list[Api]


    class Event(BaseModel):
        name: str | None = None


    class Result(BaseModel):
        event: Event | None = None
    ```

---

## `--enable-generated-header-marker` {#enable-generated-header-marker}

Include the @generated marker in file header for generated-code tooling.

The `--enable-generated-header-marker` flag marks generated output for tools that
recognize the `@generated` marker.

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --enable-generated-header-marker # (1)!
    ```

    1. :material-arrow-left: `--enable-generated-header-marker` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```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
              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:**

    ```python
    # @generated by datamodel-codegen:
    #   filename:  api.yaml
    #   timestamp: 2019-07-26T00:00:00+00:00

    from __future__ import annotations

    from pydantic import AnyUrl, BaseModel, Field, RootModel


    class Pet(BaseModel):
        id: int
        name: str
        tag: str | None = None


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


    class User(BaseModel):
        id: int
        name: str
        tag: str | None = 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: str | None = Field(
            None, description='To be used as a dataset parameter value'
        )
        apiVersionNumber: str | None = Field(
            None, description='To be used as a version parameter value'
        )
        apiUrl: AnyUrl | None = Field(
            None, description="The URL describing the dataset's fields"
        )
        apiDocumentationUrl: AnyUrl | None = Field(
            None, description='A URL to the API console for each API'
        )


    class Apis(RootModel[list[Api]]):
        root: list[Api]


    class Event(BaseModel):
        name: str | None = None


    class Result(BaseModel):
        event: Event | None = None
    ```

---

## `--enable-version-header` {#enable-version-header}

Include tool version information in file header.

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

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --enable-version-header # (1)!
    ```

    1. :material-arrow-left: `--enable-version-header` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```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
              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:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  api.yaml
    #   timestamp: 2019-07-26T00:00:00+00:00
    #   version:   0.0.0

    from __future__ import annotations

    from pydantic import AnyUrl, BaseModel, Field, RootModel


    class Pet(BaseModel):
        id: int
        name: str
        tag: str | None = None


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


    class User(BaseModel):
        id: int
        name: str
        tag: str | None = 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: str | None = Field(
            None, description='To be used as a dataset parameter value'
        )
        apiVersionNumber: str | None = Field(
            None, description='To be used as a version parameter value'
        )
        apiUrl: AnyUrl | None = Field(
            None, description="The URL describing the dataset's fields"
        )
        apiDocumentationUrl: AnyUrl | None = Field(
            None, description='A URL to the API console for each API'
        )


    class Apis(RootModel[list[Api]]):
        root: list[Api]


    class Event(BaseModel):
        name: str | None = None


    class Result(BaseModel):
        event: Event | None = None
    ```

---

## `--extra-template-data` {#extra-template-data}

Pass custom template variables via inline JSON or a JSON file path.

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

**See also:** [Custom Templates](../custom_template.md)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --extra-template-data openapi/extra_data.json # (1)!
    ```

    1. :material-arrow-left: `--extra-template-data` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```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
              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:**

    === "Pydantic v2"

        ```python
        # generated by datamodel-codegen:
        #   filename:  api.yaml
        #   timestamp: 1985-10-26T08:21:00+00:00

        from __future__ import annotations

        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: str | None = None


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


        class User(BaseModel):
            id: int
            name: str
            tag: str | None = 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: str | None = Field(
                None, description='To be used as a dataset parameter value'
            )
            apiVersionNumber: str | None = Field(
                None, description='To be used as a version parameter value'
            )
            apiUrl: AnyUrl | None = Field(
                None, description="The URL describing the dataset's fields"
            )
            apiDocumentationUrl: AnyUrl | None = Field(
                None, description='A URL to the API console for each API'
            )


        class Apis(RootModel[list[Api]]):
            root: list[Api]


        class Event(BaseModel):
            name: str | None = None


        class Result(BaseModel):
            event: Event | None = None
        ```

---

## `--formatters` {#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: builtin, black,
isort, ruff-check, ruff-format. Default is [black, isort].
Use this to customize formatting or disable formatters entirely.

**See also:** [CI/CD Integration](../ci-cd.md), [Formatter behavior](../formatter-behavior.md), [Code Formatting](../formatting.md)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --formatters isort # (1)!
    ```

    1. :material-arrow-left: `--formatters` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "Pet",
      "type": "object",
      "properties": {
        "id": {
          "type": "integer"
        },
        "name": {
          "type": "string"
        },
        "tag": {
          "type": "string"
        }
      }
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  pet_simple.json
    #   timestamp: 2019-07-26T00:00:00+00:00

    from __future__ import annotations

    from pydantic import BaseModel


    class Pet(BaseModel):
        id: int | None = None
        name: str | None = None
        tag: str | None = None
    ```

---

## `--generate-schema-validators` {#generate-schema-validators}

Generate experimental Pydantic v2 model validators for JSON Schema runtime rules.

The `--generate-schema-validators` option emits schema-derived model validators
for object constraints that cannot be represented as type hints alone, including
patternProperties on composed object models, required-only oneOf/anyOf groups,
and simple if/then/else required-property conditions. This feature is
experimental and may change as JSON Schema coverage is expanded.

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --generate-schema-validators --output-model-type pydantic_v2.BaseModel --disable-timestamp # (1)!
    ```

    1. :material-arrow-left: `--generate-schema-validators` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "$defs": {
        "First": {
          "type": "object",
          "properties": {
            "first": {
              "type": "string"
            }
          },
          "required": ["first"]
        },
        "Second": {
          "type": "object",
          "properties": {
            "second": {
              "type": "string"
            }
          },
          "required": ["second"]
        },
        "PatternBag": {
          "type": "object",
          "patternProperties": {
            "^[A-Z][A-Za-z0-9_]*$": {
              "$ref": "#/$defs/Second"
            }
          },
          "additionalProperties": false
        },
        "PatternTarget": {
          "allOf": [
            {
              "$ref": "#/$defs/First"
            },
            {
              "$ref": "#/$defs/PatternBag"
            }
          ]
        },
        "DirectPatternBag": {
          "type": "object",
          "patternProperties": {
            "^item_[0-9]+$": {
              "type": "integer"
            }
          },
          "additionalProperties": false
        },
        "ValidatorOnlyChild": {
          "allOf": [
            {
              "$ref": "#/$defs/First"
            },
            {
              "type": "object",
              "patternProperties": {
                "^extra_[A-Za-z]+$": {
                  "type": "integer"
                }
              },
              "additionalProperties": false
            }
          ]
        },
        "ValidatorOnlyPatternRef": {
          "allOf": [
            {
              "$ref": "#/$defs/First"
            }
          ],
          "patternProperties": {
            "^ref_extra_[A-Za-z]+$": {
              "type": "integer"
            }
          },
          "additionalProperties": false
        },
        "OneOfContact": {
          "type": "object",
          "properties": {
            "email": {
              "type": "string"
            },
            "phone": {
              "type": "string"
            }
          },
          "oneOf": [
            {
              "required": ["email"]
            },
            {
              "required": ["phone"]
            }
          ]
        },
        "AnyOfContact": {
          "type": "object",
          "properties": {
            "email": {
              "type": "string"
            },
            "phone": {
              "type": "string"
            }
          },
          "anyOf": [
            {
              "required": ["email"]
            },
            {
              "required": ["phone"]
            }
          ]
        },
        "ConditionalPayload": {
          "type": "object",
          "properties": {
            "kind": {
              "type": "string"
            }
          },
          "if": {
            "properties": {
              "kind": {
                "const": "metric"
              }
            },
            "required": ["kind"]
          },
          "then": {
            "properties": {
              "metric": {
                "type": "integer"
              }
            },
            "required": ["metric"]
          },
          "else": {
            "properties": {
              "note": {
                "type": "string"
              }
            },
            "required": ["note"]
          }
        },
        "RequiredOnlyGuard": {
          "type": "object",
          "properties": {
            "flag": {
              "type": "string"
            }
          },
          "oneOf": [
            {},
            {
              "required": []
            }
          ]
        }
      },
      "$ref": "#/$defs/PatternTarget"
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  schema_validators.json

    from __future__ import annotations

    import re
    from typing import Any, ClassVar

    from pydantic import BaseModel, ConfigDict, RootModel, TypeAdapter, model_validator


    class _JsonSchemaRuntimeValidationBase(BaseModel):
        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = ()
        __json_schema_one_of_required_groups__: ClassVar[tuple[Any, ...]] = ()
        __json_schema_any_of_required_groups__: ClassVar[tuple[Any, ...]] = ()
        __json_schema_conditional_required__: ClassVar[tuple[Any, ...]] = ()

        @model_validator(mode='before')
        @classmethod
        def _validate_json_schema_runtime_rules(cls, data: Any) -> Any:
            data = cls._validate_json_schema_pattern_properties(data)
            data = cls._validate_json_schema_required_groups(
                data,
                required_group_rules=cls.__json_schema_one_of_required_groups__,
                require_exactly_one=True,
            )
            data = cls._validate_json_schema_required_groups(
                data,
                required_group_rules=cls.__json_schema_any_of_required_groups__,
                require_exactly_one=False,
            )
            data = cls._validate_json_schema_conditional_required(data)
            return data

        @classmethod
        def _validate_json_schema_pattern_properties(cls, data: Any) -> Any:
            if not isinstance(data, dict):
                return data
            values = dict(data)
            for rule in cls.__json_schema_pattern_properties__:
                for key, value in data.items():
                    if key in rule['declared_properties']:
                        continue
                    if any(
                        re.search(pattern, key) for pattern in rule['rejected_patterns']
                    ):
                        raise ValueError(
                            f'Property {key!r} is not allowed by patternProperties'
                        )
                    matched = False
                    for pattern, value_type in rule['pattern_properties']:
                        if not re.search(pattern, key):
                            continue
                        matched = True
                        value = TypeAdapter(value_type).validate_python(value)
                    if matched:
                        values[key] = value
                        continue
                    if rule['additional_property_type'] is not None:
                        values[key] = TypeAdapter(
                            rule['additional_property_type']
                        ).validate_python(value)
                        continue
                    if not rule['allow_unmatched']:
                        raise ValueError(f'Unexpected property {key!r}')
            return values

        @classmethod
        def _validate_json_schema_required_groups(
            cls,
            data: Any,
            *,
            required_group_rules: tuple[Any, ...],
            require_exactly_one: bool,
        ) -> Any:
            if not required_group_rules or not isinstance(data, dict):
                return data
            for required_groups in required_group_rules:
                matches = sum(
                    all(any(name in data for name in names) for names in group)
                    for group in required_groups
                )
                if require_exactly_one:
                    if matches != 1:
                        raise ValueError(
                            'Expected exactly one required property group to be present'
                        )
                elif matches == 0:
                    raise ValueError(
                        'Expected at least one required property group to be present'
                    )
            return data

        @classmethod
        def _validate_json_schema_conditional_required(cls, data: Any) -> Any:
            if not isinstance(data, dict):
                return data
            for rule in cls.__json_schema_conditional_required__:
                condition_matches = all(
                    any(name in data and data[name] in expected for name in names)
                    for names, expected in rule['condition']
                )
                required_groups = (
                    rule['then_required_groups']
                    if condition_matches
                    else rule['else_required_groups']
                )
                for group in required_groups:
                    if all(any(name in data for name in names) for names in group):
                        continue
                    raise ValueError('Conditional required properties are missing')
            return data


    class First(BaseModel):
        first: str


    class Second(BaseModel):
        second: str


    class PatternBag(_JsonSchemaRuntimeValidationBase):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': (),
                'rejected_patterns': (),
                'pattern_properties': (('^[A-Z][A-Za-z0-9_]*$', Second),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )


    class PatternTarget(First, PatternBag):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': ('first',),
                'rejected_patterns': (),
                'pattern_properties': (('^[A-Z][A-Za-z0-9_]*$', Second),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )


    class DirectPatternBag(_JsonSchemaRuntimeValidationBase):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': (),
                'rejected_patterns': (),
                'pattern_properties': (('^item_[0-9]+$', int),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )


    class ValidatorOnlyChild(_JsonSchemaRuntimeValidationBase, First):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': ('first',),
                'rejected_patterns': (),
                'pattern_properties': (('^extra_[A-Za-z]+$', int),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )


    class ValidatorOnlyPatternRef(_JsonSchemaRuntimeValidationBase, First):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': ('first',),
                'rejected_patterns': (),
                'pattern_properties': (('^ref_extra_[A-Za-z]+$', int),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )


    class OneOfContact(_JsonSchemaRuntimeValidationBase):
        __json_schema_one_of_required_groups__: ClassVar[tuple[Any, ...]] = (
            ((('email',),), (('phone',),)),
        )

        email: str | None = None
        phone: str | None = None


    class AnyOfContact(_JsonSchemaRuntimeValidationBase):
        __json_schema_any_of_required_groups__: ClassVar[tuple[Any, ...]] = (
            ((('email',),), (('phone',),)),
        )

        email: str | None = None
        phone: str | None = None


    class ConditionalPayload(_JsonSchemaRuntimeValidationBase):
        __json_schema_conditional_required__: ClassVar[tuple[Any, ...]] = (
            {
                'condition': ((('kind',), ('metric',)),),
                'then_required_groups': ((('metric',),),),
                'else_required_groups': ((('note',),),),
            },
        )

        kind: str | None = None
        metric: int | None = None
        note: str | None = None


    class RequiredOnlyGuard1(BaseModel):
        flag: str | None = None


    class RequiredOnlyGuard(RootModel[RequiredOnlyGuard1]):
        root: RequiredOnlyGuard1


    class Model(RootModel[PatternTarget]):
        root: PatternTarget
    ```

---

## `--no-treat-dot-as-module` {#no-treat-dot-as-module}

Keep dots in schema names as underscores for flat output.

The `--no-treat-dot-as-module` flag prevents splitting dotted schema names.

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --no-treat-dot-as-module # (1)!
    ```

    1. :material-arrow-left: `--no-treat-dot-as-module` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    # 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:**

    ```python
    # __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 pydantic import BaseModel


    class User(BaseModel):
        name: str
        age: int | None = None
    ```

---

## `--no-use-type-checking-imports` {#no-use-type-checking-imports}

Keep generated model imports available at runtime when using Ruff fixes.

The `--no-use-type-checking-imports` flag prevents Ruff from moving generated model imports
into `TYPE_CHECKING` blocks. This is useful for modular Pydantic output where referenced
models need to be importable at runtime without calling `model_rebuild()` manually.
In the multi-module Pydantic + `ruff-check` case, runtime imports are preserved by default.
`--use-type-checking-imports` opts back into the old TYPE_CHECKING-only behavior, which can
require manual `model_rebuild()` calls for cross-module runtime references.

**Related:** [`--formatters`](#formatters), [`--use-exact-imports`](#use-exact-imports), [`--use-type-checking-imports`](#use-type-checking-imports)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --output-model-type pydantic_v2.BaseModel --formatters ruff-check ruff-format --no-use-type-checking-imports --disable-timestamp # (1)!
    ```

    1. :material-arrow-left: `--no-use-type-checking-imports` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```yaml
    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:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  _internal

    from __future__ import annotations
    from pydantic import BaseModel, RootModel
    from . import models


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


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


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


    class Result(BaseModel):
        event: models.Event | None = None


    class Source(BaseModel):
        country: str | None = None


    class DifferentTea(BaseModel):
        foo: Tea | None = None
        nested: Tea_1 | None = None


    class Tea(BaseModel):
        flavour: str | None = None
        id: Id | None = None


    class Cocoa(BaseModel):
        quality: int | None = None


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


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


    class List(RootModel[list[Tea_1]]):
        root: list[Tea_1]


    Tea_1.model_rebuild()
    ```

---

## `--schema-validator-base-class-name` {#schema-validator-base-class-name}

Set the generated shared Pydantic v2 schema runtime validator base class name.

The `--schema-validator-base-class-name` option changes the name of the generated
shared base class that owns schema-derived runtime validators. It is only used when
`--generate-schema-validators` emits shared validator code.

**Related:** [`--generate-schema-validators`](#generate-schema-validators)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --generate-schema-validators --schema-validator-base-class-name SharedSchemaValidatorBase --output-model-type pydantic_v2.BaseModel --disable-timestamp # (1)!
    ```

    1. :material-arrow-left: `--schema-validator-base-class-name` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "title": "CustomBaseClassName",
      "type": "object",
      "patternProperties": {
        "^item_[0-9]+$": {
          "type": "integer"
        }
      },
      "additionalProperties": false
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  schema_validators_custom_base_class_name.json

    from __future__ import annotations

    import re
    from typing import Any, ClassVar

    from pydantic import BaseModel, ConfigDict, TypeAdapter, model_validator


    class SharedSchemaValidatorBase(BaseModel):
        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = ()

        @model_validator(mode='before')
        @classmethod
        def _validate_json_schema_runtime_rules(cls, data: Any) -> Any:
            data = cls._validate_json_schema_pattern_properties(data)
            return data

        @classmethod
        def _validate_json_schema_pattern_properties(cls, data: Any) -> Any:
            if not isinstance(data, dict):
                return data
            values = dict(data)
            for rule in cls.__json_schema_pattern_properties__:
                for key, value in data.items():
                    if key in rule['declared_properties']:
                        continue
                    if any(
                        re.search(pattern, key) for pattern in rule['rejected_patterns']
                    ):
                        raise ValueError(
                            f'Property {key!r} is not allowed by patternProperties'
                        )
                    matched = False
                    for pattern, value_type in rule['pattern_properties']:
                        if not re.search(pattern, key):
                            continue
                        matched = True
                        value = TypeAdapter(value_type).validate_python(value)
                    if matched:
                        values[key] = value
                        continue
                    if rule['additional_property_type'] is not None:
                        values[key] = TypeAdapter(
                            rule['additional_property_type']
                        ).validate_python(value)
                        continue
                    if not rule['allow_unmatched']:
                        raise ValueError(f'Unexpected property {key!r}')
            return values


    class CustomBaseClassName(SharedSchemaValidatorBase):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': (),
                'rejected_patterns': (),
                'pattern_properties': (('^item_[0-9]+$', int),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )
    ```

---

## `--schema-validator-type` {#schema-validator-type}

Select the schema-derived runtime validator backend.

The `--schema-validator-type pydantic-v2` option enables the current generated
Pydantic v2 model-validator backend for JSON Schema rules that cannot be
represented as type hints alone. The explicit type keeps the CLI ready for
additional validator backends without adding them in this release.

**Related:** [`--generate-schema-validators`](#generate-schema-validators)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --schema-validator-type pydantic-v2 --output-model-type pydantic_v2.BaseModel --disable-timestamp # (1)!
    ```

    1. :material-arrow-left: `--schema-validator-type` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "$defs": {
        "First": {
          "type": "object",
          "properties": {
            "first": {
              "type": "string"
            }
          },
          "required": ["first"]
        },
        "Second": {
          "type": "object",
          "properties": {
            "second": {
              "type": "string"
            }
          },
          "required": ["second"]
        },
        "PatternBag": {
          "type": "object",
          "patternProperties": {
            "^[A-Z][A-Za-z0-9_]*$": {
              "$ref": "#/$defs/Second"
            }
          },
          "additionalProperties": false
        },
        "PatternTarget": {
          "allOf": [
            {
              "$ref": "#/$defs/First"
            },
            {
              "$ref": "#/$defs/PatternBag"
            }
          ]
        },
        "DirectPatternBag": {
          "type": "object",
          "patternProperties": {
            "^item_[0-9]+$": {
              "type": "integer"
            }
          },
          "additionalProperties": false
        },
        "ValidatorOnlyChild": {
          "allOf": [
            {
              "$ref": "#/$defs/First"
            },
            {
              "type": "object",
              "patternProperties": {
                "^extra_[A-Za-z]+$": {
                  "type": "integer"
                }
              },
              "additionalProperties": false
            }
          ]
        },
        "ValidatorOnlyPatternRef": {
          "allOf": [
            {
              "$ref": "#/$defs/First"
            }
          ],
          "patternProperties": {
            "^ref_extra_[A-Za-z]+$": {
              "type": "integer"
            }
          },
          "additionalProperties": false
        },
        "OneOfContact": {
          "type": "object",
          "properties": {
            "email": {
              "type": "string"
            },
            "phone": {
              "type": "string"
            }
          },
          "oneOf": [
            {
              "required": ["email"]
            },
            {
              "required": ["phone"]
            }
          ]
        },
        "AnyOfContact": {
          "type": "object",
          "properties": {
            "email": {
              "type": "string"
            },
            "phone": {
              "type": "string"
            }
          },
          "anyOf": [
            {
              "required": ["email"]
            },
            {
              "required": ["phone"]
            }
          ]
        },
        "ConditionalPayload": {
          "type": "object",
          "properties": {
            "kind": {
              "type": "string"
            }
          },
          "if": {
            "properties": {
              "kind": {
                "const": "metric"
              }
            },
            "required": ["kind"]
          },
          "then": {
            "properties": {
              "metric": {
                "type": "integer"
              }
            },
            "required": ["metric"]
          },
          "else": {
            "properties": {
              "note": {
                "type": "string"
              }
            },
            "required": ["note"]
          }
        },
        "RequiredOnlyGuard": {
          "type": "object",
          "properties": {
            "flag": {
              "type": "string"
            }
          },
          "oneOf": [
            {},
            {
              "required": []
            }
          ]
        }
      },
      "$ref": "#/$defs/PatternTarget"
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  schema_validators.json

    from __future__ import annotations

    import re
    from typing import Any, ClassVar

    from pydantic import BaseModel, ConfigDict, RootModel, TypeAdapter, model_validator


    class _JsonSchemaRuntimeValidationBase(BaseModel):
        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = ()
        __json_schema_one_of_required_groups__: ClassVar[tuple[Any, ...]] = ()
        __json_schema_any_of_required_groups__: ClassVar[tuple[Any, ...]] = ()
        __json_schema_conditional_required__: ClassVar[tuple[Any, ...]] = ()

        @model_validator(mode='before')
        @classmethod
        def _validate_json_schema_runtime_rules(cls, data: Any) -> Any:
            data = cls._validate_json_schema_pattern_properties(data)
            data = cls._validate_json_schema_required_groups(
                data,
                required_group_rules=cls.__json_schema_one_of_required_groups__,
                require_exactly_one=True,
            )
            data = cls._validate_json_schema_required_groups(
                data,
                required_group_rules=cls.__json_schema_any_of_required_groups__,
                require_exactly_one=False,
            )
            data = cls._validate_json_schema_conditional_required(data)
            return data

        @classmethod
        def _validate_json_schema_pattern_properties(cls, data: Any) -> Any:
            if not isinstance(data, dict):
                return data
            values = dict(data)
            for rule in cls.__json_schema_pattern_properties__:
                for key, value in data.items():
                    if key in rule['declared_properties']:
                        continue
                    if any(
                        re.search(pattern, key) for pattern in rule['rejected_patterns']
                    ):
                        raise ValueError(
                            f'Property {key!r} is not allowed by patternProperties'
                        )
                    matched = False
                    for pattern, value_type in rule['pattern_properties']:
                        if not re.search(pattern, key):
                            continue
                        matched = True
                        value = TypeAdapter(value_type).validate_python(value)
                    if matched:
                        values[key] = value
                        continue
                    if rule['additional_property_type'] is not None:
                        values[key] = TypeAdapter(
                            rule['additional_property_type']
                        ).validate_python(value)
                        continue
                    if not rule['allow_unmatched']:
                        raise ValueError(f'Unexpected property {key!r}')
            return values

        @classmethod
        def _validate_json_schema_required_groups(
            cls,
            data: Any,
            *,
            required_group_rules: tuple[Any, ...],
            require_exactly_one: bool,
        ) -> Any:
            if not required_group_rules or not isinstance(data, dict):
                return data
            for required_groups in required_group_rules:
                matches = sum(
                    all(any(name in data for name in names) for names in group)
                    for group in required_groups
                )
                if require_exactly_one:
                    if matches != 1:
                        raise ValueError(
                            'Expected exactly one required property group to be present'
                        )
                elif matches == 0:
                    raise ValueError(
                        'Expected at least one required property group to be present'
                    )
            return data

        @classmethod
        def _validate_json_schema_conditional_required(cls, data: Any) -> Any:
            if not isinstance(data, dict):
                return data
            for rule in cls.__json_schema_conditional_required__:
                condition_matches = all(
                    any(name in data and data[name] in expected for name in names)
                    for names, expected in rule['condition']
                )
                required_groups = (
                    rule['then_required_groups']
                    if condition_matches
                    else rule['else_required_groups']
                )
                for group in required_groups:
                    if all(any(name in data for name in names) for names in group):
                        continue
                    raise ValueError('Conditional required properties are missing')
            return data


    class First(BaseModel):
        first: str


    class Second(BaseModel):
        second: str


    class PatternBag(_JsonSchemaRuntimeValidationBase):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': (),
                'rejected_patterns': (),
                'pattern_properties': (('^[A-Z][A-Za-z0-9_]*$', Second),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )


    class PatternTarget(First, PatternBag):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': ('first',),
                'rejected_patterns': (),
                'pattern_properties': (('^[A-Z][A-Za-z0-9_]*$', Second),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )


    class DirectPatternBag(_JsonSchemaRuntimeValidationBase):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': (),
                'rejected_patterns': (),
                'pattern_properties': (('^item_[0-9]+$', int),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )


    class ValidatorOnlyChild(_JsonSchemaRuntimeValidationBase, First):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': ('first',),
                'rejected_patterns': (),
                'pattern_properties': (('^extra_[A-Za-z]+$', int),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )


    class ValidatorOnlyPatternRef(_JsonSchemaRuntimeValidationBase, First):
        model_config = ConfigDict(
            extra='allow',
        )

        __json_schema_pattern_properties__: ClassVar[tuple[Any, ...]] = (
            {
                'declared_properties': ('first',),
                'rejected_patterns': (),
                'pattern_properties': (('^ref_extra_[A-Za-z]+$', int),),
                'additional_property_type': None,
                'allow_unmatched': False,
            },
        )


    class OneOfContact(_JsonSchemaRuntimeValidationBase):
        __json_schema_one_of_required_groups__: ClassVar[tuple[Any, ...]] = (
            ((('email',),), (('phone',),)),
        )

        email: str | None = None
        phone: str | None = None


    class AnyOfContact(_JsonSchemaRuntimeValidationBase):
        __json_schema_any_of_required_groups__: ClassVar[tuple[Any, ...]] = (
            ((('email',),), (('phone',),)),
        )

        email: str | None = None
        phone: str | None = None


    class ConditionalPayload(_JsonSchemaRuntimeValidationBase):
        __json_schema_conditional_required__: ClassVar[tuple[Any, ...]] = (
            {
                'condition': ((('kind',), ('metric',)),),
                'then_required_groups': ((('metric',),),),
                'else_required_groups': ((('note',),),),
            },
        )

        kind: str | None = None
        metric: int | None = None
        note: str | None = None


    class RequiredOnlyGuard1(BaseModel):
        flag: str | None = None


    class RequiredOnlyGuard(RootModel[RequiredOnlyGuard1]):
        root: RequiredOnlyGuard1


    class Model(RootModel[PatternTarget]):
        root: PatternTarget
    ```

---

## `--treat-dot-as-module` {#treat-dot-as-module}

Treat dots in schema names as module separators.

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

**See also:** [Module Structure and Exports](../module-exports.md)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --treat-dot-as-module # (1)!
    ```

    1. :material-arrow-left: `--treat-dot-as-module` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    # 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:**

    ```python
    # __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 pydantic import BaseModel


    class User(BaseModel):
        name: str
        age: int | None = None
    ```

---

## `--use-double-quotes` {#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.

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --use-double-quotes # (1)!
    ```

    1. :material-arrow-left: `--use-double-quotes` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$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:**

    ```python
    # 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 Literal

    from pydantic import BaseModel, Field, RootModel, confloat


    class MapState1(BaseModel):
        map_view_mode: Literal["MODE_2D"] = Field(..., alias="mapViewMode")


    class MapState2(BaseModel):
        latitude: Latitude
        longitude: Longitude
        zoom: Zoom | None = Field(0, validate_default=True)
        bearing: Bearing | None = None
        pitch: Pitch
        drag_rotate: DragRotate | None = Field(None, alias="dragRotate")
        map_split_mode: Literal["SWIPE_COMPARE"] = Field(..., alias="mapSplitMode")
        is_split: Literal[True] = Field(True, alias="isSplit")


    class MapState3(BaseModel):
        pass


    class MapState4(MapState1, MapState3):
        pass


    class MapState5(MapState2, MapState3):
        pass


    class MapState6(MapState4):
        pass


    class MapState7(MapState5):
        pass


    class MapState(RootModel[MapState4 | MapState5 | MapState6 | MapState7]):
        root: MapState4 | MapState5 | MapState6 | MapState7 = Field(..., title="MapState")


    class Bearing(RootModel[float]):
        root: float


    class DragRotate(RootModel[bool]):
        root: bool


    class Latitude(RootModel[confloat(ge=-90.0, le=90.0)]):
        root: confloat(ge=-90.0, le=90.0)


    class Longitude(RootModel[confloat(ge=-180.0, le=180.0)]):
        root: confloat(ge=-180.0, le=180.0)


    class Pitch(RootModel[confloat(ge=0.0, lt=90.0)]):
        root: confloat(ge=0.0, lt=90.0)


    class Zoom(RootModel[confloat(ge=0.0, le=25.0)]):
        root: confloat(ge=0.0, le=25.0) = 0
    ```

---

## `--use-exact-imports` {#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.

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --use-exact-imports # (1)!
    ```

    1. :material-arrow-left: `--use-exact-imports` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "Pet",
      "type": "object",
      "properties": {
        "id": {
          "type": "integer"
        },
        "name": {
          "type": "string"
        },
        "tag": {
          "type": "string"
        }
      }
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  pet_simple.json
    #   timestamp: 2019-07-26T00:00:00+00:00

    from __future__ import annotations

    from pydantic import BaseModel


    class Pet(BaseModel):
        id: int | None = None
        name: str | None = None
        tag: str | None = None
    ```

---

## `--use-type-checking-imports` {#use-type-checking-imports}

Allow Ruff to move typing-only imports into TYPE_CHECKING blocks.

The `--use-type-checking-imports` flag explicitly re-enables Ruff's TYPE_CHECKING import moves
for multi-module Pydantic output where runtime imports might otherwise be preserved by default.

**Related:** [`--formatters`](#formatters), [`--no-use-type-checking-imports`](#no-use-type-checking-imports), [`--use-exact-imports`](#use-exact-imports)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --output-model-type pydantic_v2.BaseModel --formatters ruff-check ruff-format --use-type-checking-imports --disable-timestamp # (1)!
    ```

    1. :material-arrow-left: `--use-type-checking-imports` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```yaml
    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:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  _internal

    from __future__ import annotations

    from typing import TYPE_CHECKING

    from pydantic import BaseModel, RootModel

    if TYPE_CHECKING:
        from . import models


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


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


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


    class Result(BaseModel):
        event: models.Event | None = None


    class Source(BaseModel):
        country: str | None = None


    class DifferentTea(BaseModel):
        foo: Tea | None = None
        nested: Tea_1 | None = None


    class Tea(BaseModel):
        flavour: str | None = None
        id: Id | None = None


    class Cocoa(BaseModel):
        quality: int | None = None


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


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


    class List(RootModel[list[Tea_1]]):
        root: list[Tea_1]


    Tea_1.model_rebuild()
    ```

---

## `--validators` {#validators}

Add custom field validators to generated Pydantic v2 models.

The `--validators` option takes an inline JSON object or JSON file defining validators per model.
Each validator specifies the field(s) to validate, the validation function
to import, and optionally the mode (before/after/wrap/plain).
This allows injecting custom validation logic into generated models.

**See also:** [Field Validators](../validators.md)

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --validators tests/data/jsonschema/field_validators_config.json --output-model-type pydantic_v2.BaseModel --use-annotated --disable-timestamp # (1)!
    ```

    1. :material-arrow-left: `--validators` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "User",
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "email": {
          "type": "string",
          "format": "email"
        },
        "age": {
          "type": "integer",
          "minimum": 0
        }
      },
      "required": ["name", "email"]
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  field_validators.json

    from __future__ import annotations

    from typing import Annotated, Any

    from myapp.validators import validate_email, validate_name
    from pydantic import BaseModel, EmailStr, Field, ValidationInfo, field_validator


    class User(BaseModel):
        name: str
        email: EmailStr
        age: Annotated[int | None, Field(ge=0)] = None

        @field_validator('name', mode='before')
        @classmethod
        def validate_name_validator(cls, v: Any, info: ValidationInfo) -> Any:
            return validate_name(v, info)

        @field_validator('email', mode='after')
        @classmethod
        def validate_email_validator(cls, v: Any, info: ValidationInfo) -> Any:
            return validate_email(v, info)
    ```

---

## `--wrap-string-literal` {#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.

!!! tip "Usage"

    ```bash
    datamodel-codegen --input schema.json --wrap-string-literal # (1)!
    ```

    1. :material-arrow-left: `--wrap-string-literal` - the option documented here

??? example "Examples"

    **Input Schema:**

    ```json
    {
      "$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:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  long_description.json
    #   timestamp: 2019-07-26T00:00:00+00:00

    from __future__ import annotations

    from pydantic import BaseModel, Field


    class LongDescription(BaseModel):
        summary: str | None = Field(None, description='summary for object')
        description: str | None = Field(
            None,
            description=(
                'datamodel-code-generator. This code generator creates pydantic model from'
                ' an openapi file and others.'
            ),
        )
        multi_line: str | None = 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)'
            ),
        )
    ```

---
