Skip to content

📁 Base Options

📋 Options

Option Description
--emit-model-metadata Write a separate JSON map from the final generated models, m...
--encoding Specify character encoding for input and output files.
--external-ref-mapping Map external $ref files to Python packages.
--http-backend Select the HTTP client backend for remote schemas.
--ignore-ref-siblings-by-schema-version Read a $ref as its target alone where the schema version i...
--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 or Python ...
--input-model-ref-strategy Strategy for referenced types when using --input-model.
--output Specify the destination path for generated Python code.
--preset Apply an immutable built-in option preset.
--read-dynamic-anchors-in-document-order Resolve a $dynamicRef to the first $dynamicAnchor of its...
--read-escaped-ref-pointers Read the escapes of a $ref JSON pointer as the characters ...
--read-input-model-dataclass-fields-by-alias Read the fields of a Pydantic dataclass by their aliases wit...
--read-schema-version-per-document Read each document by the schema version it declares.
--reuse-every-reached-input-model-type Reach the types to reuse through every model kind and write ...
--schema-version Schema version to use for parsing.
--schema-version-mode Schema version validation mode.
--url Fetch a schema from a URL with custom HTTP headers.

🍳 Recipes

Generate a local schema file

Pin the input type and destination when the source extension is ambiguous or generated output needs a stable path.

Options: --input, --input-file-type, --output

Fetch a protected remote schema

Use URL input together with HTTP request controls for schemas served behind headers or slower endpoints.

Options: --url, --http-headers, --http-timeout


--emit-model-metadata

Write a separate JSON map from the final generated models, modules, fields, and type hints to the JSON Pointer locations of their source schemas. Several models can share one location, such as read and write variants of one schema, so the module and class name identify a model.

Usage

datamodel-codegen --input model_metadata.json --emit-model-metadata model-map.json --module-split-mode single --disable-timestamp # (1)!
  1. --emit-model-metadata - the option documented here
Examples

Input Schema:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Root title",
  "type": "object",
  "properties": {
    "method": {
      "const": "thread/started"
    },
    "payload": {
      "$ref": "#/$defs/MetadataPayload"
    }
  },
  "required": ["method", "payload"],
  "$defs": {
    "MetadataPayload": {
      "title": "Payload title",
      "type": "object",
      "properties": {
        "id": {
          "type": "integer"
        }
      },
      "required": ["id"]
    }
  }
}

Output:

# generated by datamodel-codegen:
#   filename:  model_metadata.json

from __future__ import annotations

from typing import Literal

from pydantic import BaseModel

from . import metadata_payload


class RootTitle(BaseModel):
    method: Literal['thread/started']
    payload: metadata_payload.MetadataPayload

Generated metadata (model-map.json):

{
  "version": 1,
  "models": [
    {
      "class_name": "RootTitle",
      "name": "RootTitle",
      "module": "root_title",
      "source_ref": "model_metadata.json#",
      "source_path": [],
      "title": "Root title",
      "fields": [
        {
          "name": "method",
          "alias": "method",
          "original_name": "method",
          "type": "Literal['thread/started']",
          "required": true
        },
        {
          "name": "payload",
          "alias": "payload",
          "original_name": "payload",
          "type": "metadata_payload.MetadataPayload",
          "required": true
        }
      ]
    },
    {
      "class_name": "MetadataPayload",
      "name": "MetadataPayload",
      "module": "metadata_payload",
      "source_ref": "model_metadata.json#/$defs/MetadataPayload",
      "source_path": [
        "$defs",
        "MetadataPayload"
      ],
      "title": "Payload title",
      "fields": [
        {
          "name": "id",
          "alias": "id",
          "original_name": "id",
          "type": "int",
          "required": true
        }
      ]
    }
  ]
}

--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.

Usage

datamodel-codegen --input encoding_test.json --encoding utf-8 # (1)!
  1. --encoding - the option documented here
Examples

Input Schema:

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

Output:

# 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

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.

Usage

datamodel-codegen --input api.yaml --input-file-type openapi --external-ref-mapping common.yaml=mypackage.shared.models # (1)!
  1. --external-ref-mapping - the option documented here
Examples

Input Schema:

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:

# 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

--http-backend

Select the HTTP client backend for remote schemas.

--http-backend auto selects stable HTTPX when its client module is installed and selects experimental HTTPX2 only when that module is absent. Explicit httpx or httpx2 selections require that exact backend. Explicit selections and paired dependency errors do not fall back.

Usage

datamodel-codegen --input pet_simple.json --http-backend auto # (1)!
  1. --http-backend - the option documented here
Examples

Input Schema:

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

Output:

# generated by datamodel-codegen:
#   filename:  http://localhost/schema.json

from __future__ import annotations

from pydantic import BaseModel


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

--ignore-ref-siblings-by-schema-version

Read a $ref as its target alone where the schema version ignores the keywords beside it.

JSON Schema draft 4, 6 and 7, OpenAPI 3.0 and AsyncAPI 2 ignore every keyword beside a $ref. Without the option those keywords overlay the referenced schema: a sibling format: binary types the field bytes, a sibling maxLength constrains it, and a sibling uniqueItems makes it a set under --use-unique-items-as-set. With --ignore-ref-siblings-by-schema-version the field is typed by the referenced schema alone, and annotations beside the $ref, such as description or default, are left out too. Versions that apply the keywords beside a $ref (2019-09 and later, OpenAPI 3.1 and later, AsyncAPI 3) read them as before. The version is the one --read-schema-version-per-document reads, else that of the document being parsed. A schema converted from Avro, XML Schema or Protocol Buffers, also as an AsyncAPI payload, keeps the keywords its converter writes beside a $ref, such as the default of a field typed by a named type.

Usage

datamodel-codegen --input ref_siblings_ignored_oas30.yaml --ignore-ref-siblings-by-schema-version # (1)!
  1. --ignore-ref-siblings-by-schema-version - the option documented here
Examples

Input Schema:

openapi: 3.0.3
info:
  title: Keywords beside a Reference Object
  version: '1'
paths: {}
components:
  schemas:
    Text:
      type: string
    Holder:
      type: object
      properties:
        data:
          $ref: '#/components/schemas/Text'
          format: binary
        note:
          $ref: '#/components/schemas/Text'
          description: A note
          maxLength: 3

Output:

# generated by datamodel-codegen:
#   filename:  ref_siblings_ignored_oas30.yaml

from __future__ import annotations

from pydantic import BaseModel, RootModel


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


class Holder(BaseModel):
    data: Text | None = None
    note: Text | None = None
# generated by datamodel-codegen:
#   filename:  ref_siblings_ignored_oas30.yaml

from __future__ import annotations

from pydantic import BaseModel, Field, RootModel, constr


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


class Holder(BaseModel):
    data: bytes | None = None
    note: constr(max_length=3) | None = Field(None, description='A note')

--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.

Usage

datamodel-codegen --input pet_simple.json --output output.py # (1)!
  1. --input - the option documented here
Examples

Input Schema:

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

Output:

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

from __future__ import annotations

from pydantic import BaseModel


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

--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, asyncapi, graphql, mcp-tools, xmlschema, protobuf, or avro 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.

Usage

datamodel-codegen --input pet.json --input-file-type json # (1)!
  1. --input-file-type - the option documented here
Examples

Input Schema:

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

Output:

# 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')

Input Schema:

Pet:
  name: cat
  age: 3

Output:

# 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

Import a Python type or dict schema from a module or Python file.

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

Usage

datamodel-codegen --input schema.json --input-model mymodule:MyModel # (1)!
  1. --input-model - the option documented here
Examples

Command:

datamodel-codegen \
  --input-model tests.data.python.input_model.typeddict_models:User \
  --output model.py

Input Model (tests/data/python/input_model/typeddict_models.py):

"""TypedDict models for --input-model tests."""

from typing_extensions import TypedDict


class User(TypedDict):
    """User TypedDict with basic fields."""

    name: str
    age: int

Output:

from __future__ import annotations

from pydantic import BaseModel, Field


class User(BaseModel):
    name: str = Field(..., title='Name')
    age: int = Field(..., title='Age')

--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.

Usage

datamodel-codegen --input schema.json --input-model-ref-strategy reuse-foreign # (1)!
  1. --input-model-ref-strategy - the option documented here
Examples

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.

Usage

datamodel-codegen --input pet_simple.json --output output.py # (1)!
  1. --output - the option documented here
Examples

Input Schema:

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

Output:

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

from __future__ import annotations

from pydantic import BaseModel


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

--preset

Apply an immutable built-in option preset.

The standard-py312-20260619 preset enables the recommended modern Python output style for new projects. The preset name pins generated Python syntax and backports.

Related: --target-python-version

See also: pyproject.toml Configuration

Usage

datamodel-codegen --input person.json --preset standard-py312-20260619 # (1)!
  1. --preset - the option documented here
Examples

Input Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Person",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string",
      "description": "The person's first name."
    },
    "lastName": {
      "type": ["string", "null"],
      "description": "The person's last name."
    },
    "age": {
      "description": "Age in years which must be equal to or greater than zero.",
      "type": "integer",
      "minimum": 0
    },
    "friends": {
      "type": "array"
    },
    "comment": {
      "type": "null"
    }
  }
}

Output:

# generated by datamodel-codegen:
#   filename:  person.json

from __future__ import annotations

from typing import Annotated, Any

from pydantic import BaseModel, ConfigDict, Field


class Person(BaseModel):
    model_config = ConfigDict(
        populate_by_name=True,
    )
    first_name: Annotated[
        str | None, Field(alias='firstName', description="The person's first name.")
    ] = None
    last_name: Annotated[
        str | None, Field(alias='lastName', description="The person's last name.")
    ] = None
    age: Annotated[
        int | None,
        Field(
            description='Age in years which must be equal to or greater than zero.',
            ge=0,
        ),
    ] = None
    friends: list[Any] | None = None
    comment: Annotated[None, Field(None)] = None

--read-dynamic-anchors-in-document-order

Resolve a $dynamicRef to the first $dynamicAnchor of its name in document order.

A plain-name $dynamicRef that its dynamic scope does not bind names a $dynamicAnchor of its name in its document. Without this option that is the first one the parse has met, so the answer depends on the order of the schemas: with Holder written before the components First and Second that both declare $dynamicAnchor: T, #T resolves to Second, written after them to First. With it the document as loaded decides: the first declaration in document order. A $ref or $dynamicRef to a plain name several schemas of a document declare, which JSON Schema leaves undefined and which warns either way, names the first declaration too, where it names the last without the option.

Usage

datamodel-codegen --input dynamic_ref_anchor_parse_order.yaml --read-dynamic-anchors-in-document-order # (1)!
  1. --read-dynamic-anchors-in-document-order - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: dynamic anchor parse order
  version: "1"
paths: {}
components:
  schemas:
    Holder:
      type: object
      properties:
        item:
          $dynamicRef: "#T"
    First:
      $dynamicAnchor: T
      type: object
      properties:
        first:
          type: integer
    Second:
      $dynamicAnchor: T
      type: object
      properties:
        second:
          type: string

Output:

# generated by datamodel-codegen:
#   filename:  dynamic_ref_anchor_parse_order.yaml

from __future__ import annotations

from pydantic import BaseModel


class First(BaseModel):
    first: int | None = None


class Second(BaseModel):
    second: str | None = None


class Holder(BaseModel):
    item: First | None = None
# generated by datamodel-codegen:
#   filename:  dynamic_ref_anchor_parse_order.yaml

from __future__ import annotations

from pydantic import BaseModel


class First(BaseModel):
    first: int | None = None


class Second(BaseModel):
    second: str | None = None


class Holder(BaseModel):
    item: Second | None = None

--read-escaped-ref-pointers

Read the escapes of a $ref JSON pointer as the characters they encode.

A pointer writes / in a name as ~1, ~ as ~0, and, in a URI fragment, any other character percent-encoded (%20 for a space). Without this option a reference keeps the escaped text as the key of its target, so the definition it names, keyed by its name, gets a copy named after the escaped text (Line20Item beside LineItem, Tax1rate beside TaxRate), which the field takes. With it every spelling of a pointer names the one model of its target, keyed as the api scope keys it; a model a reference adds is named after the decoded name, and a --model-name-map key that names a path matches it in any spelling, in the api scope too, where the first of the keys that spell one path renames it. A / written unescaped inside a name is a separator then, as JSON Pointer reads it, also after a ~1, so such a pointer warns as a dangling reference, unless the name holds ://, which is still read whole.

Usage

datamodel-codegen --input escaped_ref_pointers.json --read-escaped-ref-pointers # (1)!
  1. --read-escaped-ref-pointers - the option documented here
Examples

Input Schema:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Order",
  "type": "object",
  "properties": {
    "spaced": {"$ref": "#/$defs/Line%20Item"},
    "slashed": {"$ref": "#/$defs/tax~1rate"},
    "tilded": {"$ref": "#/$defs/note~0text"},
    "percent": {"$ref": "#/$defs/50%25"},
    "raw": {"$ref": "#/$defs/Line Item"},
    "items": {"type": "array", "items": {"$ref": "#/$defs/Line%20Item"}}
  },
  "$defs": {
    "Line Item": {"type": "object", "properties": {"sku": {"type": "string"}}, "required": ["sku"]},
    "tax/rate": {"type": "object", "properties": {"rate": {"type": "number"}}},
    "note~text": {"type": "object", "properties": {"body": {"type": "string"}}},
    "50%": {"type": "object", "properties": {"share": {"type": "integer"}}}
  }
}

Output:

# generated by datamodel-codegen:
#   filename:  escaped_ref_pointers.json

from __future__ import annotations

from pydantic import BaseModel


class LineItem(BaseModel):
    sku: str


class TaxRate(BaseModel):
    rate: float | None = None


class NoteText(BaseModel):
    body: str | None = None


class Field50(BaseModel):
    share: int | None = None


class Order(BaseModel):
    spaced: LineItem | None = None
    slashed: TaxRate | None = None
    tilded: NoteText | None = None
    percent: Field50 | None = None
    raw: LineItem | None = None
    items: list[LineItem] | None = None
# generated by datamodel-codegen:
#   filename:  escaped_ref_pointers.json

from __future__ import annotations

from pydantic import BaseModel


class LineItem(BaseModel):
    sku: str


class TaxRate(BaseModel):
    rate: float | None = None


class NoteText(BaseModel):
    body: str | None = None


class Field50(BaseModel):
    share: int | None = None


class Field5025(BaseModel):
    share: int | None = None


class Line20Item(BaseModel):
    sku: str


class Note0text(BaseModel):
    body: str | None = None


class Tax1rate(BaseModel):
    rate: float | None = None


class Order(BaseModel):
    spaced: Line20Item | None = None
    slashed: Tax1rate | None = None
    tilded: Note0text | None = None
    percent: Field5025 | None = None
    raw: LineItem | None = None
    items: list[Line20Item] | None = None

--read-input-model-dataclass-fields-by-alias

Read the fields of a Pydantic dataclass by their aliases with --input-model.

--input-model gives each field the Python type of its model, such as deque[int], where JSON Schema cannot spell it. A Pydantic dataclass is read by its annotations, keyed by field name, so a field with an alias takes the type its JSON Schema spells (list[int]) instead. With this option the fields of a Pydantic dataclass are read with their aliases, as those of a model, so an aliased field keeps its Python type like one without.

Usage

datamodel-codegen --input schema.json --input-model mymodule:Outer --read-input-model-dataclass-fields-by-alias # (1)!
  1. --read-input-model-dataclass-fields-by-alias - the option documented here
Examples

Output:

# generated by datamodel-codegen:
#   filename:  <stdin>
#   timestamp: 1985-10-26T08:21:00+00:00

from __future__ import annotations

from collections import deque

from pydantic import BaseModel, Field


class Inner(BaseModel):
    myItems: deque[int] | None = Field(None, title='Myitems')
    other_items: deque[int] | None = Field(None, title='Other Items')


class Outer(BaseModel):
    inner: Inner
# generated by datamodel-codegen:
#   filename:  <stdin>
#   timestamp: 1985-10-26T08:21:00+00:00

from __future__ import annotations

from collections import deque

from pydantic import BaseModel, Field


class Inner(BaseModel):
    myItems: list[int] | None = Field(None, title='Myitems')
    other_items: deque[int] | None = Field(None, title='Other Items')


class Outer(BaseModel):
    inner: Inner

--read-schema-version-per-document

Read each document by the schema version it declares.

Without the option the schema version of the document parsed first decides, for every document of a run, whether the keywords beside a $ref apply and which features of its version are read (const, prefixItems, $id, $defs). With --read-schema-version-per-document each document is read by the version its $schema, openapi or asyncapi field declares; a referenced document that declares none takes the version of the document whose reference loads it, and an input document that declares none is read as it is on its own. Here the draft-07 document ignores the maximum beside its allOf $ref, as draft 7 says, and the 2020-12 root keeps it. An OpenAPI 3.1 document reads the keywords beside a $ref as JSON Schema 2020-12 does, and the property-count rule of --generate-schema-validators leaves out a minProperties beside an allOf $ref of a draft-07 document. An explicit --schema-version reads every document by that version, with or without the option, except that without it the schema validators of --generate-schema-validators read an OpenAPI or AsyncAPI document as draft 7.

Usage

datamodel-codegen --input root.json --read-schema-version-per-document # (1)!
  1. --read-schema-version-per-document - the option documented here
Examples

Input Schema:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Root",
  "type": "object",
  "properties": {
    "legacy": {
      "$ref": "legacy_draft07.json#/definitions/Score"
    },
    "score": {
      "$ref": "#/$defs/Score"
    }
  },
  "$defs": {
    "Positive": {
      "type": "integer",
      "minimum": 1
    },
    "Score": {
      "allOf": [
        {
          "$ref": "#/$defs/Positive",
          "maximum": 10
        }
      ]
    }
  }
}

Output:

# generated by datamodel-codegen:
#   filename:  root.json

from __future__ import annotations

from pydantic import BaseModel, RootModel, conint


class Positive(RootModel[conint(ge=1)]):
    root: conint(ge=1)


class Score(RootModel[conint(ge=1, le=10)]):
    root: conint(ge=1, le=10)


class ScoreModel(RootModel[Positive]):
    root: Positive


class Root(BaseModel):
    legacy: ScoreModel | None = None
    score: Score | None = None
# generated by datamodel-codegen:
#   filename:  root.json

from __future__ import annotations

from pydantic import BaseModel, RootModel, conint


class Score(RootModel[conint(ge=1, le=10)]):
    root: conint(ge=1, le=10)


class Positive(RootModel[conint(ge=1)]):
    root: conint(ge=1)


class Root(BaseModel):
    legacy: Score | None = None
    score: Score | None = None

--reuse-every-reached-input-model-type

Reach the types to reuse through every model kind and write no copy of an imported type.

With --input-model-ref-strategy reuse-all or reuse-foreign the types an input model reaches are imported from its module instead of generated. Reuse follows the fields of Pydantic models only, so a type reached through a dataclass field is still generated: Color, which only the dataclass Box uses, is written although Box is imported (reuse-all), or written beside the imported Size (reuse-foreign). A field whose Python type the output keeps, such as Mapping[str, Item], imports Item, and a copy of Item (ItemModel) is written too. With this option reuse follows the fields of dataclasses, TypedDicts and msgspec Structs too, and a type that the Python type of a field imports is reused instead of copied, so references to it name the import.

Usage

datamodel-codegen --input schema.json --input-model mymodule:Order --input-model-ref-strategy reuse-foreign --reuse-every-reached-input-model-type # (1)!
  1. --reuse-every-reached-input-model-type - the option documented here
Examples

Output:

# generated by datamodel-codegen:
#   filename:  <stdin>
#   timestamp: 1985-10-26T08:21:00+00:00

from __future__ import annotations

from pydantic import BaseModel

from reached_types import Color, Size


class Box(BaseModel):
    color: Color


class Order(BaseModel):
    box: Box
    size: Size
# generated by datamodel-codegen:
#   filename:  <stdin>
#   timestamp: 1985-10-26T08:21:00+00:00

from __future__ import annotations

from enum import Enum

from pydantic import BaseModel

from reached_types import Size


class Color(Enum):
    red = 'red'
    blue = 'blue'


class Box(BaseModel):
    color: Color


class Order(BaseModel):
    box: Box
    size: Size

--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, 3.2). Default is 'auto' (detected from $schema or openapi field).

Usage

datamodel-codegen --input simple_string.json --schema-version draft-07 # (1)!
  1. --schema-version - the option documented here
Examples

Input Schema:

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

Output:

Error: File not found: openapi/api.py

Input Schema:

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

Output:

# 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 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.

Usage

datamodel-codegen --input simple_string.json --schema-version-mode lenient # (1)!
  1. --schema-version-mode - the option documented here
Examples

Input Schema:

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

Output:

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

from __future__ import annotations

from pydantic import BaseModel


class Model(BaseModel):
    s: str

--url

Fetch a schema from a 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 request headers in HeaderName:HeaderValue format.

Usage

datamodel-codegen --url https://api.example.com/schema.json --http-headers "Authorization:Bearer token" # (1)!
  1. --url - the option documented here
Examples

Input Schema:

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

Output:

# generated by datamodel-codegen:
#   filename:  https://api.example.com/schema.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from pydantic import BaseModel


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