🎨 Template Customization¶
📋 Options¶
| Option | Description |
|---|---|
--additional-imports |
Add custom imports to generated output files. |
--class-decorators |
Add custom decorators to generated model classes. |
--custom-file-header |
Add custom header text to the generated file. |
--custom-file-header-path |
Add custom header content from file to generated code. |
--custom-formatters |
Apply custom Python code formatters to generated output. |
--custom-formatters-kwargs |
Pass custom arguments to custom formatters via inline JSON o... |
--custom-template-dir |
Use custom Jinja2 templates for model generation. |
--disable-appending-item-suffix |
Disable appending 'Item' suffix to array item types. |
--disable-timestamp |
Disable timestamp in generated file header for reproducible ... |
--enable-command-header |
Include command-line options in file header for reproducibil... |
--enable-generated-header-marker |
Include the @generated marker in file header for generated-c... |
--enable-version-header |
Include tool version information in file header. |
--extra-template-data |
Pass custom template variables via inline JSON or a JSON fil... |
--formatters |
Specify code formatters to apply to generated output. |
--no-treat-dot-as-module |
Keep dots in schema names as underscores for flat output. |
--no-use-type-checking-imports |
Keep generated model imports available at runtime when using... |
--treat-dot-as-module |
Treat dots in schema names as module separators. |
--use-double-quotes |
Use double quotes for string literals in generated code. |
--use-exact-imports |
Import exact types instead of modules. |
--use-type-checking-imports |
Allow Ruff to move typing-only imports into TYPE_CHECKING bl... |
--validators |
Add custom field validators to generated Pydantic v2 models. |
--wrap-string-literal |
Wrap long string literals across multiple lines. |
--additional-imports¶
Add custom imports to generated output files.
The --additional-imports flag allows you to specify custom imports as a
comma-delimited list that will be added to the generated output file. This
is useful when using custom types defined in external modules (e.g.,
"datetime.datetime,datetime.date,mymodule.myclass.MyCustomPythonClass").
See also: Custom Class Decorators
Usage
datamodel-codegen --input schema.json --additional-imports datetime.datetime,datetime.date,mymodule.myclass.MyCustomPythonClass # (1)!
-
--additional-imports- the option documented here
Examples
Input Schema:
scalar Date
"DateTime (ISO8601, example: 2020-01-01T10:11:12+00:00)"
scalar DateTime
scalar MyCustomClass
type A {
a: Date!
b: DateTime!
c: MyCustomClass!
}
Output:
# generated by datamodel-codegen:
# filename: additional-imports.graphql
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from datetime import date, datetime
from typing import Literal
from mymodule.myclass import MyCustomPythonClass
from pydantic import BaseModel, Field
from typing_extensions import TypeAliasType
Boolean = TypeAliasType("Boolean", bool)
"""
The `Boolean` scalar type represents `true` or `false`.
"""
Date = TypeAliasType("Date", date)
DateTime = TypeAliasType("DateTime", datetime)
"""
DateTime (ISO8601, example: 2020-01-01T10:11:12+00:00)
"""
MyCustomClass = TypeAliasType("MyCustomClass", MyCustomPythonClass)
String = TypeAliasType("String", str)
"""
The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
"""
class A(BaseModel):
a: Date
b: DateTime
c: MyCustomClass
typename__: Literal['A'] | None = Field('A', alias='__typename')
--class-decorators¶
Add custom decorators to generated model classes.
The --class-decorators option adds custom decorators to all generated model classes.
This is useful for integrating with serialization libraries like dataclasses_json.
Use with --additional-imports to add the required imports for the decorators.
The @ prefix is optional and will be added automatically if missing.
Related: --additional-imports, --output-model-type
See also: Custom Class Decorators
Usage
datamodel-codegen --input schema.json --output-model-type dataclasses.dataclass --class-decorators @dataclass_json --additional-imports dataclasses_json.dataclass_json # (1)!
-
--class-decorators- the option documented here
Examples
Input Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "User",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer"
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name", "age"]
}
Output:
# generated by datamodel-codegen:
# filename: simple_frozen_test.json
# timestamp: 1985-10-26T08:21:00+00:00
from __future__ import annotations
from dataclasses import dataclass
from dataclasses_json import dataclass_json
@dataclass_json
@dataclass
class User:
name: str
age: int
email: str | None = None
--custom-file-header¶
Add custom header text to the generated file.
The --custom-file-header flag replaces the default "generated by datamodel-codegen"
header with custom text. This is useful for adding copyright notices, license
headers, or other metadata to generated files.
Usage
-
--custom-file-header- the option documented here
Examples
Input Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Person",
"type": "object",
"properties": {
"first-name": {
"type": "string"
},
"last-name": {
"type": "string"
},
"email_address": {
"type": "string"
}
},
"required": ["first-name", "last-name"]
}
Output:
# generated by datamodel-codegen:
# filename: no_alias.json
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from pydantic import BaseModel, Field
class Person(BaseModel):
first_name: str = Field(..., alias='first-name')
last_name: str = Field(..., alias='last-name')
email_address: str | None = None
--custom-file-header-path¶
Add custom header content from file to generated code.
The --custom-file-header-path flag allows you to specify a file containing
custom header content (like copyright notices, linting directives, or module docstrings)
to be inserted at the top of generated Python files.
Usage
-
--custom-file-header-path- 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:
# multiline custom ;
# header ;
# file ;
from __future__ import annotations
from pydantic import AnyUrl, BaseModel, Field, RootModel
class Pet(BaseModel):
id: int
name: str
tag: str | None = None
class Pets(RootModel[list[Pet]]):
root: list[Pet]
class User(BaseModel):
id: int
name: str
tag: str | None = None
class Users(RootModel[list[User]]):
root: list[User]
class Id(RootModel[str]):
root: str
class Rules(RootModel[list[str]]):
root: list[str]
class Error(BaseModel):
code: int
message: str
class Api(BaseModel):
apiKey: str | None = Field(
None, description='To be used as a dataset parameter value'
)
apiVersionNumber: str | None = Field(
None, description='To be used as a version parameter value'
)
apiUrl: AnyUrl | None = Field(
None, description="The URL describing the dataset's fields"
)
apiDocumentationUrl: AnyUrl | None = Field(
None, description='A URL to the API console for each API'
)
class Apis(RootModel[list[Api]]):
root: list[Api]
class Event(BaseModel):
name: str | None = None
class Result(BaseModel):
event: Event | None = None
--custom-formatters¶
Apply custom Python code formatters to generated output.
The --custom-formatters flag allows you to specify custom Python functions
that will be applied to format the generated code. The formatter is specified
as a module path (e.g., "mymodule.formatter_function"). This is useful for
adding custom comments, modifying code structure, or applying project-specific
formatting rules beyond what black/isort provide.
See also: Custom Code Formatters
Usage
datamodel-codegen --input schema.json --custom-formatters tests.data.python.custom_formatters.add_comment # (1)!
-
--custom-formatters- the option documented here
Examples
Input Schema:
Output:
# generated by datamodel-codegen:
# filename: custom-scalar-types.graphql
# timestamp: 2019-07-26T00:00:00+00:00
# a comment
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
from typing_extensions import TypeAliasType
Boolean = TypeAliasType("Boolean", bool)
"""
The `Boolean` scalar type represents `true` or `false`.
"""
ID = TypeAliasType("ID", str)
"""
The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.
"""
Long = TypeAliasType("Long", str)
String = TypeAliasType("String", str)
"""
The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
"""
class A(BaseModel):
duration: Long
id: ID
typename__: Literal['A'] | None = Field('A', alias='__typename')
--custom-formatters-kwargs¶
Pass custom arguments to custom formatters via inline JSON or a JSON file path.
The --custom-formatters-kwargs flag accepts an inline JSON object or a path to a JSON file containing
custom configuration for custom formatters (used with --custom-formatters).
The file should contain a JSON object mapping formatter names to their kwargs.
Note: This option is primarily used with --custom-formatters to pass configuration to user-defined formatter modules.
See also: Custom Code Formatters
Usage
-
--custom-formatters-kwargs- 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:
--custom-template-dir¶
Use custom Jinja2 templates for model generation.
The --custom-template-dir option allows you to specify a directory containing custom Jinja2 templates
to override the default templates used for generating data models. This enables full customization of
the generated code structure and formatting. Use with --extra-template-data to pass additional data
to the templates.
See also: Custom Templates
Usage
datamodel-codegen --input schema.json --custom-template-dir templates --extra-template-data openapi/extra_data.json # (1)!
-
--custom-template-dir- 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:
# generated by datamodel-codegen:
# filename: api.yaml
# timestamp: 1985-10-26T08:21:00+00:00
from __future__ import annotations
from pydantic import AnyUrl, BaseModel, ConfigDict, Field, RootModel
class Pet(BaseModel): # 1 2, 1 2, this is just a pet
model_config = ConfigDict(
arbitrary_types_allowed=True,
coerce_numbers_to_str=True,
)
id: int
name: str
tag: str | None = None
class Pets(RootModel[list[Pet]]):
root: list[Pet]
class User(BaseModel):
id: int
name: str
tag: str | None = None
class Users(RootModel[list[User]]):
root: list[User]
class Id(RootModel[str]):
root: str
class Rules(RootModel[list[str]]):
root: list[str]
class Error(BaseModel):
code: int
message: str
class Api(BaseModel):
apiKey: str | None = Field(
None, description='To be used as a dataset parameter value'
)
apiVersionNumber: str | None = Field(
None, description='To be used as a version parameter value'
)
apiUrl: AnyUrl | None = Field(
None, description="The URL describing the dataset's fields"
)
apiDocumentationUrl: AnyUrl | None = Field(
None, description='A URL to the API console for each API'
)
class Apis(RootModel[list[Api]]):
root: list[Api]
class Event(BaseModel):
name: str | None = None
class Result(BaseModel):
event: Event | None = None
--disable-appending-item-suffix¶
Disable appending 'Item' suffix to array item types.
The --disable-appending-item-suffix flag configures the code generation behavior.
Usage
-
--disable-appending-item-suffix- 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
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 pydantic import AnyUrl, BaseModel, Field, RootModel
class Pet(BaseModel):
id: int = Field(..., ge=0, le=9223372036854775807)
name: str = Field(..., max_length=256)
tag: str | None = Field(None, max_length=64)
class Pets(RootModel[list[Pet]]):
root: list[Pet] = Field(..., max_length=10, min_length=1)
class UID(RootModel[int]):
root: int = Field(..., ge=0)
class Phone(RootModel[str]):
root: str = Field(..., min_length=3)
class Fax(RootModel[str]):
root: str = Field(..., min_length=3)
class User(BaseModel):
id: int = Field(..., ge=0)
name: str = Field(..., max_length=256)
tag: str | None = Field(None, max_length=64)
uid: UID
phones: list[Phone] | None = Field(None, max_length=10)
fax: list[Fax] | None = None
height: int | float | None = Field(None, ge=1.0, le=300.0)
weight: float | int | None = Field(None, ge=1.0, le=1000.0)
age: int | None = Field(None, gt=0, le=200)
rating: float | None = Field(None, gt=0.0, le=5.0)
class Users(RootModel[list[User]]):
root: list[User]
class Id(RootModel[str]):
root: str
class Rules(RootModel[list[str]]):
root: list[str]
class Error(BaseModel):
code: int
message: str
class Api(BaseModel):
apiKey: str | None = Field(
None, description='To be used as a dataset parameter value'
)
apiVersionNumber: str | None = Field(
None, description='To be used as a version parameter value'
)
apiUrl: AnyUrl | None = Field(
None, description="The URL describing the dataset's fields"
)
apiDocumentationUrl: AnyUrl | None = Field(
None, description='A URL to the API console for each API'
)
class Apis(RootModel[list[Api]]):
root: list[Api]
class Event(BaseModel):
name: str | None = None
class Result(BaseModel):
event: Event | None = None
--disable-timestamp¶
Disable timestamp in generated file header for reproducible output.
The --disable-timestamp flag configures the code generation behavior.
See also: CI/CD Integration
Usage
-
--disable-timestamp- the option documented here
Examples
Input Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Info",
"type": "object",
"properties": {
"hostName": {
"type": "string",
"format": "hostname"
},
"arn": {
"type": "string",
"pattern": "(^arn:([^:]*):([^:]*):([^:]*):(|\\*|[\\d]{12}):(.+)$)|^\\*$"
},
"tel": {
"type": "string",
"pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
},
"comment": {
"type": "string",
"pattern": "[^\\x08\\f\\n\\r\\t\\\\a+.?'\"|()]+$"
}
}
}
Output:
# generated by datamodel-codegen:
# filename: pattern.json
from __future__ import annotations
from pydantic import BaseModel, constr
class Info(BaseModel):
hostName: (
constr(
pattern=r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9])$'
)
| None
) = None
arn: (
constr(pattern=r'(^arn:([^:]*):([^:]*):([^:]*):(|\*|[\d]{12}):(.+)$)|^\*$')
| None
) = None
tel: constr(pattern=r'^(\([0-9]{3}\))?[0-9]{3}-[0-9]{4}$') | None = None
comment: constr(pattern=r'[^\x08\f\n\r\t\\a+.?\'"|()]+$') | None = None
--enable-command-header¶
Include command-line options in file header for reproducibility.
The --enable-command-header flag adds the full command-line used to generate
the file to the header, making it easy to reproduce the generation.
Usage
-
--enable-command-header- 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:
# generated by datamodel-codegen:
# filename: api.yaml
# timestamp: 2019-07-26T00:00:00+00:00
# command: datamodel-codegen [COMMAND]
from __future__ import annotations
from pydantic import AnyUrl, BaseModel, Field, RootModel
class Pet(BaseModel):
id: int
name: str
tag: str | None = None
class Pets(RootModel[list[Pet]]):
root: list[Pet]
class User(BaseModel):
id: int
name: str
tag: str | None = None
class Users(RootModel[list[User]]):
root: list[User]
class Id(RootModel[str]):
root: str
class Rules(RootModel[list[str]]):
root: list[str]
class Error(BaseModel):
code: int
message: str
class Api(BaseModel):
apiKey: str | None = Field(
None, description='To be used as a dataset parameter value'
)
apiVersionNumber: str | None = Field(
None, description='To be used as a version parameter value'
)
apiUrl: AnyUrl | None = Field(
None, description="The URL describing the dataset's fields"
)
apiDocumentationUrl: AnyUrl | None = Field(
None, description='A URL to the API console for each API'
)
class Apis(RootModel[list[Api]]):
root: list[Api]
class Event(BaseModel):
name: str | None = None
class Result(BaseModel):
event: Event | None = None
--enable-generated-header-marker¶
Include the @generated marker in file header for generated-code tooling.
The --enable-generated-header-marker flag marks generated output for tools that
recognize the @generated marker.
Usage
-
--enable-generated-header-marker- 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:
# @generated by datamodel-codegen:
# filename: api.yaml
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from pydantic import AnyUrl, BaseModel, Field, RootModel
class Pet(BaseModel):
id: int
name: str
tag: str | None = None
class Pets(RootModel[list[Pet]]):
root: list[Pet]
class User(BaseModel):
id: int
name: str
tag: str | None = None
class Users(RootModel[list[User]]):
root: list[User]
class Id(RootModel[str]):
root: str
class Rules(RootModel[list[str]]):
root: list[str]
class Error(BaseModel):
code: int
message: str
class Api(BaseModel):
apiKey: str | None = Field(
None, description='To be used as a dataset parameter value'
)
apiVersionNumber: str | None = Field(
None, description='To be used as a version parameter value'
)
apiUrl: AnyUrl | None = Field(
None, description="The URL describing the dataset's fields"
)
apiDocumentationUrl: AnyUrl | None = Field(
None, description='A URL to the API console for each API'
)
class Apis(RootModel[list[Api]]):
root: list[Api]
class Event(BaseModel):
name: str | None = None
class Result(BaseModel):
event: Event | None = None
--enable-version-header¶
Include tool version information in file header.
The --enable-version-header flag configures the code generation behavior.
Usage
-
--enable-version-header- 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:
# generated by datamodel-codegen:
# filename: api.yaml
# timestamp: 2019-07-26T00:00:00+00:00
# version: 0.0.0
from __future__ import annotations
from pydantic import AnyUrl, BaseModel, Field, RootModel
class Pet(BaseModel):
id: int
name: str
tag: str | None = None
class Pets(RootModel[list[Pet]]):
root: list[Pet]
class User(BaseModel):
id: int
name: str
tag: str | None = None
class Users(RootModel[list[User]]):
root: list[User]
class Id(RootModel[str]):
root: str
class Rules(RootModel[list[str]]):
root: list[str]
class Error(BaseModel):
code: int
message: str
class Api(BaseModel):
apiKey: str | None = Field(
None, description='To be used as a dataset parameter value'
)
apiVersionNumber: str | None = Field(
None, description='To be used as a version parameter value'
)
apiUrl: AnyUrl | None = Field(
None, description="The URL describing the dataset's fields"
)
apiDocumentationUrl: AnyUrl | None = Field(
None, description='A URL to the API console for each API'
)
class Apis(RootModel[list[Api]]):
root: list[Api]
class Event(BaseModel):
name: str | None = None
class Result(BaseModel):
event: Event | None = None
--extra-template-data¶
Pass custom template variables via inline JSON or a JSON file path.
The --extra-template-data flag allows you to provide additional variables
from an inline JSON object or JSON file that can be used in custom templates to configure generated
model settings like Config classes, enabling customization beyond standard options.
See also: Custom Templates
Usage
-
--extra-template-data- 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:
# generated by datamodel-codegen:
# filename: api.yaml
# timestamp: 1985-10-26T08:21:00+00:00
from __future__ import annotations
from pydantic import AnyUrl, BaseModel, ConfigDict, Field, RootModel
class Pet(BaseModel): # 1 2, 1 2, this is just a pet
model_config = ConfigDict(
arbitrary_types_allowed=True,
coerce_numbers_to_str=True,
)
id: int
name: str
tag: str | None = None
class Pets(RootModel[list[Pet]]):
root: list[Pet]
class User(BaseModel):
id: int
name: str
tag: str | None = None
class Users(RootModel[list[User]]):
root: list[User]
class Id(RootModel[str]):
root: str
class Rules(RootModel[list[str]]):
root: list[str]
class Error(BaseModel):
code: int
message: str
class Api(BaseModel):
apiKey: str | None = Field(
None, description='To be used as a dataset parameter value'
)
apiVersionNumber: str | None = Field(
None, description='To be used as a version parameter value'
)
apiUrl: AnyUrl | None = Field(
None, description="The URL describing the dataset's fields"
)
apiDocumentationUrl: AnyUrl | None = Field(
None, description='A URL to the API console for each API'
)
class Apis(RootModel[list[Api]]):
root: list[Api]
class Event(BaseModel):
name: str | None = None
class Result(BaseModel):
event: Event | None = None
--formatters¶
Specify code formatters to apply to generated output.
The --formatters flag specifies which code formatters to apply to
the generated Python code. Available formatters are: builtin, black,
isort, ruff-check, ruff-format. Default is [black, isort].
Use this to customize formatting or disable formatters entirely.
See also: CI/CD Integration, Formatter behavior, Code Formatting
Usage
-
--formatters- 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:
--no-treat-dot-as-module¶
Keep dots in schema names as underscores for flat output.
The --no-treat-dot-as-module flag prevents splitting dotted schema names.
Usage
-
--no-treat-dot-as-module- the option documented here
Examples
Input Schema:
# model.schema.json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "User",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer"
}
},
"required": ["name"]
}
Output:
# __init__.py
# generated by datamodel-codegen:
# filename: treat_dot_as_module_single
# timestamp: 2019-07-26T00:00:00+00:00
# model_schema.py
# generated by datamodel-codegen:
# filename: model.schema.json
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int | None = None
--no-use-type-checking-imports¶
Keep generated model imports available at runtime when using Ruff fixes.
The --no-use-type-checking-imports flag prevents Ruff from moving generated model imports
into TYPE_CHECKING blocks. This is useful for modular Pydantic output where referenced
models need to be importable at runtime without calling model_rebuild() manually.
In the multi-module Pydantic + ruff-check case, runtime imports are preserved by default.
--use-type-checking-imports opts back into the old TYPE_CHECKING-only behavior, which can
require manual model_rebuild() calls for cross-module runtime references.
Related: --formatters, --use-exact-imports, --use-type-checking-imports
Usage
datamodel-codegen --input schema.json --output-model-type pydantic_v2.BaseModel --formatters ruff-check ruff-format --no-use-type-checking-imports --disable-timestamp # (1)!
-
--no-use-type-checking-imports- the option documented here
Examples
Input Schema:
openapi: "3.0.0"
info:
version: 1.0.0
title: Modular Swagger Petstore
license:
name: MIT
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/collections.Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
x-amazon-apigateway-integration:
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
passthroughBehavior: when_no_templates
httpMethod: POST
type: aws_proxy
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
x-amazon-apigateway-integration:
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
passthroughBehavior: when_no_templates
httpMethod: POST
type: aws_proxy
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/collections.Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
x-amazon-apigateway-integration:
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
passthroughBehavior: when_no_templates
httpMethod: POST
type: aws_proxy
components:
schemas:
models.Species:
type: string
enum:
- dog
- cat
- snake
models.Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
species:
$ref: '#/components/schemas/models.Species'
models.User:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
collections.Pets:
type: array
items:
$ref: "#/components/schemas/models.Pet"
collections.Users:
type: array
items:
$ref: "#/components/schemas/models.User"
optional:
type: string
Id:
type: string
collections.Rules:
type: array
items:
type: string
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
collections.apis:
type: array
items:
type: object
properties:
apiKey:
type: string
description: To be used as a dataset parameter value
apiVersionNumber:
type: string
description: To be used as a version parameter value
apiUrl:
type: string
format: uri
description: "The URL describing the dataset's fields"
apiDocumentationUrl:
type: string
format: uri
description: A URL to the API console for each API
stage:
type: string
enum: [
"test",
"dev",
"stg",
"prod"
]
models.Event:
type: object
properties:
name:
anyOf:
- type: string
- type: number
- type: integer
- type: boolean
- type: object
- type: array
items:
type: string
Result:
type: object
properties:
event:
$ref: '#/components/schemas/models.Event'
foo.bar.Thing:
properties:
attributes:
type: object
foo.bar.Thang:
properties:
attributes:
type: array
items:
type: object
foo.bar.Clone:
allOf:
- $ref: '#/components/schemas/foo.bar.Thing'
- type: object
properties:
others:
type: object
properties:
name:
type: string
foo.Tea:
properties:
flavour:
type: string
id:
$ref: '#/components/schemas/Id'
Source:
properties:
country:
type: string
foo.Cocoa:
properties:
quality:
type: integer
bar.Field:
type: string
example: green
woo.boo.Chocolate:
properties:
flavour:
type: string
source:
$ref: '#/components/schemas/Source'
cocoa:
$ref: '#/components/schemas/foo.Cocoa'
field:
$ref: '#/components/schemas/bar.Field'
differentTea:
type: object
properties:
foo:
$ref: '#/components/schemas/foo.Tea'
nested:
$ref: '#/components/schemas/nested.foo.Tea'
nested.foo.Tea:
properties:
flavour:
type: string
id:
$ref: '#/components/schemas/Id'
self:
$ref: '#/components/schemas/nested.foo.Tea'
optional:
type: array
items:
$ref: '#/components/schemas/optional'
nested.foo.TeaClone:
properties:
flavour:
type: string
id:
$ref: '#/components/schemas/Id'
self:
$ref: '#/components/schemas/nested.foo.Tea'
optional:
type: array
items:
$ref: '#/components/schemas/optional'
nested.foo.List:
type: array
items:
$ref: '#/components/schemas/nested.foo.Tea'
Output:
# generated by datamodel-codegen:
# filename: _internal
from __future__ import annotations
from pydantic import BaseModel, RootModel
from . import models
class Optional(RootModel[str]):
root: str
class Id(RootModel[str]):
root: str
class Error(BaseModel):
code: int
message: str
class Result(BaseModel):
event: models.Event | None = None
class Source(BaseModel):
country: str | None = None
class DifferentTea(BaseModel):
foo: Tea | None = None
nested: Tea_1 | None = None
class Tea(BaseModel):
flavour: str | None = None
id: Id | None = None
class Cocoa(BaseModel):
quality: int | None = None
class Tea_1(BaseModel):
flavour: str | None = None
id: Id | None = None
self: Tea_1 | None = None
optional: list[Optional] | None = None
class TeaClone(BaseModel):
flavour: str | None = None
id: Id | None = None
self: Tea_1 | None = None
optional: list[Optional] | None = None
class List(RootModel[list[Tea_1]]):
root: list[Tea_1]
Tea_1.model_rebuild()
--treat-dot-as-module¶
Treat dots in schema names as module separators.
The --treat-dot-as-module flag configures the code generation behavior.
See also: Module Structure and Exports
Usage
-
--treat-dot-as-module- the option documented here
Examples
Input Schema:
# model.schema.json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "User",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer"
}
},
"required": ["name"]
}
Output:
# __init__.py
# generated by datamodel-codegen:
# filename: treat_dot_as_module_single
# timestamp: 2019-07-26T00:00:00+00:00
# model/__init__.py
# generated by datamodel-codegen:
# filename: treat_dot_as_module_single
# timestamp: 2019-07-26T00:00:00+00:00
# model/schema.py
# generated by datamodel-codegen:
# filename: model.schema.json
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int | None = None
--use-double-quotes¶
Use double quotes for string literals in generated code.
The --use-double-quotes option formats all string literals in the generated Python code with double quotes instead of the default single quotes. This helps maintain consistency with codebases that prefer double-quote formatting.
Usage
-
--use-double-quotes- the option documented here
Examples
Input Schema:
{
"$id": "https://example.com/schemas/MapState.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "MapState",
"allOf": [
{
"anyOf": [
{
"type": "object",
"properties": {
"latitude": {"type": "number", "minimum": -90, "maximum": 90},
"longitude": {"type": "number", "minimum": -180, "maximum": 180},
"zoom": {"type": "number", "minimum": 0, "maximum": 25, "default": 0},
"bearing": {"type": "number"},
"pitch": {"type": "number", "minimum": 0, "exclusiveMaximum": 90},
"dragRotate": {"type": "boolean"},
"mapSplitMode": {"type": "string", "const": "SINGLE_MAP"},
"isSplit": {"type": "boolean", "const": false, "default": false}
},
"required": ["latitude", "longitude", "pitch", "mapSplitMode"]
},
{
"type": "object",
"properties": {
"latitude": {"$ref": "#/allOf/0/anyOf/0/properties/latitude"},
"longitude": {"$ref": "#/allOf/0/anyOf/0/properties/longitude"},
"zoom": {"$ref": "#/allOf/0/anyOf/0/properties/zoom"},
"bearing": {"$ref": "#/allOf/0/anyOf/0/properties/bearing"},
"pitch": {"$ref": "#/allOf/0/anyOf/0/properties/pitch"},
"dragRotate": {"$ref": "#/allOf/0/anyOf/0/properties/dragRotate"},
"mapSplitMode": {"type": "string", "const": "SWIPE_COMPARE"},
"isSplit": {"type": "boolean", "const": true, "default": true}
},
"required": ["latitude", "longitude", "pitch", "mapSplitMode"]
}
]
},
{
"anyOf": [
{
"type": "object",
"properties": {
"mapViewMode": {"type": "string", "const": "MODE_2D"}
},
"required": ["mapViewMode"]
},
{
"type": "object",
"properties": {
"mapViewMode": {"type": "string", "const": "MODE_3D"}
},
"required": ["mapViewMode"]
}
]
}
]
}
Output:
# generated by datamodel-codegen:
# filename: all_of_any_of_base_class_ref.json
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field, RootModel, confloat
class MapState1(BaseModel):
map_view_mode: Literal["MODE_2D"] = Field(..., alias="mapViewMode")
class MapState2(BaseModel):
latitude: Latitude
longitude: Longitude
zoom: Zoom | None = Field(0, validate_default=True)
bearing: Bearing | None = None
pitch: Pitch
drag_rotate: DragRotate | None = Field(None, alias="dragRotate")
map_split_mode: Literal["SWIPE_COMPARE"] = Field(..., alias="mapSplitMode")
is_split: Literal[True] = Field(True, alias="isSplit")
class MapState3(BaseModel):
pass
class MapState4(MapState1, MapState3):
pass
class MapState5(MapState2, MapState3):
pass
class MapState6(MapState4):
pass
class MapState7(MapState5):
pass
class MapState(RootModel[MapState4 | MapState5 | MapState6 | MapState7]):
root: MapState4 | MapState5 | MapState6 | MapState7 = Field(..., title="MapState")
class Bearing(RootModel[float]):
root: float
class DragRotate(RootModel[bool]):
root: bool
class Latitude(RootModel[confloat(ge=-90.0, le=90.0)]):
root: confloat(ge=-90.0, le=90.0)
class Longitude(RootModel[confloat(ge=-180.0, le=180.0)]):
root: confloat(ge=-180.0, le=180.0)
class Pitch(RootModel[confloat(ge=0.0, lt=90.0)]):
root: confloat(ge=0.0, lt=90.0)
class Zoom(RootModel[confloat(ge=0.0, le=25.0)]):
root: confloat(ge=0.0, le=25.0) = 0
--use-exact-imports¶
Import exact types instead of modules.
The --use-exact-imports flag changes import style from module imports
to exact type imports. For example, instead of from . import foo then
foo.Bar, it generates from .foo import Bar. This can make the generated
code more explicit and easier to read.
Note: This option primarily affects modular output where imports between modules are generated. For single-file output, the difference is minimal.
Usage
-
--use-exact-imports- 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:
--use-type-checking-imports¶
Allow Ruff to move typing-only imports into TYPE_CHECKING blocks.
The --use-type-checking-imports flag explicitly re-enables Ruff's TYPE_CHECKING import moves
for multi-module Pydantic output where runtime imports might otherwise be preserved by default.
Related: --formatters, --no-use-type-checking-imports, --use-exact-imports
Usage
datamodel-codegen --input schema.json --output-model-type pydantic_v2.BaseModel --formatters ruff-check ruff-format --use-type-checking-imports --disable-timestamp # (1)!
-
--use-type-checking-imports- the option documented here
Examples
Input Schema:
openapi: "3.0.0"
info:
version: 1.0.0
title: Modular Swagger Petstore
license:
name: MIT
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/collections.Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
x-amazon-apigateway-integration:
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
passthroughBehavior: when_no_templates
httpMethod: POST
type: aws_proxy
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
x-amazon-apigateway-integration:
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
passthroughBehavior: when_no_templates
httpMethod: POST
type: aws_proxy
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/collections.Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
x-amazon-apigateway-integration:
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
passthroughBehavior: when_no_templates
httpMethod: POST
type: aws_proxy
components:
schemas:
models.Species:
type: string
enum:
- dog
- cat
- snake
models.Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
species:
$ref: '#/components/schemas/models.Species'
models.User:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
collections.Pets:
type: array
items:
$ref: "#/components/schemas/models.Pet"
collections.Users:
type: array
items:
$ref: "#/components/schemas/models.User"
optional:
type: string
Id:
type: string
collections.Rules:
type: array
items:
type: string
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
collections.apis:
type: array
items:
type: object
properties:
apiKey:
type: string
description: To be used as a dataset parameter value
apiVersionNumber:
type: string
description: To be used as a version parameter value
apiUrl:
type: string
format: uri
description: "The URL describing the dataset's fields"
apiDocumentationUrl:
type: string
format: uri
description: A URL to the API console for each API
stage:
type: string
enum: [
"test",
"dev",
"stg",
"prod"
]
models.Event:
type: object
properties:
name:
anyOf:
- type: string
- type: number
- type: integer
- type: boolean
- type: object
- type: array
items:
type: string
Result:
type: object
properties:
event:
$ref: '#/components/schemas/models.Event'
foo.bar.Thing:
properties:
attributes:
type: object
foo.bar.Thang:
properties:
attributes:
type: array
items:
type: object
foo.bar.Clone:
allOf:
- $ref: '#/components/schemas/foo.bar.Thing'
- type: object
properties:
others:
type: object
properties:
name:
type: string
foo.Tea:
properties:
flavour:
type: string
id:
$ref: '#/components/schemas/Id'
Source:
properties:
country:
type: string
foo.Cocoa:
properties:
quality:
type: integer
bar.Field:
type: string
example: green
woo.boo.Chocolate:
properties:
flavour:
type: string
source:
$ref: '#/components/schemas/Source'
cocoa:
$ref: '#/components/schemas/foo.Cocoa'
field:
$ref: '#/components/schemas/bar.Field'
differentTea:
type: object
properties:
foo:
$ref: '#/components/schemas/foo.Tea'
nested:
$ref: '#/components/schemas/nested.foo.Tea'
nested.foo.Tea:
properties:
flavour:
type: string
id:
$ref: '#/components/schemas/Id'
self:
$ref: '#/components/schemas/nested.foo.Tea'
optional:
type: array
items:
$ref: '#/components/schemas/optional'
nested.foo.TeaClone:
properties:
flavour:
type: string
id:
$ref: '#/components/schemas/Id'
self:
$ref: '#/components/schemas/nested.foo.Tea'
optional:
type: array
items:
$ref: '#/components/schemas/optional'
nested.foo.List:
type: array
items:
$ref: '#/components/schemas/nested.foo.Tea'
Output:
# generated by datamodel-codegen:
# filename: _internal
from __future__ import annotations
from typing import TYPE_CHECKING
from pydantic import BaseModel, RootModel
if TYPE_CHECKING:
from . import models
class Optional(RootModel[str]):
root: str
class Id(RootModel[str]):
root: str
class Error(BaseModel):
code: int
message: str
class Result(BaseModel):
event: models.Event | None = None
class Source(BaseModel):
country: str | None = None
class DifferentTea(BaseModel):
foo: Tea | None = None
nested: Tea_1 | None = None
class Tea(BaseModel):
flavour: str | None = None
id: Id | None = None
class Cocoa(BaseModel):
quality: int | None = None
class Tea_1(BaseModel):
flavour: str | None = None
id: Id | None = None
self: Tea_1 | None = None
optional: list[Optional] | None = None
class TeaClone(BaseModel):
flavour: str | None = None
id: Id | None = None
self: Tea_1 | None = None
optional: list[Optional] | None = None
class List(RootModel[list[Tea_1]]):
root: list[Tea_1]
Tea_1.model_rebuild()
--validators¶
Add custom field validators to generated Pydantic v2 models.
The --validators option takes an inline JSON object or JSON file defining validators per model.
Each validator specifies the field(s) to validate, the validation function
to import, and optionally the mode (before/after/wrap/plain).
This allows injecting custom validation logic into generated models.
See also: Field Validators
Usage
datamodel-codegen --input schema.json --validators tests/data/jsonschema/field_validators_config.json --output-model-type pydantic_v2.BaseModel --disable-timestamp # (1)!
-
--validators- the option documented here
Examples
Input Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "User",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 0
}
},
"required": ["name", "email"]
}
Output:
# generated by datamodel-codegen:
# filename: field_validators.json
from __future__ import annotations
from typing import Any
from myapp.validators import validate_email, validate_name
from pydantic import BaseModel, EmailStr, ValidationInfo, conint, field_validator
class User(BaseModel):
name: str
email: EmailStr
age: conint(ge=0) | None = None
@field_validator('name', mode='before')
@classmethod
def validate_name_validator(cls, v: Any, info: ValidationInfo) -> Any:
return validate_name(v, info)
@field_validator('email', mode='after')
@classmethod
def validate_email_validator(cls, v: Any, info: ValidationInfo) -> Any:
return validate_email(v, info)
--wrap-string-literal¶
Wrap long string literals across multiple lines.
The --wrap-string-literal flag breaks long string literals (like descriptions)
across multiple lines for better readability, instead of having very long
single-line strings in the generated code.
Usage
-
--wrap-string-literal- the option documented here
Examples
Input Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "LongDescription",
"type": "object",
"properties": {
"summary": {
"type": "string",
"description": "summary for object"
},
"description": {
"type": "string",
"description": "datamodel-code-generator. This code generator creates pydantic model from an openapi file and others."
},
"multi_line": {
"description": "datamodel-code-generator\nThis code generator creates pydantic model from an openapi file and others.\n\n\nSupported source types\nOpenAPI 3 (YAML/JSON, OpenAPI Data Type)\nJSON Schema (JSON Schema Core/JSON Schema Validation)\nJSON/YAML/CSV Data (it will be converted to JSON Schema)\nPython dictionary (it will be converted to JSON Schema)",
"type": "string"
}
}
}
Output:
# generated by datamodel-codegen:
# filename: long_description.json
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from pydantic import BaseModel, Field
class LongDescription(BaseModel):
summary: str | None = Field(None, description='summary for object')
description: str | None = Field(
None,
description=(
'datamodel-code-generator. This code generator creates pydantic model from'
' an openapi file and others.'
),
)
multi_line: str | None = Field(
None,
description=(
'datamodel-code-generator\nThis code generator creates pydantic model from'
' an openapi file and others.\n\n\nSupported source types\nOpenAPI 3'
' (YAML/JSON, OpenAPI Data Type)\nJSON Schema (JSON Schema Core/JSON Schema'
' Validation)\nJSON/YAML/CSV Data (it will be converted to JSON'
' Schema)\nPython dictionary (it will be converted to JSON Schema)'
),
)