Skip to content

Latest commit

 

History

History
749 lines (575 loc) · 19.1 KB

File metadata and controls

749 lines (575 loc) · 19.1 KB

📁 Base Options

📋 Options

Option Description
--encoding Specify character encoding for input and output files.
--external-ref-mapping Map external $ref files to Python packages.
--input Specify the input schema file path.
--input-file-type Specify the input file type for code generation.
--input-model Import a Python type or dict schema from a module.
--input-model-ref-strategy Strategy for referenced types when using --input-model.
--output Specify the destination path for generated Python code.
--schema-version Schema version to use for parsing.
--schema-version-mode Schema version validation mode.
--url Fetch schema from URL with custom HTTP headers.

--encoding {#encoding}

Specify character encoding for input and output files.

The --encoding flag sets the character encoding used when reading the schema file and writing the generated Python code. This is useful for schemas containing non-ASCII characters (e.g., Japanese, Chinese). Default is UTF-8, which is the standard encoding for JSON and most modern text files.

!!! tip "Usage"

```bash
datamodel-codegen --input schema.json --encoding utf-8 # (1)!
```

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

??? example "Examples"

**Input Schema:**

```json
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "日本語Model",
  "description": "モデルの説明文",
  "type": "object",
  "properties": {
    "名前": {
      "type": "string",
      "description": "ユーザー名"
    },
    "年齢": {
      "type": "integer"
    }
  }
}
```

**Output:**

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

from __future__ import annotations

from pydantic import BaseModel, Field


class 日本語Model(BaseModel):
    名前: str | None = Field(None, description='ユーザー名')
    年齢: int | None = None
```

--external-ref-mapping {#external-ref-mapping}

Map external $ref files to Python packages.

Use --external-ref-mapping FILE_PATH=PYTHON_PACKAGE to import referenced models from an existing package, instead of generating duplicate classes from external schema files.

!!! tip "Usage"

```bash
datamodel-codegen --input schema.json --input-file-type openapi --external-ref-mapping common.yaml=mypackage.shared.models # (1)!
```

1. :material-arrow-left: `--external-ref-mapping` - the option documented here

??? example "Examples"

**Input Schema:**

```yaml
openapi: "3.0.3"
info:
  title: API
  version: "1.0.0"
paths: {}
components:
  schemas:
    UserResponse:
      type: object
      properties:
        user:
          $ref: "common.yaml#/components/schemas/User"
        request_id:
          type: string
      required:
        - user
        - request_id
    ErrorResponse:
      type: object
      properties:
        error:
          $ref: "common.yaml#/components/schemas/Error"
        timestamp:
          type: string
          format: date-time
      required:
        - error
        - timestamp
```

**Output:**

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

from __future__ import annotations

from mypackage.shared.models import Error, User
from pydantic import AwareDatetime, BaseModel


class UserResponse(BaseModel):
    user: User
    request_id: str


class ErrorResponse(BaseModel):
    error: Error
    timestamp: AwareDatetime
```

--input {#input}

Specify the input schema file path.

The --input flag specifies the path to the schema file (JSON Schema, OpenAPI, GraphQL, etc.). Multiple input files can be specified to merge schemas. Required unless using --url to fetch schema from a URL.

!!! tip "Usage"

```bash
datamodel-codegen --input schema.json --input pet_simple.json --output output.py # (1)!
```

1. :material-arrow-left: `--input` - 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
```

--input-file-type {#input-file-type}

Specify the input file type for code generation.

The --input-file-type flag explicitly sets the input format.

Important distinction:

  • Use jsonschema, openapi, or graphql for schema definition files
  • Use json, yaml, or csv for raw sample data to automatically infer a schema

For example, if you have a JSON Schema written in YAML format, use --input-file-type jsonschema, not --input-file-type yaml. The yaml type treats the file as raw data and infers a schema from it.

!!! tip "Usage"

```bash
datamodel-codegen --input schema.json --input-file-type json # (1)!
```

1. :material-arrow-left: `--input-file-type` - the option documented here

??? example "Examples"

=== "JSON"

    **Input Schema:**

    ```json
    {
      "Pet": {
        "name": "dog",
        "age": 2
      }
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  pet.json
    #   timestamp: 2019-07-26T00:00:00+00:00
    
    from __future__ import annotations
    
    from pydantic import BaseModel, Field
    
    
    class Pet(BaseModel):
        name: str
        age: int
    
    
    class Model(BaseModel):
        Pet_1: Pet = Field(..., alias='Pet')
    ```

=== "YAML"

    **Input Schema:**

    ```yaml
    Pet:
      name: cat
      age: 3
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  pet.yaml
    #   timestamp: 2019-07-26T00:00:00+00:00
    
    from __future__ import annotations
    
    from pydantic import BaseModel, Field
    
    
    class Pet(BaseModel):
        name: str
        age: int
    
    
    class Model(BaseModel):
        Pet_1: Pet = Field(..., alias='Pet')
    ```

--input-model {#input-model}

Import a Python type or dict schema from a module.

Use the format module:Object or path/to/file.py:Object to specify the type.

!!! tip "Usage"

```bash
datamodel-codegen --input schema.json --input-model mymodule:MyModel # (1)!
```

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

??? example "Examples"

**Output:**

--input-model-ref-strategy {#input-model-ref-strategy}

Strategy for referenced types when using --input-model.

The --input-model-ref-strategy option determines whether to regenerate or import referenced types. Use regenerate-all (default) to regenerate all types, reuse-foreign to import types from different families (like enums when generating dataclasses) while regenerating same-family types, or reuse-all to import all referenced types directly.

!!! tip "Usage"

```bash
datamodel-codegen --input schema.json --input-model-ref-strategy reuse-foreign # (1)!
```

1. :material-arrow-left: `--input-model-ref-strategy` - the option documented here

??? example "Examples"

**Output:**

--output {#output}

Specify the destination path for generated Python code.

The --output flag specifies where to write the generated Python code. It can be either a file path (single-file output) or a directory path (multi-file output for modular schemas). If omitted, the generated code is written to stdout.

!!! tip "Usage"

```bash
datamodel-codegen --input schema.json --input pet_simple.json --output output.py # (1)!
```

1. :material-arrow-left: `--output` - 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
```

--schema-version {#schema-version}

Schema version to use for parsing.

The --schema-version option specifies the schema version to use instead of auto-detection. Valid values depend on input type: JsonSchema (draft-04, draft-06, draft-07, 2019-09, 2020-12) or OpenAPI (3.0, 3.1). Default is 'auto' (detected from $schema or openapi field).

!!! tip "Usage"

```bash
datamodel-codegen --input schema.json --schema-version draft-07 # (1)!
```

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

??? example "Examples"

=== "OpenAPI"

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

    > **Error:** File not found: openapi/api.py

=== "JSON Schema"

    **Input Schema:**

    ```json
    {
      "$schema": "http://json-schema.org/draft-07/schema",
      "type": "object",
      "properties": {"s": {"type": ["string"]}},
      "required": ["s"]
    }
    ```

    **Output:**

    ```python
    # generated by datamodel-codegen:
    #   filename:  simple_string.json
    
    from __future__ import annotations
    
    from pydantic import BaseModel
    
    
    class Model(BaseModel):
        s: str
    ```

--schema-version-mode {#schema-version-mode}

Schema version validation mode.

The --schema-version-mode option controls how schema version validation is performed. 'lenient' (default): accept all features regardless of version. 'strict': warn on features outside the declared/detected version.

!!! tip "Usage"

```bash
datamodel-codegen --input schema.json --schema-version-mode lenient # (1)!
```

1. :material-arrow-left: `--schema-version-mode` - the option documented here

??? example "Examples"

**Input Schema:**

```json
{
  "$schema": "http://json-schema.org/draft-07/schema",
  "type": "object",
  "properties": {"s": {"type": ["string"]}},
  "required": ["s"]
}
```

**Output:**

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

from __future__ import annotations

from pydantic import BaseModel


class Model(BaseModel):
    s: str
```

--url {#url}

Fetch schema from URL with custom HTTP headers.

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

!!! tip "Usage"

```bash
datamodel-codegen --input schema.json --url https://api.example.com/schema.json --http-headers "Authorization:Bearer token" # (1)!
```

1. :material-arrow-left: `--url` - 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:  https://api.example.com/schema.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
```