📘 OpenAPI-only Options¶
This generated reference lists every OpenAPI-only CLI flag and its tested examples. For a workflow-oriented guide, see OpenAPI Options. For input format basics, see Generate from OpenAPI.
📋 Options¶
| Option | Description |
|---|---|
--dedupe-numbered-request-response-variants |
Deduplicate a Request or Response variant of a numbered mode... |
--dedupe-request-response-variants |
Decide Request/Response variants from the schema graph and b... |
--include-path-parameters |
Include OpenAPI path parameters in generated parameter model... |
--keep-content-parameter-refs |
Type a parameter whose content media schema is a $ref by t... |
--keep-first-character-of-path-keys |
Strip only a leading slash from a paths key when naming its ... |
--openapi-as-definitions |
Give OpenAPI paths bodies or ref components the models their... |
--openapi-include-info-version |
Emit OpenAPI info.version as a generated constant. |
--openapi-include-paths |
Filter OpenAPI paths to include in model generation. |
--openapi-scopes |
Specify OpenAPI scopes to generate (schemas, paths, paramete... |
--read-only-write-only-model-type |
Generate separate request and response models for readOnly/w... |
--skip-path-extension-keys |
Skip the x- keys of paths in the paths scope, as the `... |
--use-enum-field-as-literal-in-operations |
Write an operation body or response enum as a Literal root m... |
--use-operation-id-as-name |
Use OpenAPI operationId as the generated function/class name... |
--use-status-code-in-response-name |
Include HTTP status code in response model names. |
--validation |
Enable validation constraints (deprecated, use --field-const... |
🍳 Recipes¶
Generate operation-focused models¶
Limit OpenAPI output to operation shapes and name models from operation IDs and status codes.
Options: --openapi-scopes, --use-operation-id-as-name, --use-status-code-in-response-name
Trim an OpenAPI build¶
Restrict generation to selected paths while preserving parameter and info-version context.
Options: --openapi-include-paths, --include-path-parameters, --openapi-include-info-version
--dedupe-numbered-request-response-variants¶
Deduplicate a Request or Response variant of a numbered model like the model.
An inline object that renders as a component gets a numbered name (Page1) and merges into the component (Page),
but its read/write variants keep names of their own (Page1Request, Page1Response): under
--read-only-write-only-model-type request-response the fields of HolderRequest and HolderResponse name them, and
under all an unused Page1Request is written. With --dedupe-numbered-request-response-variants such a variant is
deduplicated by the variant name of the name its model was numbered from, so it merges into PageRequest or
PageResponse where it renders the same.
Related: --dedupe-request-response-variants, --read-only-write-only-model-type
Usage
datamodel-codegen --input read_only_numbered_variants.yaml --read-only-write-only-model-type request-response --dedupe-numbered-request-response-variants # (1)!
-
--dedupe-numbered-request-response-variants- the option documented here
Examples
Input Schema:
openapi: 3.1.0
info: {title: t, version: "1"}
paths: {}
components:
schemas:
Page:
type: object
properties:
cursor: {type: string, readOnly: true}
size: {type: integer}
Holder:
type: object
properties:
page:
type: object
properties:
cursor: {type: string, readOnly: true}
size: {type: integer}
Output:
# generated by datamodel-codegen:
# filename: read_only_numbered_variants.yaml
from __future__ import annotations
from pydantic import BaseModel
class PageRequest(BaseModel):
size: int | None = None
class PageResponse(BaseModel):
cursor: str | None = None
size: int | None = None
class HolderRequest(BaseModel):
page: PageRequest | None = None
class HolderResponse(BaseModel):
page: PageResponse | None = None
# generated by datamodel-codegen:
# filename: read_only_numbered_variants.yaml
from __future__ import annotations
from pydantic import BaseModel
class PageRequest(BaseModel):
size: int | None = None
class PageResponse(BaseModel):
cursor: str | None = None
size: int | None = None
class Page1Request(BaseModel):
size: int | None = None
class Page1Response(BaseModel):
cursor: str | None = None
size: int | None = None
class HolderRequest(BaseModel):
page: Page1Request | None = None
class HolderResponse(BaseModel):
page: Page1Response | None = None
--dedupe-request-response-variants¶
Decide Request/Response variants from the schema graph and build each inline model once.
Under --read-only-write-only-model-type (request-response or all), the generator decides which models split into
Request and Response variants. Without the flag it decides as 0.86.0 did, from a temporary parse of each referenced
schema; that parse takes class names and can emit unreferenced copies, so other classes get higher numbers
(Child1Request where ChildRequest is free), and a schema whose parse reaches itself again through the models it
builds stops there. A child that inherits from an allOf parent also builds the inline models of the parent's
properties a second time (Payload1 unused, Payload2 referenced). Some recursive schemas cannot be generated that
way and the error names this flag.
With the flag the decision reads the raw schemas only: an input without readOnly or writeOnly gives the models it
gives without --read-only-write-only-model-type, and each inline model is written once (Payload1 referenced).
Both forms validate the same data.
Usage
datamodel-codegen --input read_only_write_only_allof_parent_inline_models.yaml --output-model-type pydantic_v2.BaseModel --read-only-write-only-model-type request-response --dedupe-request-response-variants # (1)!
-
--dedupe-request-response-variants- the option documented here
Examples
Input Schema:
openapi: 3.1.0
info:
title: t
version: '1'
paths: {}
components:
schemas:
Child:
allOf:
- $ref: '#/components/schemas/Parent'
- type: object
properties:
payload:
properties:
extra:
type: string
Parent:
type: object
properties:
id:
type: integer
readOnly: true
payload:
type: object
properties:
value:
type: object
properties:
code:
type: integer
Output:
# generated by datamodel-codegen:
# filename: read_only_write_only_allof_parent_inline_models.yaml
from __future__ import annotations
from pydantic import BaseModel
class Value(BaseModel):
code: int | None = None
class Payload(BaseModel):
value: Value | None = None
extra: str | None = None
class Payload1(BaseModel):
value: Value | None = None
class ChildRequest(BaseModel):
payload: Payload | None = None
class ChildResponse(BaseModel):
id: int | None = None
payload: Payload | None = None
class ParentRequest(BaseModel):
payload: Payload1 | None = None
class ParentResponse(BaseModel):
id: int | None = None
payload: Payload1 | None = None
# generated by datamodel-codegen:
# filename: read_only_write_only_allof_parent_inline_models.yaml
from __future__ import annotations
from pydantic import BaseModel
class Value(BaseModel):
code: int | None = None
class Payload(BaseModel):
value: Value | None = None
extra: str | None = None
class Payload1(BaseModel):
value: Value | None = None
class ChildRequest(BaseModel):
payload: Payload | None = None
class ChildResponse(BaseModel):
id: int | None = None
payload: Payload | None = None
class Payload2(BaseModel):
value: Value | None = None
class ParentRequest(BaseModel):
payload: Payload2 | None = None
class ParentResponse(BaseModel):
id: int | None = None
payload: Payload2 | None = None
--include-path-parameters¶
Include OpenAPI path parameters in generated parameter models.
The --include-path-parameters flag adds path parameters (like /users/{userId})
to the generated request parameter models. By default, only query parameters
are included. Use this with --openapi-scopes parameters to generate parameter
models that include both path and query parameters.
See also: OpenAPI Options
Usage
datamodel-codegen --input include_path_parameters.yaml --include-path-parameters --openapi-scopes schemas paths parameters # (1)!
-
--include-path-parameters- the option documented here
Examples
Input Schema:
openapi: "3.0.0"
info:
version: 1.0.0
title: API with Path Parameters
paths:
/users/{userId}/posts/{postId}:
get:
summary: Get a specific post by user
operationId: getUserPost
parameters:
- name: userId
in: path
required: true
schema:
type: integer
- name: postId
in: path
required: true
schema:
type: string
- name: includeComments
in: query
required: false
schema:
type: boolean
responses:
'200':
description: A post
content:
application/json:
schema:
$ref: "#/components/schemas/Post"
components:
schemas:
Post:
type: object
properties:
id:
type: string
title:
type: string
content:
type: string
Output:
# generated by datamodel-codegen:
# filename: include_path_parameters.yaml
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from pydantic import BaseModel
class Post(BaseModel):
id: str | None = None
title: str | None = None
content: str | None = None
class UsersUserIdPostsPostIdGetParameters(BaseModel):
userId: int
postId: str
includeComments: bool | None = None
--keep-content-parameter-refs¶
Type a parameter whose content media schema is a $ref by the model the $ref names.
Without this option a parameter with content reads its media schema {"$ref": "#/components/schemas/Page"} as a
copy of the referenced schema: an object gets a model of the parameter's own (merged back into Page only where the
two render alike), and a scalar its inline type with the default and description of the target. Under
--read-only-write-only-model-type request-response the copy splits into Page1Request and Page1Response beside
PageRequest and PageResponse, and the parameter names Page1Request. With the option the parameter names the
referenced model, its Request variant there, as a parameter's schema: {"$ref": ...} does.
Usage
datamodel-codegen --input content_parameter_refs.yaml --openapi-scopes schemas paths parameters --read-only-write-only-model-type request-response --keep-content-parameter-refs # (1)!
-
--keep-content-parameter-refs- the option documented here
Examples
Input Schema:
openapi: 3.1.0
info:
title: Parameters whose content media schema is a $ref
version: "1.0"
paths:
/content:
get:
parameters:
- name: page
in: query
content:
application/json:
schema:
$ref: "#/components/schemas/Page"
- name: count
in: query
content:
application/json:
schema:
$ref: "#/components/schemas/Count"
- name: anything
in: query
content:
application/json:
schema: true
- name: other
in: query
schema:
$ref: "#/components/schemas/Page"
responses:
"200":
description: OK
components:
schemas:
Page:
type: object
description: A page.
properties:
cursor:
type: string
readOnly: true
size:
type: integer
Count:
type: integer
description: A count.
minimum: 1
default: 3
Output:
# generated by datamodel-codegen:
# filename: content_parameter_refs.yaml
from __future__ import annotations
from typing import Any
from pydantic import BaseModel, Field, RootModel, conint
class PageRequest(BaseModel):
size: int | None = None
class PageResponse(BaseModel):
cursor: str | None = None
size: int | None = None
class Count(RootModel[conint(ge=1)]):
root: conint(ge=1) = Field(3, description='A count.')
class ContentGetParametersQuery(BaseModel):
page: PageRequest | None = None
count: Count | None = Field(3, validate_default=True)
anything: Any | None = None
other: PageRequest | None = None
# generated by datamodel-codegen:
# filename: content_parameter_refs.yaml
from __future__ import annotations
from typing import Any
from pydantic import BaseModel, Field, RootModel, conint
class PageRequest(BaseModel):
size: int | None = None
class PageResponse(BaseModel):
cursor: str | None = None
size: int | None = None
class Count(RootModel[conint(ge=1)]):
root: conint(ge=1) = Field(3, description='A count.')
class Page1Request(BaseModel):
size: int | None = None
class Page1Response(BaseModel):
cursor: str | None = None
size: int | None = None
class ContentGetParametersQuery(BaseModel):
page: Page1Request | None = Field(None, description='A page.')
count: conint(ge=1) | None = Field(3, description='A count.')
anything: Any | None = None
other: PageRequest | None = None
--keep-first-character-of-path-keys¶
Strip only a leading slash from a paths key when naming its operation models.
The models of an operation are named after its path, without the leading /. A paths key that does not start with
/, which OpenAPI does not allow but which is read, loses its first character instead: pets gives EtsGetResponse.
With --keep-first-character-of-path-keys only a leading slash is stripped, as for webhook names and the api scope:
pets gives PetsGetResponse. Keys that start with / are named as before.
Related: --openapi-scopes
Usage
datamodel-codegen --input paths_key_without_leading_slash.yaml --openapi-scopes schemas paths parameters --keep-first-character-of-path-keys # (1)!
-
--keep-first-character-of-path-keys- the option documented here
Examples
Input Schema:
openapi: 3.0.0
info: {title: t, version: '1'}
paths:
pets:
get:
parameters:
- {name: q, in: query, schema: {type: string}}
responses:
'200':
description: ok
content:
application/json:
schema: {type: object, properties: {a: {type: string}}}
/stores:
get:
responses:
'200':
description: ok
content:
application/json:
schema: {type: object, properties: {b: {type: integer}}}
Output:
# generated by datamodel-codegen:
# filename: paths_key_without_leading_slash.yaml
from __future__ import annotations
from pydantic import BaseModel
class PetsGetParametersQuery(BaseModel):
q: str | None = None
class PetsGetResponse(BaseModel):
a: str | None = None
class StoresGetResponse(BaseModel):
b: int | None = None
# generated by datamodel-codegen:
# filename: paths_key_without_leading_slash.yaml
from __future__ import annotations
from pydantic import BaseModel
class EtsGetParametersQuery(BaseModel):
q: str | None = None
class EtsGetResponse(BaseModel):
a: str | None = None
class StoresGetResponse(BaseModel):
b: int | None = None
--openapi-as-definitions¶
Give OpenAPI paths bodies or ref components the models their definitions get.
The --openapi-as-definitions option takes one or more values, paths-bodies and ref-components, each a
separate change.
paths-bodies: with --openapi-scopes paths (or webhooks), request and response bodies are parsed by their own
dispatch, which types some object bodies inline although a schema definition of the same body gets a model: a body
whose type array admits objects, such as type: [object, "null"], or one with additionalProperties,
patternProperties or propertyNames and no type. With --openapi-as-definitions paths-bodies, such a body gets
the model its definition would get, such as a root model of dict[str, Any] | None, whose values
--use-typed-nullable-map-values types as declared. A document whose only bodies are such schemas then generates
models instead of failing with "Models not found in the input data", whose message names this value when it
applies. A body of type: object with patternProperties or propertyNames and no properties gets the root model
of a map its definition gets, such as dict[constr(pattern=r'^a'), int], instead of the model or dict[str, ...] of
0.86.0; one whose patternProperties admit its only keys (additionalProperties: false) gets that root model with or
without the value. Bodies typed as arrays, combinations, enums and references, and the api scope, are unchanged.
ref-components: a component such as Tree: {$ref: '#/components/schemas/Node', minProperties: 1}, where Node
leads back to Tree or to itself, cannot merge its sibling keywords into Node. Without the value it gets no model,
as in 0.86.0, and a reference to it is typed by Node; with --openapi-as-definitions ref-components it gets the
root model Tree(RootModel[Node]) that the same schema gets as a $defs entry, references to it name Tree, and a
component nothing references is generated too. Such a component in another document gets that model with or without
the value.
Usage
datamodel-codegen --input type_array_request_body.yaml --openapi-scopes paths --openapi-as-definitions paths-bodies # (1)!
-
--openapi-as-definitions- the option documented here
Examples
Input Schema:
openapi: 3.1.0
info:
title: Type array request body
version: "1.0"
paths:
/pets:
post:
requestBody:
content:
application/json:
schema:
type: [object, "null"]
additionalProperties:
type: object
properties:
name:
type: string
responses:
"200":
description: The pets are stored.
Output:
--openapi-include-info-version¶
Emit OpenAPI info.version as a generated constant.
The --openapi-include-info-version flag adds OPENAPI_INFO_VERSION to the
generated module so applications can check the source OpenAPI document version
at build time or runtime.
Usage
-
--openapi-include-info-version- the option documented here
Examples
Input Schema:
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
x-amazon-apigateway-integration:
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
passthroughBehavior: when_no_templates
httpMethod: POST
type: aws_proxy
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
x-amazon-apigateway-integration:
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
passthroughBehavior: when_no_templates
httpMethod: POST
type: aws_proxy
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
x-amazon-apigateway-integration:
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations
passthroughBehavior: when_no_templates
httpMethod: POST
type: aws_proxy
components:
schemas:
Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
default: 1
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: "#/components/schemas/Pet"
Users:
type: array
items:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Id:
type: string
Rules:
type: array
items:
type: string
Error:
description: error result
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
apis:
type: array
items:
type: object
properties:
apiKey:
type: string
description: To be used as a dataset parameter value
apiVersionNumber:
type: string
description: To be used as a version parameter value
apiUrl:
type: string
format: uri
description: "The URL describing the dataset's fields"
apiDocumentationUrl:
type: string
format: uri
description: A URL to the API console for each API
Event:
type: object
description: Event object
properties:
name:
type: string
Result:
type: object
properties:
event:
$ref: '#/components/schemas/Event'
Output:
# 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
OPENAPI_INFO_VERSION = '1.0.0'
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
--openapi-include-paths¶
Filter OpenAPI paths to include in model generation.
The --openapi-include-paths flag allows filtering which paths are processed.
Usage
datamodel-codegen --input body_and_parameters.yaml --openapi-scopes paths schemas --openapi-include-paths /pets* # (1)!
-
--openapi-include-paths- the option documented here
Examples
Input Schema:
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
description: |
This description is for testing
multi-line
description
servers:
- url: http://petstore.swagger.io/v1
security:
- BearerAuth: []
paths:
/pets:
$ref: '#/components/pathItems/Pets'
/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/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
put:
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
summary: update a pet
tags:
- pets
requestBody:
required: false
content:
application/json:
schema:
$ref: '#/components/schemas/PetForm'
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
/food:
post:
summary: Create a food
tags:
- pets
requestBody:
required: true
content:
application/problem+json:
schema:
type: string
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/problem+json:
schema:
type: string
/food/{food_id}:
get:
summary: Info for a specific pet
operationId: showFoodById
tags:
- foods
parameters:
- name: food_id
in: path
description: The id of the food to retrieve
schema:
type: string
- name: message_texts
in: query
required: false
explode: true
schema:
type: array
items:
type: string
responses:
'200':
description: OK
content:
application/json:
schema:
type: array
items:
type: integer
examples:
example-1:
value:
- 0
- 1
- 3
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
/foo:
get:
tags:
- foo
responses:
'200':
description: OK
content:
application/json:
schema:
type: string
parameters:
- $ref: '#/components/parameters/MyParam'
/bar:
post:
summary: Create a bar
tags:
- bar
requestBody:
content:
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/PetForm'
/user:
get:
tags:
- user
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
timestamp:
type: string
format: date-time
name:
type: string
age:
type: string
required:
- name
- timestamp
post:
tags:
- user
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
timestamp:
type: string
format: date-time
name:
type: string
age:
type: string
required:
- name
- timestamp
responses:
'201':
description: OK
/users:
get:
tags:
- user
responses:
'200':
description: OK
content:
application/json:
schema:
type: array
items:
type: object
properties:
timestamp:
type: string
format: date-time
name:
type: string
age:
type: string
required:
- name
- timestamp
post:
tags:
- user
requestBody:
required: true
content:
application/json:
schema:
type: array
items:
type: object
properties:
timestamp:
type: string
format: date-time
name:
type: string
age:
type: string
required:
- name
- timestamp
responses:
'201':
description: OK
components:
parameters:
MyParam:
name: foo
in: query
schema:
type: string
securitySchemes:
BearerAuth:
type: http
scheme: bearer
schemas:
Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
PetForm:
title: PetForm
type: object
properties:
name:
type: string
age:
type: integer
pathItems:
Pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
security: []
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
default: 0
type: integer
format: int32
- name: HomeAddress
in: query
required: false
schema:
default: 'Unknown'
type: string
- name: kind
in: query
required: false
schema:
default: dog
type: string
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:
type: array
items:
- $ref: "#/components/schemas/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
tags:
- pets
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/PetForm'
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
Output:
# generated by datamodel-codegen:
# filename: body_and_parameters.yaml
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from pydantic import BaseModel, RootModel
class Pet(BaseModel):
id: int
name: str
tag: str | None = None
class Error(BaseModel):
code: int
message: str
class PetForm(BaseModel):
name: str | None = None
age: int | None = None
class PetsGetResponse(RootModel[list[Pet]]):
root: list[Pet]
--openapi-scopes¶
Specify OpenAPI scopes to generate (schemas, paths, parameters).
The --openapi-scopes flag configures the code generation behavior.
See also: OpenAPI Options
Usage
-
--openapi-scopes- the option documented here
Examples
Input Schema:
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
description: |
This description is for testing
multi-line
description
servers:
- url: http://petstore.swagger.io/v1
security:
- BearerAuth: []
paths:
/pets:
$ref: '#/components/pathItems/Pets'
/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/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
put:
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
summary: update a pet
tags:
- pets
requestBody:
required: false
content:
application/json:
schema:
$ref: '#/components/schemas/PetForm'
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
/food:
post:
summary: Create a food
tags:
- pets
requestBody:
required: true
content:
application/problem+json:
schema:
type: string
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/problem+json:
schema:
type: string
/food/{food_id}:
get:
summary: Info for a specific pet
operationId: showFoodById
tags:
- foods
parameters:
- name: food_id
in: path
description: The id of the food to retrieve
schema:
type: string
- name: message_texts
in: query
required: false
explode: true
schema:
type: array
items:
type: string
responses:
'200':
description: OK
content:
application/json:
schema:
type: array
items:
type: integer
examples:
example-1:
value:
- 0
- 1
- 3
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
/foo:
get:
tags:
- foo
responses:
'200':
description: OK
content:
application/json:
schema:
type: string
parameters:
- $ref: '#/components/parameters/MyParam'
/bar:
post:
summary: Create a bar
tags:
- bar
requestBody:
content:
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/PetForm'
/user:
get:
tags:
- user
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
timestamp:
type: string
format: date-time
name:
type: string
age:
type: string
required:
- name
- timestamp
post:
tags:
- user
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
timestamp:
type: string
format: date-time
name:
type: string
age:
type: string
required:
- name
- timestamp
responses:
'201':
description: OK
/users:
get:
tags:
- user
responses:
'200':
description: OK
content:
application/json:
schema:
type: array
items:
type: object
properties:
timestamp:
type: string
format: date-time
name:
type: string
age:
type: string
required:
- name
- timestamp
post:
tags:
- user
requestBody:
required: true
content:
application/json:
schema:
type: array
items:
type: object
properties:
timestamp:
type: string
format: date-time
name:
type: string
age:
type: string
required:
- name
- timestamp
responses:
'201':
description: OK
components:
parameters:
MyParam:
name: foo
in: query
schema:
type: string
securitySchemes:
BearerAuth:
type: http
scheme: bearer
schemas:
Pet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
PetForm:
title: PetForm
type: object
properties:
name:
type: string
age:
type: integer
pathItems:
Pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
security: []
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
default: 0
type: integer
format: int32
- name: HomeAddress
in: query
required: false
schema:
default: 'Unknown'
type: string
- name: kind
in: query
required: false
schema:
default: dog
type: string
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:
type: array
items:
- $ref: "#/components/schemas/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
tags:
- pets
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/PetForm'
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
Output:
# generated by datamodel-codegen:
# filename: body_and_parameters.yaml
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from pydantic import AwareDatetime, BaseModel, RootModel
class Pet(BaseModel):
id: int
name: str
tag: str | None = None
class Error(BaseModel):
code: int
message: str
class PetForm(BaseModel):
name: str | None = None
age: int | None = None
class PetsGetResponse(RootModel[list[Pet]]):
root: list[Pet]
class FoodFoodIdGetResponse(RootModel[list[int]]):
root: list[int]
class UserGetResponse(BaseModel):
timestamp: AwareDatetime
name: str
age: str | None = None
class UserPostRequest(BaseModel):
timestamp: AwareDatetime
name: str
age: str | None = None
class UsersGetResponseItem(BaseModel):
timestamp: AwareDatetime
name: str
age: str | None = None
class UsersGetResponse(RootModel[list[UsersGetResponseItem]]):
root: list[UsersGetResponseItem]
class UsersPostRequestItem(BaseModel):
timestamp: AwareDatetime
name: str
age: str | None = None
class UsersPostRequest(RootModel[list[UsersPostRequestItem]]):
root: list[UsersPostRequestItem]
--read-only-write-only-model-type¶
Generate separate request and response models for readOnly/writeOnly fields.
The --read-only-write-only-model-type option controls how models with readOnly or writeOnly
properties are generated. The 'request-response' mode creates separate Request and Response
variants for each schema that contains readOnly or writeOnly fields, allowing proper type
validation for API requests and responses without a shared base model.
See also: OpenAPI Options
Usage
datamodel-codegen --input read_only_write_only.yaml --output-model-type pydantic_v2.BaseModel --read-only-write-only-model-type request-response # (1)!
-
--read-only-write-only-model-type- the option documented here
Examples
Input Schema:
openapi: "3.0.0"
info:
title: Read Only Write Only Test API
version: "1.0"
paths: {}
components:
schemas:
User:
type: object
required:
- id
- name
- password
properties:
id:
type: integer
readOnly: true
name:
type: string
password:
type: string
writeOnly: true
created_at:
type: string
format: date-time
readOnly: true
secret_token:
type: string
writeOnly: true
Output:
# generated by datamodel-codegen:
# filename: read_only_write_only.yaml
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from pydantic import AwareDatetime, BaseModel
class UserRequest(BaseModel):
name: str
password: str
secret_token: str | None = None
class UserResponse(BaseModel):
id: int
name: str
created_at: AwareDatetime | None = None
--skip-path-extension-keys¶
Skip the x- keys of paths in the paths scope, as the api scope does.
OpenAPI reads a key of the Paths Object that begins with x- as a specification extension, not as a path. The
paths scope reads such a key that holds an object as a path, so the operations under x-internal get models
(FieldInternalGetResponse). With --skip-path-extension-keys the paths scope skips it, as the api scope always
does. A key that holds no object is skipped either way.
Related: --openapi-scopes
Usage
datamodel-codegen --input paths_extension_keys.yaml --openapi-scopes schemas paths parameters --skip-path-extension-keys # (1)!
-
--skip-path-extension-keys- the option documented here
Examples
Input Schema:
openapi: 3.0.3
info: {title: t, version: '1'}
paths:
x-internal:
get:
parameters:
- {name: secret, in: query, schema: {type: string}}
responses:
'200':
description: ok
content:
application/json:
schema: {type: object, properties: {hidden: {type: string}}}
x-owner: platform team
/pets:
get:
parameters:
- {name: limit, in: query, schema: {type: integer}}
responses:
'200':
description: ok
content:
application/json:
schema: {type: object, properties: {name: {type: string}}}
Output:
# generated by datamodel-codegen:
# filename: paths_extension_keys.yaml
from __future__ import annotations
from pydantic import BaseModel
class FieldInternalGetParametersQuery(BaseModel):
secret: str | None = None
class FieldInternalGetResponse(BaseModel):
hidden: str | None = None
class PetsGetParametersQuery(BaseModel):
limit: int | None = None
class PetsGetResponse(BaseModel):
name: str | None = None
--use-enum-field-as-literal-in-operations¶
Write an operation body or response enum as a Literal root model as a definition's enum is.
--enum-field-as-literal, --enum-field-as-literal-map and x-enum-field-as-literal write the enum of a definition
as a root model of a Literal (C), but the enum of a request body or response schema written inline in an
operation stays an Enum class (APostRequest). With --use-enum-field-as-literal-in-operations such an enum reads
the three as a definition's enum does, so APostRequest and APostResponse are root models of a Literal, while
APostResponse1, whose x-enum-field-as-literal is false, stays an Enum class.
Related: --enum-field-as-literal, --enum-field-as-literal-map
Usage
datamodel-codegen --input operation_enums_as_literal.yaml --openapi-scopes schemas paths --enum-field-as-literal all --use-enum-field-as-literal-in-operations # (1)!
-
--use-enum-field-as-literal-in-operations- the option documented here
Examples
Input Schema:
openapi: 3.0.3
info: {title: t, version: '1'}
paths:
/a:
post:
requestBody:
content:
application/json:
schema: {type: string, enum: [x, y]}
responses:
'200':
description: ok
content:
application/json:
schema: {type: string, enum: [p, q]}
'201':
description: ok
content:
application/json:
schema: {type: string, enum: [s], x-enum-field-as-literal: false}
components:
schemas:
C: {type: string, enum: [m, n]}
Output:
# generated by datamodel-codegen:
# filename: operation_enums_as_literal.yaml
from __future__ import annotations
from enum import Enum
from typing import Literal
from pydantic import RootModel
class C(RootModel[Literal['m', 'n']]):
root: Literal['m', 'n']
class APostRequest(RootModel[Literal['x', 'y']]):
root: Literal['x', 'y']
class APostResponse(RootModel[Literal['p', 'q']]):
root: Literal['p', 'q']
class APostResponse1(Enum):
s = 's'
# generated by datamodel-codegen:
# filename: operation_enums_as_literal.yaml
from __future__ import annotations
from enum import Enum
from typing import Literal
from pydantic import RootModel
class C(RootModel[Literal['m', 'n']]):
root: Literal['m', 'n']
class APostRequest(Enum):
x = 'x'
y = 'y'
class APostResponse(Enum):
p = 'p'
q = 'q'
class APostResponse1(Enum):
s = 's'
--use-operation-id-as-name¶
Use OpenAPI operationId as the generated function/class name.
The --use-operation-id-as-name flag configures the code generation behavior.
See also: OpenAPI Options
Usage
datamodel-codegen --input api.yaml --use-operation-id-as-name --openapi-scopes paths schemas parameters # (1)!
-
--use-operation-id-as-name- 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
class ListPetsParametersQuery(BaseModel):
limit: int | None = None
--use-status-code-in-response-name¶
Include HTTP status code in response model names.
The --use-status-code-in-response-name flag includes the HTTP status code
in generated response model class names. Instead of generating ambiguous names
like ResourceGetResponse, ResourceGetResponse1, ResourceGetResponse2, it generates
clear names like ResourceGetResponse200, ResourceGetResponse400, ResourceGetResponseDefault.
Usage
datamodel-codegen --input use_status_code_in_response_name.yaml --use-status-code-in-response-name --openapi-scopes schemas paths # (1)!
-
--use-status-code-in-response-name- the option documented here
Examples
Input Schema:
openapi: "3.0.0"
info:
version: 1.0.0
title: Status Code Response Name Test API
paths:
/resource:
get:
summary: Get a resource
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
id:
type: integer
name:
type: string
'400':
description: Bad request error
content:
application/json:
schema:
type: object
properties:
error:
type: string
code:
type: integer
'default':
description: Unexpected error
content:
application/json:
schema:
type: object
properties:
message:
type: string
Output:
# generated by datamodel-codegen:
# filename: use_status_code_in_response_name.yaml
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from pydantic import BaseModel
class ResourceGetResponse200(BaseModel):
id: int | None = None
name: str | None = None
class ResourceGetResponse400(BaseModel):
error: str | None = None
code: int | None = None
class ResourceGetResponseDefault(BaseModel):
message: str | None = None
--validation¶
Enable validation constraints (deprecated, use --field-constraints).
The --validation flag configures the code generation behavior.
Deprecated: The --validation option is deprecated and will be removed in a future release. Use --field-constraints instead.
See also: OpenAPI Options
Usage
-
--validation- 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