Skip to content

🔧 Typing Customization

📋 Options

Option Description
--allof-merge-mode Merge constraints from root model references in allOf schema...
--disable-future-imports Prevent automatic addition of future imports in generate...
--enum-field-as-literal Convert all enum fields to Literal types instead of Enum cla...
--no-use-specialized-enum Disable specialized Enum classes for Python 3.11+ code gener...
--output-datetime-class Specify datetime class type for date-time schema fields.
--strict-types Enable strict type validation for specified Python types.
--type-mappings Override default type mappings for schema formats.
--use-annotated Test GraphQL annotated types with standard collections and u...
--use-decimal-for-multiple-of Generate Decimal types for fields with multipleOf constraint...
--use-generic-container-types Use typing.Dict/List instead of dict/list for container type...
--use-non-positive-negative-number-constrained-types Use NonPositive/NonNegative types for number constraints.
--use-pendulum Use pendulum types for date/time fields instead of datetime ...
--use-standard-collections Use built-in dict/list instead of typing.Dict/List.
--use-type-alias Use TypeAlias instead of root models for type definitions (e...
--use-union-operator Test GraphQL annotated types with standard collections and u...
--use-unique-items-as-set Generate set types for arrays with uniqueItems constraint.

--allof-merge-mode

Merge constraints from root model references in allOf schemas.

The --allof-merge-mode constraints merges only constraint properties (minLength, maximum, etc.) from parent schemas referenced in allOf. This ensures child schemas inherit validation constraints while keeping other properties separate.

Usage

datamodel-codegen --input schema.json --allof-merge-mode constraints # (1)!
  1. --allof-merge-mode - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "StringDatatype": {
      "description": "A base string type.",
      "type": "string",
      "pattern": "^\\S(.*\\S)?$"
    },
    "ConstrainedStringDatatype": {
      "description": "A constrained string.",
      "allOf": [
        { "$ref": "#/definitions/StringDatatype" },
        { "type": "string", "minLength": 1, "pattern": "^[A-Z].*" }
      ]
    },
    "IntegerDatatype": {
      "description": "A whole number.",
      "type": "integer"
    },
    "NonNegativeIntegerDatatype": {
      "description": "Non-negative integer.",
      "allOf": [
        { "$ref": "#/definitions/IntegerDatatype" },
        { "minimum": 0 }
      ]
    },
    "BoundedIntegerDatatype": {
      "description": "Integer between 0 and 100.",
      "allOf": [
        { "$ref": "#/definitions/IntegerDatatype" },
        { "minimum": 0, "maximum": 100 }
      ]
    },
    "EmailDatatype": {
      "description": "Email with format.",
      "allOf": [
        { "$ref": "#/definitions/StringDatatype" },
        { "format": "email" }
      ]
    },
    "FormattedStringDatatype": {
      "description": "A string with email format.",
      "type": "string",
      "format": "email"
    },
    "ObjectBase": {
      "type": "object",
      "properties": {
        "id": { "type": "integer" }
      }
    },
    "ObjectWithAllOf": {
      "description": "Object inheritance - not a root model.",
      "allOf": [
        { "$ref": "#/definitions/ObjectBase" },
        { "type": "object", "properties": { "name": { "type": "string" } } }
      ]
    },
    "MultiRefAllOf": {
      "description": "Multiple refs - not handled by new code.",
      "allOf": [
        { "$ref": "#/definitions/StringDatatype" },
        { "$ref": "#/definitions/IntegerDatatype" }
      ]
    },
    "NoConstraintAllOf": {
      "description": "No constraints added.",
      "allOf": [
        { "$ref": "#/definitions/StringDatatype" }
      ]
    },
    "IncompatibleTypeAllOf": {
      "description": "Incompatible types.",
      "allOf": [
        { "$ref": "#/definitions/StringDatatype" },
        { "type": "boolean" }
      ]
    },
    "ConstraintWithProperties": {
      "description": "Constraint item has properties.",
      "allOf": [
        { "$ref": "#/definitions/StringDatatype" },
        { "properties": { "extra": { "type": "string" } } }
      ]
    },
    "ConstraintWithItems": {
      "description": "Constraint item has items.",
      "allOf": [
        { "$ref": "#/definitions/StringDatatype" },
        { "items": { "type": "string" } }
      ]
    },
    "NumberIntegerCompatible": {
      "description": "Number and integer are compatible.",
      "allOf": [
        { "$ref": "#/definitions/IntegerDatatype" },
        { "type": "number", "minimum": 0 }
      ]
    },
    "RefWithSchemaKeywords": {
      "description": "Ref with additional schema keywords.",
      "allOf": [
        { "$ref": "#/definitions/StringDatatype", "minLength": 5 },
        { "maxLength": 100 }
      ]
    },
    "ArrayDatatype": {
      "type": "array",
      "items": { "type": "string" }
    },
    "RefToArrayAllOf": {
      "description": "Ref to array - not a root model.",
      "allOf": [
        { "$ref": "#/definitions/ArrayDatatype" },
        { "minItems": 1 }
      ]
    },
    "ObjectNoPropsDatatype": {
      "type": "object"
    },
    "RefToObjectNoPropsAllOf": {
      "description": "Ref to object without properties - not a root model.",
      "allOf": [
        { "$ref": "#/definitions/ObjectNoPropsDatatype" },
        { "minProperties": 1 }
      ]
    },
    "PatternPropsDatatype": {
      "patternProperties": {
        "^S_": { "type": "string" }
      }
    },
    "RefToPatternPropsAllOf": {
      "description": "Ref to patternProperties - not a root model.",
      "allOf": [
        { "$ref": "#/definitions/PatternPropsDatatype" },
        { "minProperties": 1 }
      ]
    },
    "NestedAllOfDatatype": {
      "allOf": [
        { "type": "string" },
        { "minLength": 1 }
      ]
    },
    "RefToNestedAllOfAllOf": {
      "description": "Ref to nested allOf - not a root model.",
      "allOf": [
        { "$ref": "#/definitions/NestedAllOfDatatype" },
        { "maxLength": 100 }
      ]
    },
    "ConstraintsOnlyDatatype": {
      "description": "Constraints only, no type.",
      "minLength": 1,
      "pattern": "^[A-Z]"
    },
    "RefToConstraintsOnlyAllOf": {
      "description": "Ref to constraints-only schema.",
      "allOf": [
        { "$ref": "#/definitions/ConstraintsOnlyDatatype" },
        { "maxLength": 100 }
      ]
    },
    "NoDescriptionAllOf": {
      "allOf": [
        { "$ref": "#/definitions/StringDatatype" },
        { "minLength": 5 }
      ]
    },
    "EmptyConstraintItemAllOf": {
      "description": "AllOf with empty constraint item.",
      "allOf": [
        { "$ref": "#/definitions/StringDatatype" },
        {},
        { "maxLength": 50 }
      ]
    },
    "ConflictingFormatAllOf": {
      "description": "Conflicting formats - falls back to existing behavior.",
      "allOf": [
        { "$ref": "#/definitions/FormattedStringDatatype" },
        { "format": "date-time" }
      ]
    }
  },
  "type": "object",
  "properties": {
    "name": { "$ref": "#/definitions/ConstrainedStringDatatype" },
    "count": { "$ref": "#/definitions/NonNegativeIntegerDatatype" },
    "percentage": { "$ref": "#/definitions/BoundedIntegerDatatype" },
    "email": { "$ref": "#/definitions/EmailDatatype" },
    "obj": { "$ref": "#/definitions/ObjectWithAllOf" },
    "multi": { "$ref": "#/definitions/MultiRefAllOf" },
    "noconstraint": { "$ref": "#/definitions/NoConstraintAllOf" },
    "incompatible": { "$ref": "#/definitions/IncompatibleTypeAllOf" },
    "withprops": { "$ref": "#/definitions/ConstraintWithProperties" },
    "withitems": { "$ref": "#/definitions/ConstraintWithItems" },
    "numint": { "$ref": "#/definitions/NumberIntegerCompatible" },
    "refwithkw": { "$ref": "#/definitions/RefWithSchemaKeywords" },
    "refarr": { "$ref": "#/definitions/RefToArrayAllOf" },
    "refobjnoprops": { "$ref": "#/definitions/RefToObjectNoPropsAllOf" },
    "refpatternprops": { "$ref": "#/definitions/RefToPatternPropsAllOf" },
    "refnestedallof": { "$ref": "#/definitions/RefToNestedAllOfAllOf" },
    "refconstraintsonly": { "$ref": "#/definitions/RefToConstraintsOnlyAllOf" },
    "nodescription": { "$ref": "#/definitions/NoDescriptionAllOf" },
    "emptyconstraint": { "$ref": "#/definitions/EmptyConstraintItemAllOf" },
    "conflictingformat": { "$ref": "#/definitions/ConflictingFormatAllOf" }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  allof_root_model_constraints.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Any, Dict, List, Optional

from pydantic import BaseModel, EmailStr, Field, conint, constr


class StringDatatype(BaseModel):
    __root__: constr(regex=r'^\S(.*\S)?$') = Field(
        ..., description='A base string type.'
    )


class ConstrainedStringDatatype(BaseModel):
    __root__: constr(regex=r'(?=^\S(.*\S)?$)(?=^[A-Z].*)', min_length=1) = Field(
        ..., description='A constrained string.'
    )


class IntegerDatatype(BaseModel):
    __root__: int = Field(..., description='A whole number.')


class NonNegativeIntegerDatatype(BaseModel):
    __root__: conint(ge=0) = Field(..., description='Non-negative integer.')


class BoundedIntegerDatatype(BaseModel):
    __root__: conint(ge=0, le=100) = Field(
        ..., description='Integer between 0 and 100.'
    )


class EmailDatatype(BaseModel):
    __root__: EmailStr = Field(..., description='Email with format.')


class FormattedStringDatatype(BaseModel):
    __root__: EmailStr = Field(..., description='A string with email format.')


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


class ObjectWithAllOf(ObjectBase):
    name: Optional[str] = None


class MultiRefAllOf(BaseModel):
    pass


class NoConstraintAllOf(BaseModel):
    pass


class IncompatibleTypeAllOf(BaseModel):
    pass


class ConstraintWithProperties(BaseModel):
    extra: Optional[str] = None


class ConstraintWithItems(BaseModel):
    pass


class NumberIntegerCompatible(BaseModel):
    __root__: conint(ge=0) = Field(
        ..., description='Number and integer are compatible.'
    )


class RefWithSchemaKeywords(BaseModel):
    __root__: constr(regex=r'^\S(.*\S)?$', min_length=5, max_length=100) = Field(
        ..., description='Ref with additional schema keywords.'
    )


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


class RefToArrayAllOf(BaseModel):
    pass


class ObjectNoPropsDatatype(BaseModel):
    pass


class RefToObjectNoPropsAllOf(ObjectNoPropsDatatype):
    pass


class PatternPropsDatatype(BaseModel):
    __root__: Dict[constr(regex=r'^S_'), str]


class RefToPatternPropsAllOf(BaseModel):
    pass


class NestedAllOfDatatype(BaseModel):
    pass


class RefToNestedAllOfAllOf(NestedAllOfDatatype):
    pass


class ConstraintsOnlyDatatype(BaseModel):
    __root__: Any = Field(..., description='Constraints only, no type.')


class RefToConstraintsOnlyAllOf(BaseModel):
    __root__: Any = Field(..., description='Ref to constraints-only schema.')


class NoDescriptionAllOf(BaseModel):
    __root__: constr(regex=r'^\S(.*\S)?$', min_length=5) = Field(
        ..., description='A base string type.'
    )


class EmptyConstraintItemAllOf(BaseModel):
    __root__: constr(regex=r'^\S(.*\S)?$', max_length=50) = Field(
        ..., description='AllOf with empty constraint item.'
    )


class ConflictingFormatAllOf(BaseModel):
    pass


class Model(BaseModel):
    name: Optional[ConstrainedStringDatatype] = None
    count: Optional[NonNegativeIntegerDatatype] = None
    percentage: Optional[BoundedIntegerDatatype] = None
    email: Optional[EmailDatatype] = None
    obj: Optional[ObjectWithAllOf] = None
    multi: Optional[MultiRefAllOf] = None
    noconstraint: Optional[NoConstraintAllOf] = None
    incompatible: Optional[IncompatibleTypeAllOf] = None
    withprops: Optional[ConstraintWithProperties] = None
    withitems: Optional[ConstraintWithItems] = None
    numint: Optional[NumberIntegerCompatible] = None
    refwithkw: Optional[RefWithSchemaKeywords] = None
    refarr: Optional[RefToArrayAllOf] = None
    refobjnoprops: Optional[RefToObjectNoPropsAllOf] = None
    refpatternprops: Optional[RefToPatternPropsAllOf] = None
    refnestedallof: Optional[RefToNestedAllOfAllOf] = None
    refconstraintsonly: Optional[RefToConstraintsOnlyAllOf] = None
    nodescription: Optional[NoDescriptionAllOf] = None
    emptyconstraint: Optional[EmptyConstraintItemAllOf] = None
    conflictingformat: Optional[ConflictingFormatAllOf] = None
# generated by datamodel-codegen:
#   filename:  allof_root_model_constraints.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Any, Dict, List, Optional

from pydantic import BaseModel, EmailStr, Field, conint, constr


class StringDatatype(BaseModel):
    __root__: constr(regex=r'^\S(.*\S)?$') = Field(
        ..., description='A base string type.'
    )


class ConstrainedStringDatatype(BaseModel):
    __root__: constr(regex=r'^[A-Z].*', min_length=1) = Field(
        ..., description='A constrained string.'
    )


class IntegerDatatype(BaseModel):
    __root__: int = Field(..., description='A whole number.')


class NonNegativeIntegerDatatype(BaseModel):
    __root__: conint(ge=0) = Field(..., description='Non-negative integer.')


class BoundedIntegerDatatype(BaseModel):
    __root__: conint(ge=0, le=100) = Field(
        ..., description='Integer between 0 and 100.'
    )


class EmailDatatype(BaseModel):
    __root__: EmailStr = Field(..., description='Email with format.')


class FormattedStringDatatype(BaseModel):
    __root__: EmailStr = Field(..., description='A string with email format.')


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


class ObjectWithAllOf(ObjectBase):
    name: Optional[str] = None


class MultiRefAllOf(BaseModel):
    pass


class NoConstraintAllOf(BaseModel):
    pass


class IncompatibleTypeAllOf(BaseModel):
    pass


class ConstraintWithProperties(BaseModel):
    extra: Optional[str] = None


class ConstraintWithItems(BaseModel):
    pass


class NumberIntegerCompatible(BaseModel):
    __root__: conint(ge=0) = Field(
        ..., description='Number and integer are compatible.'
    )


class RefWithSchemaKeywords(BaseModel):
    __root__: constr(regex=r'^\S(.*\S)?$', min_length=5, max_length=100) = Field(
        ..., description='Ref with additional schema keywords.'
    )


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


class RefToArrayAllOf(BaseModel):
    pass


class ObjectNoPropsDatatype(BaseModel):
    pass


class RefToObjectNoPropsAllOf(ObjectNoPropsDatatype):
    pass


class PatternPropsDatatype(BaseModel):
    __root__: Dict[constr(regex=r'^S_'), str]


class RefToPatternPropsAllOf(BaseModel):
    pass


class NestedAllOfDatatype(BaseModel):
    pass


class RefToNestedAllOfAllOf(NestedAllOfDatatype):
    pass


class ConstraintsOnlyDatatype(BaseModel):
    __root__: Any = Field(..., description='Constraints only, no type.')


class RefToConstraintsOnlyAllOf(BaseModel):
    __root__: Any = Field(..., description='Ref to constraints-only schema.')


class NoDescriptionAllOf(BaseModel):
    __root__: constr(regex=r'^\S(.*\S)?$', min_length=5) = Field(
        ..., description='A base string type.'
    )


class EmptyConstraintItemAllOf(BaseModel):
    __root__: constr(regex=r'^\S(.*\S)?$', max_length=50) = Field(
        ..., description='AllOf with empty constraint item.'
    )


class ConflictingFormatAllOf(BaseModel):
    pass


class Model(BaseModel):
    name: Optional[ConstrainedStringDatatype] = None
    count: Optional[NonNegativeIntegerDatatype] = None
    percentage: Optional[BoundedIntegerDatatype] = None
    email: Optional[EmailDatatype] = None
    obj: Optional[ObjectWithAllOf] = None
    multi: Optional[MultiRefAllOf] = None
    noconstraint: Optional[NoConstraintAllOf] = None
    incompatible: Optional[IncompatibleTypeAllOf] = None
    withprops: Optional[ConstraintWithProperties] = None
    withitems: Optional[ConstraintWithItems] = None
    numint: Optional[NumberIntegerCompatible] = None
    refwithkw: Optional[RefWithSchemaKeywords] = None
    refarr: Optional[RefToArrayAllOf] = None
    refobjnoprops: Optional[RefToObjectNoPropsAllOf] = None
    refpatternprops: Optional[RefToPatternPropsAllOf] = None
    refnestedallof: Optional[RefToNestedAllOfAllOf] = None
    refconstraintsonly: Optional[RefToConstraintsOnlyAllOf] = None
    nodescription: Optional[NoDescriptionAllOf] = None
    emptyconstraint: Optional[EmptyConstraintItemAllOf] = None
    conflictingformat: Optional[ConflictingFormatAllOf] = None

--disable-future-imports

Prevent automatic addition of future imports in generated code.

The --disable-future-imports option stops the generator from adding 'from future import annotations' to the output. This is useful when you need compatibility with tools or environments that don't support postponed evaluation of annotations (PEP 563).

Usage

datamodel-codegen --input schema.json --disable-future-imports --target-python-version 3.10 # (1)!
  1. --disable-future-imports - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "DescriptionType",
  "type": "object",
  "properties": {
    "metadata": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/Metadata"
      }
    }
  },
  "definitions": {
    "Metadata": {
      "title": "Metadata",
      "type": "object",
      "properties": {
        "title": {
          "type": "string"
        }
      }
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  keep_model_order_field_references.json
#   timestamp: 2019-07-26T00:00:00+00:00

from typing import List, Optional

from pydantic import BaseModel


class Metadata(BaseModel):
    title: Optional[str] = None


class DescriptionType(BaseModel):
    metadata: Optional[List[Metadata]] = None

--enum-field-as-literal

Convert all enum fields to Literal types instead of Enum classes.

The --enum-field-as-literal all flag converts all enum types to Literal type annotations. This is useful when you want string literal types instead of Enum classes for all enumerations.

Usage

datamodel-codegen --input schema.json --enum-field-as-literal all # (1)!
  1. --enum-field-as-literal - the option documented here
Input Schema
"Employee shift status"
enum EmployeeShiftStatus {
  "not on shift"
  NOT_ON_SHIFT
  "on shift"
  ON_SHIFT
}

enum Color {
  RED
  GREEN
  BLUE
}

enum EnumWithOneField {
    FIELD
}
Output
# generated by datamodel-codegen:
#   filename:  enums.graphql
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Literal

from pydantic import BaseModel
from typing_extensions import TypeAlias

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


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


class Color(BaseModel):
    __root__: Literal['BLUE', 'GREEN', 'RED']


class EmployeeShiftStatus(BaseModel):
    """
    Employee shift status
    """

    __root__: Literal['NOT_ON_SHIFT', 'ON_SHIFT']


class EnumWithOneField(BaseModel):
    __root__: Literal['FIELD']
# generated by datamodel-codegen:
#   filename:  enums.graphql
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from enum import Enum

from typing_extensions import TypeAlias

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


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


class Color(Enum):
    BLUE = 'BLUE'
    GREEN = 'GREEN'
    RED = 'RED'


class EmployeeShiftStatus(Enum):
    """
    Employee shift status
    """

    NOT_ON_SHIFT = 'NOT_ON_SHIFT'
    ON_SHIFT = 'ON_SHIFT'


class EnumWithOneField(Enum):
    FIELD = 'FIELD'

--no-use-specialized-enum

Disable specialized Enum classes for Python 3.11+ code generation.

The --no-use-specialized-enum flag prevents the generator from using specialized Enum classes (StrEnum, IntEnum) when generating code for Python 3.11+, falling back to standard Enum classes instead.

Related: --no-use-specialized-enum, --target-python-version

Usage

datamodel-codegen --input schema.json --target-python-version 3.11 --no-use-specialized-enum # (1)!
  1. --no-use-specialized-enum - the option documented here
Input Schema
"Employee shift status"
enum EmployeeShiftStatus {
  "not on shift"
  NOT_ON_SHIFT
  "on shift"
  ON_SHIFT
}

enum Color {
  RED
  GREEN
  BLUE
}

enum EnumWithOneField {
    FIELD
}
Output
# generated by datamodel-codegen:
#   filename:  enums.graphql
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from enum import Enum
from typing import TypeAlias

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


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


class Color(Enum):
    BLUE = 'BLUE'
    GREEN = 'GREEN'
    RED = 'RED'


class EmployeeShiftStatus(Enum):
    """
    Employee shift status
    """

    NOT_ON_SHIFT = 'NOT_ON_SHIFT'
    ON_SHIFT = 'ON_SHIFT'


class EnumWithOneField(Enum):
    FIELD = 'FIELD'

--output-datetime-class

Specify datetime class type for date-time schema fields.

The --output-datetime-class flag controls which datetime type to use for fields with date-time format. Options include 'AwareDatetime' for timezone-aware datetimes or 'datetime' for standard Python datetime objects.

Usage

datamodel-codegen --input schema.json --output-datetime-class AwareDatetime # (1)!
  1. --output-datetime-class - the option documented here
Input Schema
openapi: "3.0.0"
components:
  schemas:
    InventoryItem:
      required:
#      - id
#      - name
      - releaseDate
      type: object
      properties:
#        id:
#          type: string
#          format: uuid
#          example: d290f1ee-6c54-4b01-90e6-d701748f0851
#        name:
#          type: string
#          example: Widget Adapter
        releaseDate:
          type: string
          format: date-time
          example: 2016-08-29T09:12:33.001Z
Output
# generated by datamodel-codegen:
#   filename:  datetime.yaml
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from pydantic import AwareDatetime, BaseModel, Field


class InventoryItem(BaseModel):
    releaseDate: AwareDatetime = Field(..., examples=['2016-08-29T09:12:33.001Z'])

--strict-types

Enable strict type validation for specified Python types.

The --strict-types option enforces stricter type checking by preventing implicit type coercion for the specified types (str, bytes, int, float, bool). This generates StrictStr, StrictBytes, StrictInt, StrictFloat, and StrictBool types in Pydantic models, ensuring values match exactly without automatic conversion.

Usage

datamodel-codegen --input schema.json --strict-types str bytes int float bool # (1)!
  1. --strict-types - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "User",
  "type": "object",
  "properties": {
        "name": {
          "type": "string",
          "example": "ken"
        },
        "age": {
          "type": "integer"
        },
        "salary": {
          "type": "integer",
          "minimum": 0
        },
        "debt" : {
          "type": "integer",
          "maximum": 0
        },
        "loan" : {
          "type": "number",
          "maximum": 0
        },
        "tel": {
          "type": "string",
          "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
        },
        "height": {
          "type": "number",
          "minimum": 0
        },
        "weight": {
          "type": "number",
          "minimum": 0
        },
        "score": {
          "type": "number",
          "minimum": 1e-08
        },
        "active": {
          "type": "boolean"
        },
        "photo": {
          "type": "string",
          "format": "binary",
          "minLength": 100
        }
      }
}
Output
# generated by datamodel-codegen:
#   filename:  strict_types.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import (
    BaseModel,
    Field,
    StrictBool,
    StrictBytes,
    StrictInt,
    StrictStr,
    confloat,
    conint,
    constr,
)


class User(BaseModel):
    name: Optional[StrictStr] = Field(None, example='ken')
    age: Optional[StrictInt] = None
    salary: Optional[conint(ge=0, strict=True)] = None
    debt: Optional[conint(le=0, strict=True)] = None
    loan: Optional[confloat(le=0.0, strict=True)] = None
    tel: Optional[
        constr(regex=r'^(\([0-9]{3}\))?[0-9]{3}-[0-9]{4}$', strict=True)
    ] = None
    height: Optional[confloat(ge=0.0, strict=True)] = None
    weight: Optional[confloat(ge=0.0, strict=True)] = None
    score: Optional[confloat(ge=1e-08, strict=True)] = None
    active: Optional[StrictBool] = None
    photo: Optional[StrictBytes] = None

--type-mappings

Override default type mappings for schema formats.

The --type-mappings flag configures the code generation behavior.

Usage

datamodel-codegen --input schema.json --output-model-type pydantic_v2.BaseModel --type-mappings binary=string # (1)!
  1. --type-mappings - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "BlobModel",
  "type": "object",
  "properties": {
    "content": {
      "type": "string",
      "format": "binary",
      "description": "Binary content that should be mapped to string"
    },
    "data": {
      "type": "string",
      "format": "byte",
      "description": "Base64 encoded data"
    },
    "name": {
      "type": "string",
      "description": "Regular string field"
    }
  },
  "required": ["content", "data", "name"]
}
Output
# generated by datamodel-codegen:
#   filename:  type_mappings.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from pydantic import Base64Str, BaseModel, Field


class BlobModel(BaseModel):
    content: str = Field(
        ..., description='Binary content that should be mapped to string'
    )
    data: Base64Str = Field(..., description='Base64 encoded data')
    name: str = Field(..., description='Regular string field')

--use-annotated

Test GraphQL annotated types with standard collections and union operator.

Related: --use-standard-collections

Usage

datamodel-codegen --input schema.json --output-model-type pydantic_v2.BaseModel --use-annotated --use-standard-collections --use-union-operator # (1)!
  1. --use-annotated - the option documented here
Input Schema
type A {
    field: String!
    optionalField: String
    listField: [String!]!
    listOptionalField: [String]!
    optionalListField: [String!]
    optionalListOptionalField: [String]
    listListField:[[String!]!]!
}
Output
# generated by datamodel-codegen:
#   filename:  annotated.graphql
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Annotated, Literal

from pydantic import BaseModel, Field
from typing_extensions import TypeAliasType

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


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):
    field: String
    listField: list[String]
    listListField: list[list[String]]
    listOptionalField: list[String | None]
    optionalField: String | None = None
    optionalListField: list[String] | None = None
    optionalListOptionalField: list[String | None] | None = None
    typename__: Annotated[Literal['A'] | None, Field(alias='__typename')] = 'A'

--use-decimal-for-multiple-of

Generate Decimal types for fields with multipleOf constraint.

The --use-decimal-for-multiple-of flag generates condecimal or Decimal types for numeric fields that have a multipleOf constraint. This ensures precise decimal arithmetic when validating values against the constraint.

Usage

datamodel-codegen --input schema.json --use-decimal-for-multiple-of # (1)!
  1. --use-decimal-for-multiple-of - the option documented here
Input Schema
{
  "type": "object",
  "properties": {
    "price": {
      "type": "number",
      "multipleOf": 0.01,
      "minimum": 0,
      "maximum": 99999.99
    },
    "quantity": {
      "type": "number",
      "multipleOf": 0.1
    },
    "rate": {
      "type": "number",
      "multipleOf": 0.001,
      "exclusiveMinimum": 0,
      "exclusiveMaximum": 1
    },
    "simple_float": {
      "type": "number",
      "minimum": 0,
      "maximum": 100
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  use_decimal_for_multiple_of.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel, condecimal, confloat


class Model(BaseModel):
    price: Optional[condecimal(ge=0, le=99999.99, multiple_of=0.01)] = None
    quantity: Optional[condecimal(multiple_of=0.1)] = None
    rate: Optional[condecimal(multiple_of=0.001, lt=1.0, gt=0.0)] = None
    simple_float: Optional[confloat(ge=0.0, le=100.0)] = None

--use-generic-container-types

Use typing.Dict/List instead of dict/list for container types.

The --use-generic-container-types flag generates typing module generic containers (Dict, List, etc.) instead of built-in types. This is useful for Python 3.8 compatibility or when explicit typing imports are preferred.

Related: --use-standard-collections

Usage

datamodel-codegen --input schema.json --use-generic-container-types # (1)!
  1. --use-generic-container-types - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "test.json",
  "description": "test",
  "type": "object",
  "required": [
    "test_id",
    "test_ip",
    "result",
    "nested_object_result",
    "nested_enum_result"
  ],
  "properties": {
    "test_id": {
      "type": "string",
      "description": "test ID"
    },
    "test_ip": {
      "type": "string",
      "description": "test IP"
    },
    "result": {
      "type": "object",
      "additionalProperties": {
        "type": "integer"
      }
    },
    "nested_object_result": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "properties": {
          "status":{
            "type": "integer"
          }
        },
        "required": ["status"]
      }
    },
    "nested_enum_result": {
      "type": "object",
      "additionalProperties": {
        "enum": ["red", "green"]
      }
    },
    "all_of_result" :{
      "type" : "object",
      "additionalProperties" :
      {
        "allOf" : [
          { "$ref" : "#/definitions/User" },
          { "type" : "object",
            "properties": {
              "description": {"type" : "string" }
            }
          }
        ]
      }
    },
    "one_of_result" :{
      "type" : "object",
      "additionalProperties" :
      {
        "oneOf" : [
          { "$ref" : "#/definitions/User" },
          { "type" : "object",
            "properties": {
              "description": {"type" : "string" }
            }
          }
        ]
      }
    },
    "any_of_result" :{
      "type" : "object",
      "additionalProperties" :
      {
        "anyOf" : [
          { "$ref" : "#/definitions/User" },
          { "type" : "object",
            "properties": {
              "description": {"type" : "string" }
            }
          }
        ]
      }
    },
    "all_of_with_unknown_object" :{
      "type" : "object",
      "additionalProperties" :
      {
        "allOf" : [
          { "$ref" : "#/definitions/User" },
          { "description": "TODO" }
        ]
      }
    },
    "objectRef": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/definitions/User"
      }
    },
    "deepNestedObjectRef": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "additionalProperties": {
          "type": "object",
          "additionalProperties": {
             "$ref": "#/definitions/User"
          }
        }
      }
    }
  },
  "definitions": {
    "User": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        }
      }
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  root_model_with_additional_properties.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from enum import Enum
from typing import Mapping, Optional, Union

from pydantic import BaseModel, Field


class NestedObjectResult(BaseModel):
    status: int


class NestedEnumResult(Enum):
    red = 'red'
    green = 'green'


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


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


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


class AllOfResult(User):
    description: Optional[str] = None


class Model(BaseModel):
    test_id: str = Field(..., description='test ID')
    test_ip: str = Field(..., description='test IP')
    result: Mapping[str, int]
    nested_object_result: Mapping[str, NestedObjectResult]
    nested_enum_result: Mapping[str, NestedEnumResult]
    all_of_result: Optional[Mapping[str, AllOfResult]] = None
    one_of_result: Optional[Mapping[str, Union[User, OneOfResult]]] = None
    any_of_result: Optional[Mapping[str, Union[User, AnyOfResult]]] = None
    all_of_with_unknown_object: Optional[Mapping[str, User]] = None
    objectRef: Optional[Mapping[str, User]] = None
    deepNestedObjectRef: Optional[Mapping[str, Mapping[str, Mapping[str, User]]]] = None

--use-non-positive-negative-number-constrained-types

Use NonPositive/NonNegative types for number constraints.

The --use-non-positive-negative-number-constrained-types flag generates Pydantic's NonPositiveInt, NonNegativeInt, NonPositiveFloat, and NonNegativeFloat types for fields with minimum: 0 or maximum: 0 constraints, instead of using conint/confloat with ge/le parameters.

Usage

datamodel-codegen --input schema.json --use-non-positive-negative-number-constrained-types # (1)!
  1. --use-non-positive-negative-number-constrained-types - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "NumberConstraints",
  "type": "object",
  "properties": {
    "non_negative_count": {
      "type": "integer",
      "minimum": 0,
      "description": "A count that cannot be negative"
    },
    "non_positive_balance": {
      "type": "integer",
      "maximum": 0,
      "description": "A balance that cannot be positive"
    },
    "non_negative_amount": {
      "type": "number",
      "minimum": 0,
      "description": "An amount that cannot be negative"
    },
    "non_positive_score": {
      "type": "number",
      "maximum": 0,
      "description": "A score that cannot be positive"
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  use_non_positive_negative.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import (
    BaseModel,
    Field,
    NonNegativeFloat,
    NonNegativeInt,
    NonPositiveFloat,
    NonPositiveInt,
)


class NumberConstraints(BaseModel):
    non_negative_count: Optional[NonNegativeInt] = Field(
        None, description='A count that cannot be negative'
    )
    non_positive_balance: Optional[NonPositiveInt] = Field(
        None, description='A balance that cannot be positive'
    )
    non_negative_amount: Optional[NonNegativeFloat] = Field(
        None, description='An amount that cannot be negative'
    )
    non_positive_score: Optional[NonPositiveFloat] = Field(
        None, description='A score that cannot be positive'
    )

--use-pendulum

Use pendulum types for date/time fields instead of datetime module.

The --use-pendulum flag generates pendulum library types (DateTime, Date, Time, Duration) instead of standard datetime types. This is useful when working with the pendulum library for enhanced timezone and date handling.

Usage

datamodel-codegen --input schema.json --use-pendulum # (1)!
  1. --use-pendulum - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Event",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "created_at": {
      "type": "string",
      "format": "date-time"
    },
    "event_date": {
      "type": "string",
      "format": "date"
    },
    "duration": {
      "type": "string",
      "format": "duration"
    }
  },
  "required": ["name", "created_at"]
}
Output
# generated by datamodel-codegen:
#   filename:  use_pendulum.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pendulum import Date, DateTime, Duration
from pydantic import BaseModel


class Event(BaseModel):
    name: str
    created_at: DateTime
    event_date: Optional[Date] = None
    duration: Optional[Duration] = None

--use-standard-collections

Use built-in dict/list instead of typing.Dict/List.

The --use-standard-collections flag generates built-in container types (dict, list) instead of typing module equivalents. This produces cleaner code for Python 3.9+ where built-in types support subscripting.

Related: --use-generic-container-types

Usage

datamodel-codegen --input schema.json --use-standard-collections # (1)!
  1. --use-standard-collections - the option documented here
Input Schema
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "test.json",
  "description": "test",
  "type": "object",
  "required": [
    "test_id",
    "test_ip",
    "result",
    "nested_object_result",
    "nested_enum_result"
  ],
  "properties": {
    "test_id": {
      "type": "string",
      "description": "test ID"
    },
    "test_ip": {
      "type": "string",
      "description": "test IP"
    },
    "result": {
      "type": "object",
      "additionalProperties": {
        "type": "integer"
      }
    },
    "nested_object_result": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "properties": {
          "status":{
            "type": "integer"
          }
        },
        "required": ["status"]
      }
    },
    "nested_enum_result": {
      "type": "object",
      "additionalProperties": {
        "enum": ["red", "green"]
      }
    },
    "all_of_result" :{
      "type" : "object",
      "additionalProperties" :
      {
        "allOf" : [
          { "$ref" : "#/definitions/User" },
          { "type" : "object",
            "properties": {
              "description": {"type" : "string" }
            }
          }
        ]
      }
    },
    "one_of_result" :{
      "type" : "object",
      "additionalProperties" :
      {
        "oneOf" : [
          { "$ref" : "#/definitions/User" },
          { "type" : "object",
            "properties": {
              "description": {"type" : "string" }
            }
          }
        ]
      }
    },
    "any_of_result" :{
      "type" : "object",
      "additionalProperties" :
      {
        "anyOf" : [
          { "$ref" : "#/definitions/User" },
          { "type" : "object",
            "properties": {
              "description": {"type" : "string" }
            }
          }
        ]
      }
    },
    "all_of_with_unknown_object" :{
      "type" : "object",
      "additionalProperties" :
      {
        "allOf" : [
          { "$ref" : "#/definitions/User" },
          { "description": "TODO" }
        ]
      }
    },
    "objectRef": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/definitions/User"
      }
    },
    "deepNestedObjectRef": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "additionalProperties": {
          "type": "object",
          "additionalProperties": {
             "$ref": "#/definitions/User"
          }
        }
      }
    }
  },
  "definitions": {
    "User": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        }
      }
    }
  }
}
Output
# generated by datamodel-codegen:
#   filename:  root_model_with_additional_properties.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from enum import Enum
from typing import Optional, Union

from pydantic import BaseModel, Field


class NestedObjectResult(BaseModel):
    status: int


class NestedEnumResult(Enum):
    red = 'red'
    green = 'green'


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


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


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


class AllOfResult(User):
    description: Optional[str] = None


class Model(BaseModel):
    test_id: str = Field(..., description='test ID')
    test_ip: str = Field(..., description='test IP')
    result: dict[str, int]
    nested_object_result: dict[str, NestedObjectResult]
    nested_enum_result: dict[str, NestedEnumResult]
    all_of_result: Optional[dict[str, AllOfResult]] = None
    one_of_result: Optional[dict[str, Union[User, OneOfResult]]] = None
    any_of_result: Optional[dict[str, Union[User, AnyOfResult]]] = None
    all_of_with_unknown_object: Optional[dict[str, User]] = None
    objectRef: Optional[dict[str, User]] = None
    deepNestedObjectRef: Optional[dict[str, dict[str, dict[str, User]]]] = None

--use-type-alias

Use TypeAlias instead of root models for type definitions (experimental).

The --use-type-alias flag generates TypeAlias declarations instead of root model classes for certain type definitions. For Python 3.9-3.11, it generates TypeAliasType, and for Python 3.12+, it uses the 'type' statement syntax. This feature is experimental.

Related: --target-python-version

Usage

datamodel-codegen --input schema.json --use-type-alias # (1)!
  1. --use-type-alias - the option documented here
Input Schema
scalar SimpleString

type Person {
  name: String!
  age: Int!
}

type Pet {
  name: String!
  type: String!
}

union UnionType = Person | Pet

type ModelWithTypeAliasField {
  simple_field: SimpleString
  union_field: UnionType
  string_field: String
}
Output
# generated by datamodel-codegen:
#   filename:  type_alias.graphql
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Literal, Optional, Union

from pydantic import BaseModel, Field
from typing_extensions import TypeAlias

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


Int: TypeAlias = int
"""
The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.
"""


SimpleString: TypeAlias = str


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


class Person(BaseModel):
    age: Int
    name: String
    typename__: Optional[Literal['Person']] = Field('Person', alias='__typename')


class Pet(BaseModel):
    name: String
    type: String
    typename__: Optional[Literal['Pet']] = Field('Pet', alias='__typename')


UnionType: TypeAlias = Union[
    'Person',
    'Pet',
]


class ModelWithTypeAliasField(BaseModel):
    simple_field: Optional[SimpleString] = None
    string_field: Optional[String] = None
    union_field: Optional[UnionType] = None
    typename__: Optional[Literal['ModelWithTypeAliasField']] = Field(
        'ModelWithTypeAliasField', alias='__typename'
    )

--use-union-operator

Test GraphQL annotated types with standard collections and union operator.

Related: --use-standard-collections

Usage

datamodel-codegen --input schema.json --output-model-type pydantic_v2.BaseModel --use-annotated --use-standard-collections --use-union-operator # (1)!
  1. --use-union-operator - the option documented here
Input Schema
type A {
    field: String!
    optionalField: String
    listField: [String!]!
    listOptionalField: [String]!
    optionalListField: [String!]
    optionalListOptionalField: [String]
    listListField:[[String!]!]!
}
Output
# generated by datamodel-codegen:
#   filename:  annotated.graphql
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Annotated, Literal

from pydantic import BaseModel, Field
from typing_extensions import TypeAliasType

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


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):
    field: String
    listField: list[String]
    listListField: list[list[String]]
    listOptionalField: list[String | None]
    optionalField: String | None = None
    optionalListField: list[String] | None = None
    optionalListOptionalField: list[String | None] | None = None
    typename__: Annotated[Literal['A'] | None, Field(alias='__typename')] = 'A'

--use-unique-items-as-set

Generate set types for arrays with uniqueItems constraint.

The --use-unique-items-as-set flag generates Python set types instead of list types for JSON Schema arrays that have the uniqueItems constraint set to true, enforcing uniqueness at the type level.

Usage

datamodel-codegen --input schema.json --use-unique-items-as-set --field-constraints # (1)!
  1. --use-unique-items-as-set - the option documented here
Input Schema
openapi: "3.0.0"
info:
  version: 1.0.0
  title: Swagger Petstore
  license:
    name: MIT
servers:
  - url: http://petstore.swagger.io/v1
paths:
  /pets:
    get:
      summary: List all pets
      operationId: listPets
      tags:
        - pets
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
            format: int32
            minimum: 0
            maximum: 100
      responses:
        '200':
          description: A paged array of pets
          headers:
            x-next:
              description: A link to the next page of responses
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pets"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
                x-amazon-apigateway-integration:
                  uri:
                    Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
                  passthroughBehavior: when_no_templates
                  httpMethod: POST
                  type: aws_proxy
    post:
      summary: Create a pet
      operationId: createPets
      tags:
        - pets
      responses:
        '201':
          description: Null response
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
                x-amazon-apigateway-integration:
                  uri:
                    Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
                  passthroughBehavior: when_no_templates
                  httpMethod: POST
                  type: aws_proxy
  /pets/{petId}:
    get:
      summary: Info for a specific pet
      operationId: showPetById
      tags:
        - pets
      parameters:
        - name: petId
          in: path
          required: true
          description: The id of the pet to retrieve
          schema:
            type: string
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pets"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    x-amazon-apigateway-integration:
      uri:
        Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
      passthroughBehavior: when_no_templates
      httpMethod: POST
      type: aws_proxy
components:
  schemas:
    Pet:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
          minimum: 0
          maximum: 9223372036854775807
        name:
          type: string
          maxLength: 256
        tag:
          type: string
          maxLength: 64
    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"
      maxItems: 10
      minItems: 1
      uniqueItems: true
    UID:
      type: integer
      minimum: 0
    Users:
      type: array
      items:
        required:
          - id
          - name
          - uid
        properties:
          id:
            type: integer
            format: int64
            minimum: 0
          name:
            type: string
            maxLength: 256
          tag:
            type: string
            maxLength: 64
          uid:
            $ref: '#/components/schemas/UID'
          phones:
            type: array
            items:
              type: string
              minLength: 3
            maxItems: 10
          fax:
            type: array
            items:
              type: string
              minLength: 3
          height:
            type:
              - integer
              - number
            minimum: 1
            maximum: 300
          weight:
            type:
              - number
              - integer
            minimum: 1.0
            maximum: 1000.0
          age:
            type: integer
            minimum: 0.0
            maximum: 200.0
            exclusiveMinimum: true
          rating:
            type: number
            minimum: 0
            exclusiveMinimum: True
            maximum: 5

    Id:
      type: string
    Rules:
      type: array
      items:
        type: string
    Error:
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
    apis:
      type: array
      items:
        type: object
        properties:
          apiKey:
            type: string
            description: To be used as a dataset parameter value
          apiVersionNumber:
            type: string
            description: To be used as a version parameter value
          apiUrl:
            type: string
            format: uri
            minLength: 1
            description: "The URL describing the dataset's fields"
          apiDocumentationUrl:
            type: string
            format: uri
            description: A URL to the API console for each API
    Event:
      type: object
      properties:
        name:
          type: string
    Result:
        type: object
        properties:
          event:
            $ref: '#/components/schemas/Event'
Output
# generated by datamodel-codegen:
#   filename:  api_constrained.yaml
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import List, Optional, Set, Union

from pydantic import AnyUrl, BaseModel, Field


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


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


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


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


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


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


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


class Id(BaseModel):
    __root__: str


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


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


class Api(BaseModel):
    apiKey: Optional[str] = Field(
        None, description='To be used as a dataset parameter value'
    )
    apiVersionNumber: Optional[str] = Field(
        None, description='To be used as a version parameter value'
    )
    apiUrl: Optional[AnyUrl] = Field(
        None, description="The URL describing the dataset's fields"
    )
    apiDocumentationUrl: Optional[AnyUrl] = Field(
        None, description='A URL to the API console for each API'
    )


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


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


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