Skip to content

🚀 Target Generation Options

📋 Options

Option Description
--client-asyncapi-perspective Read an AsyncAPI document as its server's or its client's (e...
--client-body-arguments Choose how operation methods take request bodies (experiment...
--client-deep-object-brackets Write deepObject values in brackets: a[]=v, a=v, a[k][k]=v (...
--client-default-base-url Set the server URL of operations that declare no servers (ex...
--client-model-package Name the import path of the models the client package import...
--client-operations Set the client settings of single operations (experimental).
--client-output Write the client package to this directory (experimental).
--client-package Name the import path of the client package (experimental).
--client-protocols Declare the protocol helpers of the client package (experime...
--client-resource-names Name the resources of tags (experimental).
--client-server-base-url Resolve relative server URLs against this base URL (experime...
--client-signature-style Declare the arguments of the operation methods (experimental...
--generate-client Generate an HTTPX2 client package for the models (experiment...
--generate-server Generate a FastAPI server package for the models (experiment...
--server-body-mode Choose how service methods receive request bodies (experimen...
--server-body-modes Set the body mode of single operations (experimental).
--server-handler-mode Declare the service methods as plain or coroutine functions ...
--server-handler-modes Set the handler mode of single operations (experimental).
--server-include-request Pass the Starlette Request to every service method (experime...
--server-layout Choose how the server package lays out its routes (experimen...
--server-model-package Name the import path of the models the server package import...
--server-operation-names Name the service methods of single operations (experimental)...
--server-output Write the server package to this directory (experimental).
--server-package Name the import path of the server package (experimental).
--server-parameter-names Name the method arguments of single operations (experimental...
--server-primary-responses Choose the response a bare return value of an operation take...
--server-router-names Name router groups (experimental).

--client-asyncapi-perspective

Read an AsyncAPI document as its server's or its client's (experimental).

With --input-file-type asyncapi, --generate-client opens each channel of a ws or wss server as client.<channel>.connect(...), a WebSocket session that sends one message type and receives another. server (the default) reads the document as the server's, as the AsyncAPI operations define it: the client sends what the server receives (AsyncAPI 2 publish, AsyncAPI 3 action: receive) and receives what it sends (subscribe, action: send). client reads the document as the client's and swaps the two. A server-sent event channel, which client.<channel>.open(...) opens, flows from the server only, so the client receives each of its messages whichever the option says. Other input types refuse the option.

Option relationships:

  • Requires: --generate-client - --client-asyncapi-perspective requires --generate-client httpx2.

Usage

datamodel-codegen --input asyncapi-market-v3.yaml --input-file-type asyncapi --output models.py --target-python-version 3.11 --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models --client-asyncapi-perspective client # (1)!
  1. --client-asyncapi-perspective - the option documented here
Examples

Input Schema:

asyncapi: 3.0.0
info:
  title: Market feed
  version: 1.0.0
servers:
  production:
    host: feed.example.com
    pathname: /ws
    protocol: wss
  sandbox:
    host: '{region}.sandbox.example.com'
    protocol: ws
    variables:
      region:
        default: eu
        enum: [eu, us]
  broker:
    host: kafka.example.com
    protocol: kafka
channels:
  market:
    address: /v1/market/{pair}
    servers:
      - $ref: '#/servers/production'
      - $ref: '#/servers/sandbox'
    parameters:
      pair:
        description: The trading pair.
    messages:
      subscribe:
        $ref: '#/components/messages/subscribe'
      trade:
        $ref: '#/components/messages/trade'
  ticker:
    address: /v1/ticker
    servers:
      - $ref: '#/servers/production'
    messages:
      tick:
        contentType: text/plain
        payload:
          type: string
  audio:
    address: /v1/audio
    servers:
      - $ref: '#/servers/production'
    messages:
      frame:
        contentType: application/octet-stream
        payload:
          type: string
          format: binary
      status:
        payload:
          type: object
          properties:
            level:
              type: integer
          required: [level]
  status:
    address: /v1/status
    messages:
      update:
        payload:
          $ref: '#/components/schemas/Status'
operations:
  onSubscribe:
    action: receive
    channel:
      $ref: '#/channels/market'
    messages:
      - $ref: '#/channels/market/messages/subscribe'
  publishTrade:
    action: send
    channel:
      $ref: '#/channels/market'
    messages:
      - $ref: '#/channels/market/messages/trade'
  publishTick:
    action: send
    channel:
      $ref: '#/channels/ticker'
  onFrame:
    action: receive
    channel:
      $ref: '#/channels/audio'
    messages:
      - $ref: '#/channels/audio/messages/frame'
  publishStatus:
    action: send
    channel:
      $ref: '#/channels/audio'
    messages:
      - $ref: '#/channels/audio/messages/status'
  publishStatusUpdate:
    action: send
    channel:
      $ref: '#/channels/status'
components:
  messages:
    subscribe:
      payload:
        $ref: '#/components/schemas/Subscribe'
    trade:
      contentType: application/json
      payload:
        $ref: '#/components/schemas/Trade'
  schemas:
    Subscribe:
      type: object
      properties:
        event:
          type: string
          const: subscribe
        channels:
          type: array
          items:
            type: string
      required: [event, channels]
    Trade:
      type: object
      properties:
        event:
          type: string
          const: trade
        price:
          type: number
        volume:
          type: number
      required: [event, price]
    Status:
      type: object
      properties:
        state:
          type: string
          enum: [online, maintenance]
      required: [state]

Output:

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

"""The plans of this package's WebSocket helpers; regenerate them instead of editing."""

from __future__ import annotations

from typing import Final, Never

import models

from .. import _operations
from .._generated import model_bindings
from .._runtime.protocols.references import OperationRef
from .._runtime.protocols.websocket import ChannelPlan

SOCKET_0: Final[ChannelPlan[models.Trade, models.Subscribe]] = ChannelPlan(
    helper_id='market',
    operation=OperationRef(pointer='/channels/market'),
    call=_operations.OPERATION_0,
    fingerprint='cab2f78a5d2490691e4c3dc1aa01e0e9d49f86d7743eb26c4c3c22a5b9f94aac',
    encoder=model_bindings.codec_1,
    decoder=model_bindings.codec_2,
)


SOCKET_1: Final[ChannelPlan[str, Never]] = ChannelPlan(
    helper_id='ticker',
    operation=OperationRef(pointer='/channels/ticker'),
    call=_operations.OPERATION_1,
    fingerprint='1f1c1a8a5c1eacfa751f7539271b43e84cfa608417dac548f70b8286076c4316',
    send_codec='utf8',
    receive_codec='none',
)


SOCKET_2: Final[ChannelPlan[models.AudioStatusPayload, bytes]] = ChannelPlan(
    helper_id='audio',
    operation=OperationRef(pointer='/channels/audio'),
    call=_operations.OPERATION_2,
    fingerprint='dd024ec23cc2efc79cac6778b3b14563fd39a7973685078a5ef7b1f077563a46',
    encoder=model_bindings.codec_3,
    receive_codec='bytes',
    receive_frame='binary',
)


SOCKET_3: Final[ChannelPlan[models.Status, Never]] = ChannelPlan(
    helper_id='status',
    operation=OperationRef(pointer='/channels/status'),
    call=_operations.OPERATION_3,
    fingerprint='1b8010c9f550b24a09e72e1f84b1fbcbcdf186ad031338a61795437e1469f1b9',
    encoder=model_bindings.codec_4,
    receive_codec='none',
)

--client-body-arguments

Choose how operation methods take request bodies (experimental).

body (the default) takes the body as one body argument; both also takes the properties of an object body as keyword arguments, so a call can pass either. The body_arguments of an operation in --client-operations overrides it for that operation.

Option relationships:

  • Requires: --generate-client - --client-body-arguments requires --generate-client httpx2.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models --client-body-arguments both # (1)!
  1. --client-body-arguments - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

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

"""The synchronous operations of the pets resource."""

from __future__ import annotations

from contextlib import AbstractContextManager
from functools import cached_property
from typing import Literal, overload

import models

from ... import _operations
from ..._runtime.client.client import ClientCore
from ...options import UNSET, RequestOptions
from ...responses import RawResponse, Response
from ...types.pets import CreatePetResponse, ListPetsResponse


class PetsResource:
    """The pets operations."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    @cached_property
    def with_response(self) -> PetsWithResponse:
        """The same operations, returning each result with its response metadata."""
        return PetsWithResponse(self._core)

    @cached_property
    def with_raw_response(self) -> PetsWithRawResponse:
        """The same operations, returning each raw response with its body read into memory."""
        return PetsWithRawResponse(self._core)

    @cached_property
    def with_streaming_response(self) -> PetsWithStreamingResponse:
        """The same operations, returning blocks that send each call on entry and stream its response."""
        return PetsWithStreamingResponse(self._core)

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> ListPetsResponse:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        ).data

    @overload
    def create_pet(
        self,
        *,
        body: models.NewPet,
        name: UNSET = UNSET,
        tag: UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> CreatePetResponse: ...
    @overload
    def create_pet(
        self,
        *,
        body: UNSET = UNSET,
        name: str,
        tag: str | UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> CreatePetResponse: ...
    def create_pet(
        self,
        *,
        body: models.NewPet | UNSET = UNSET,
        name: str | UNSET = UNSET,
        tag: str | UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> CreatePetResponse:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            fields=(name, tag),
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        ).data


class PetsWithResponse:
    """The pets operations, returning each result with its response metadata."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[ListPetsResponse]:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    @overload
    def create_pet(
        self,
        *,
        body: models.NewPet,
        name: UNSET = UNSET,
        tag: UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[CreatePetResponse]: ...
    @overload
    def create_pet(
        self,
        *,
        body: UNSET = UNSET,
        name: str,
        tag: str | UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[CreatePetResponse]: ...
    def create_pet(
        self,
        *,
        body: models.NewPet | UNSET = UNSET,
        name: str | UNSET = UNSET,
        tag: str | UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[CreatePetResponse]:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            fields=(name, tag),
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithRawResponse:
    """The pets operations, returning each raw response with its body read into memory."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call GET /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    @overload
    def create_pet(
        self,
        *,
        body: models.NewPet,
        name: UNSET = UNSET,
        tag: UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse: ...
    @overload
    def create_pet(
        self,
        *,
        body: UNSET = UNSET,
        name: str,
        tag: str | UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse: ...
    def create_pet(
        self,
        *,
        body: models.NewPet | UNSET = UNSET,
        name: str | UNSET = UNSET,
        tag: str | UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call POST /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_1,
            (),
            body=body,
            fields=(name, tag),
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithStreamingResponse:
    """The pets operations, returning blocks that send each call on entry and stream its response."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call GET /pets.
        """
        return self._core.stream(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    @overload
    def create_pet(
        self,
        *,
        body: models.NewPet,
        name: UNSET = UNSET,
        tag: UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]: ...
    @overload
    def create_pet(
        self,
        *,
        body: UNSET = UNSET,
        name: str,
        tag: str | UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]: ...
    def create_pet(
        self,
        *,
        body: models.NewPet | UNSET = UNSET,
        name: str | UNSET = UNSET,
        tag: str | UNSET = UNSET,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call POST /pets.
        """
        return self._core.stream(
            _operations.OPERATION_1,
            (),
            body=body,
            fields=(name, tag),
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )

--client-deep-object-brackets

Write deepObject values in brackets: a[]=v, a=v, a[k][k]=v (experimental).

OpenAPI defines style: deepObject for objects of scalars alone, so an operation whose deepObject query parameter, or member of an application/x-www-form-urlencoded body, takes an array, a scalar, a nested object or a union of a scalar and an object is left out with a warning. With this option the client writes such values in the bracket form: an array of scalars as name[]=value for each item, such as expand[]=a&expand[]=b, a scalar as name=value, the members of objects as name[key]=value at any depth, such as shipping[address][city]=Paris, and an array of objects by index, such as items[0][price]=p_1, with the brackets percent-encoded as those of an object's name[key] pairs are. A value that may be a scalar or an object or array is written as the one a call gives: created=5 or created[gt]=5, and an empty string as metadata=. Arrays of arrays, recursive values, and unions whose members a value does not tell apart stay left out. --no-client-deep-object-brackets turns off the client-deep-object-brackets key of pyproject.toml.

Option relationships:

  • Requires: --generate-client - --client-deep-object-brackets requires --generate-client httpx2.

Usage

datamodel-codegen --input options-deep-object.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models --client-deep-object-brackets # (1)!
  1. --client-deep-object-brackets - the option documented here
Examples

Input Schema:

openapi: 3.0.3
info:
  title: Charges
  version: 1.0.0
servers:
  - url: https://api.example.com
paths:
  /v1/charges/{charge}:
    get:
      operationId: GetChargesCharge
      tags: [charges]
      parameters:
        - {name: charge, in: path, required: true, schema: {type: string}}
        - name: expand
          in: query
          style: deepObject
          explode: true
          schema:
            type: array
            items: {type: string}
        - name: limit
          in: query
          style: deepObject
          explode: true
          schema: {type: integer}
        - name: created
          in: query
          style: deepObject
          explode: true
          schema:
            type: object
            properties:
              gt: {type: integer}
      responses:
        '204':
          description: The charge.

Output:

# generated by datamodel-codegen:
#   filename:  options-deep-object.yaml

"""The operation registry of this package; regenerate it instead of editing."""

from __future__ import annotations

from typing import Final

from ._generated import model_bindings
from ._runtime.client.operations import (
    OperationPlan,
    ParameterSpec,
    ResponseDecoder,
    ServerPlan,
    empty_branch,
)
from ._runtime.model_codecs.media import FieldPlan
from ._runtime.model_codecs.parameters import ParameterPlan
from .types.charges import GetChargesChargeResponse

_SERVERS_0: Final = (ServerPlan(url='https://api.example.com'),)

OPERATION_0: Final[OperationPlan[GetChargesChargeResponse]] = OperationPlan(
    operation_id='GetChargesCharge',
    method='GET',
    path='/v1/charges/{charge}',
    servers=_SERVERS_0,
    responses=ResponseDecoder((empty_branch('204'),), ()),
    parameters=(
        ParameterSpec(
            plan=ParameterPlan(
                location='path', name='charge', style='simple', required=True
            ),
            codec=model_bindings.codec_0,
        ),
        ParameterSpec(
            plan=ParameterPlan(
                location='query',
                name='expand',
                style='deepObject',
                explode=True,
                shape='array',
                brackets=True,
            ),
            codec=model_bindings.codec_1,
        ),
        ParameterSpec(
            plan=ParameterPlan(
                location='query',
                name='limit',
                style='deepObject',
                explode=True,
                kind='integer',
                brackets=True,
            ),
            codec=model_bindings.codec_2,
        ),
        ParameterSpec(
            plan=ParameterPlan(
                location='query',
                name='created',
                style='deepObject',
                explode=True,
                shape='object',
                fields=(FieldPlan('gt', 'integer'),),
                additional=FieldPlan('', 'string'),
                reserved_names=('expand', 'limit'),
                brackets=True,
            ),
            codec=model_bindings.codec_3,
        ),
    ),
)

--client-default-base-url

Set the server URL of operations that declare no servers (experimental).

An absolute http or https URL without userinfo, query, or fragment. Operations whose document and path declare servers keep them.

Option relationships:

  • Requires: --generate-client - --client-default-base-url requires --generate-client httpx2.

Usage

datamodel-codegen --input options-unserved.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models --client-default-base-url https://api.example.com/v1 # (1)!
  1. --client-default-base-url - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

# generated by datamodel-codegen:
#   filename:  options-unserved.yaml

"""The operation registry of this package; regenerate it instead of editing."""

from __future__ import annotations

from typing import Final

from ._generated import model_bindings
from ._runtime.client.operations import (
    BodyMedia,
    OperationPlan,
    ParameterSpec,
    RequestBody,
    ResponseDecoder,
    ServerPlan,
    model_branch,
)
from ._runtime.model_codecs.parameters import ParameterPlan
from .types.pets import CreatePetResponse, ListPetsResponse

_SERVERS_0: Final = (ServerPlan(url='https://api.example.com/v1'),)

OPERATION_0: Final[OperationPlan[ListPetsResponse]] = OperationPlan(
    operation_id='listPets',
    method='GET',
    path='/pets',
    servers=_SERVERS_0,
    responses=ResponseDecoder(
        (model_branch('200', 'application/json', 'json', model_bindings.codec_2),), ()
    ),
    parameters=(
        ParameterSpec(
            plan=ParameterPlan(
                location='query',
                name='limit',
                style='form',
                explode=True,
                kind='integer',
            ),
            codec=model_bindings.codec_0,
        ),
        ParameterSpec(
            plan=ParameterPlan(
                location='query', name='cursor', style='form', explode=True
            ),
            codec=model_bindings.codec_1,
        ),
    ),
)

OPERATION_1: Final[OperationPlan[CreatePetResponse]] = OperationPlan(
    operation_id='createPet',
    method='POST',
    path='/pets',
    servers=_SERVERS_0,
    responses=ResponseDecoder(
        (model_branch('201', 'application/json', 'json', model_bindings.codec_4),), ()
    ),
    body=RequestBody(
        media=(
            BodyMedia(
                media_type='application/json', kind='json', codec=model_bindings.codec_3
            ),
        ),
        default='application/json',
        required=True,
    ),
)

--client-model-package

Name the import path of the models the client package imports (experimental).

--client-model-package is required with --generate-client, and names the module or package --output generates.

Option relationships:

  • Requires: --generate-client - --client-model-package requires --generate-client httpx2.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models # (1)!
  1. --client-model-package - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

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

"""The synchronous operations of the pets resource."""

from __future__ import annotations

from contextlib import AbstractContextManager
from functools import cached_property
from typing import Literal

import models

from ... import _operations
from ..._runtime.client.client import ClientCore
from ...options import UNSET, RequestOptions
from ...responses import RawResponse, Response
from ...types.pets import CreatePetResponse, ListPetsResponse


class PetsResource:
    """The pets operations."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    @cached_property
    def with_response(self) -> PetsWithResponse:
        """The same operations, returning each result with its response metadata."""
        return PetsWithResponse(self._core)

    @cached_property
    def with_raw_response(self) -> PetsWithRawResponse:
        """The same operations, returning each raw response with its body read into memory."""
        return PetsWithRawResponse(self._core)

    @cached_property
    def with_streaming_response(self) -> PetsWithStreamingResponse:
        """The same operations, returning blocks that send each call on entry and stream its response."""
        return PetsWithStreamingResponse(self._core)

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> ListPetsResponse:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        ).data

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> CreatePetResponse:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        ).data


class PetsWithResponse:
    """The pets operations, returning each result with its response metadata."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[ListPetsResponse]:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[CreatePetResponse]:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithRawResponse:
    """The pets operations, returning each raw response with its body read into memory."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call GET /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call POST /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithStreamingResponse:
    """The pets operations, returning blocks that send each call on entry and stream its response."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call GET /pets.
        """
        return self._core.stream(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call POST /pets.
        """
        return self._core.stream(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )

--client-operations

Set the client settings of single operations (experimental).

The JSON object, inline or in a file, maps operation references to their settings. An operation reference is the JSON pointer of the path item method, such as /paths/~1pets/get, optionally after a document and #, such as pets.yaml#/paths/~1pets/get. A relative document resolves against the JSON file that holds the reference, or without a file against the working directory, and against the pyproject.toml directory for a table. The settings are resource, name, parameter_names (keyed by location and name, such as {"query:limit": "page_size"}), request_media_type, response_media_type, description, body_arguments, which overrides --client-body-arguments, body_field_names (keyed by media type, then property, such as {"application/json": {"petName": "pet_name"}}), and runtime: request_id_header, success_statuses, retry_safety, idempotency ({"header_name": "Idempotency-Key"}), retry_after_ms_header, should_retry_header, auth_challenge_less_401, and accepted_content_encodings. In pyproject.toml, client-operations is a table, and a command-line value replaces the whole table.

Option relationships:

  • Requires: --generate-client - --client-operations requires --generate-client httpx2.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models --client-operations '{"/paths/~1pets/get": {"name": "list_all", "parameter_names": {"query:limit": "page_size"}}}' # (1)!
  1. --client-operations - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

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

"""The synchronous operations of the pets resource."""

from __future__ import annotations

from contextlib import AbstractContextManager
from functools import cached_property
from typing import Literal

import models

from ... import _operations
from ..._runtime.client.client import ClientCore
from ...options import UNSET, RequestOptions
from ...responses import RawResponse, Response
from ...types.pets import CreatePetResponse, ListAllResponse


class PetsResource:
    """The pets operations."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    @cached_property
    def with_response(self) -> PetsWithResponse:
        """The same operations, returning each result with its response metadata."""
        return PetsWithResponse(self._core)

    @cached_property
    def with_raw_response(self) -> PetsWithRawResponse:
        """The same operations, returning each raw response with its body read into memory."""
        return PetsWithRawResponse(self._core)

    @cached_property
    def with_streaming_response(self) -> PetsWithStreamingResponse:
        """The same operations, returning blocks that send each call on entry and stream its response."""
        return PetsWithStreamingResponse(self._core)

    def list_all(
        self,
        *,
        page_size: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> ListAllResponse:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (page_size, cursor),
            options=options,
            response_media_type=response_media_type,
        ).data

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> CreatePetResponse:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        ).data


class PetsWithResponse:
    """The pets operations, returning each result with its response metadata."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_all(
        self,
        *,
        page_size: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[ListAllResponse]:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (page_size, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[CreatePetResponse]:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithRawResponse:
    """The pets operations, returning each raw response with its body read into memory."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_all(
        self,
        *,
        page_size: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call GET /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_0,
            (page_size, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call POST /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithStreamingResponse:
    """The pets operations, returning blocks that send each call on entry and stream its response."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_all(
        self,
        *,
        page_size: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call GET /pets.
        """
        return self._core.stream(
            _operations.OPERATION_0,
            (page_size, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call POST /pets.
        """
        return self._core.stream(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )

--client-output

Write the client package to this directory (experimental).

--client-output is required with --generate-client. A path given on the command line is relative to the working directory, and the client-output key of pyproject.toml is relative to the pyproject.toml directory, as for --output.

Option relationships:

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models # (1)!
  1. --client-output - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

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

"""The synchronous operations of the pets resource."""

from __future__ import annotations

from contextlib import AbstractContextManager
from functools import cached_property
from typing import Literal

import models

from ... import _operations
from ..._runtime.client.client import ClientCore
from ...options import UNSET, RequestOptions
from ...responses import RawResponse, Response
from ...types.pets import CreatePetResponse, ListPetsResponse


class PetsResource:
    """The pets operations."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    @cached_property
    def with_response(self) -> PetsWithResponse:
        """The same operations, returning each result with its response metadata."""
        return PetsWithResponse(self._core)

    @cached_property
    def with_raw_response(self) -> PetsWithRawResponse:
        """The same operations, returning each raw response with its body read into memory."""
        return PetsWithRawResponse(self._core)

    @cached_property
    def with_streaming_response(self) -> PetsWithStreamingResponse:
        """The same operations, returning blocks that send each call on entry and stream its response."""
        return PetsWithStreamingResponse(self._core)

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> ListPetsResponse:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        ).data

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> CreatePetResponse:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        ).data


class PetsWithResponse:
    """The pets operations, returning each result with its response metadata."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[ListPetsResponse]:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[CreatePetResponse]:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithRawResponse:
    """The pets operations, returning each raw response with its body read into memory."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call GET /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call POST /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithStreamingResponse:
    """The pets operations, returning blocks that send each call on entry and stream its response."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call GET /pets.
        """
        return self._core.stream(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call POST /pets.
        """
        return self._core.stream(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )

--client-package

Name the import path of the client package (experimental).

--client-package is required with --generate-client. The generated README and the dependency command a generation prints name the package by it; the package imports its own modules relatively.

Option relationships:

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models # (1)!
  1. --client-package - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

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

"""The synchronous operations of the pets resource."""

from __future__ import annotations

from contextlib import AbstractContextManager
from functools import cached_property
from typing import Literal

import models

from ... import _operations
from ..._runtime.client.client import ClientCore
from ...options import UNSET, RequestOptions
from ...responses import RawResponse, Response
from ...types.pets import CreatePetResponse, ListPetsResponse


class PetsResource:
    """The pets operations."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    @cached_property
    def with_response(self) -> PetsWithResponse:
        """The same operations, returning each result with its response metadata."""
        return PetsWithResponse(self._core)

    @cached_property
    def with_raw_response(self) -> PetsWithRawResponse:
        """The same operations, returning each raw response with its body read into memory."""
        return PetsWithRawResponse(self._core)

    @cached_property
    def with_streaming_response(self) -> PetsWithStreamingResponse:
        """The same operations, returning blocks that send each call on entry and stream its response."""
        return PetsWithStreamingResponse(self._core)

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> ListPetsResponse:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        ).data

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> CreatePetResponse:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        ).data


class PetsWithResponse:
    """The pets operations, returning each result with its response metadata."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[ListPetsResponse]:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[CreatePetResponse]:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithRawResponse:
    """The pets operations, returning each raw response with its body read into memory."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call GET /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call POST /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithStreamingResponse:
    """The pets operations, returning blocks that send each call on entry and stream its response."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call GET /pets.
        """
        return self._core.stream(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call POST /pets.
        """
        return self._core.stream(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )

--client-protocols

Declare the protocol helpers of the client package (experimental).

The JSON object, inline or in a file, maps each helper's name to the definition of a pagination, polling, stream, WebSocket, cache, upload, or webhook helper, as the Python client guide describes. Relative documents that its references name resolve against the directory of the JSON file that holds them, on the command line and for the client-protocols key alike. For inline JSON they resolve against the working directory, and for a table of the client-protocols key against the pyproject.toml directory.

Option relationships:

  • Requires: --generate-client - --client-protocols requires --generate-client httpx2.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models --client-protocols protocols.json # (1)!
  1. --client-protocols - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

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

"""The synchronous protocol helpers of this package, by their dotted names."""

from __future__ import annotations

from functools import cached_property

import models

from .._runtime.client.client import ClientCore as ClientCore_1
from .._runtime.model_codecs.media import JSONValue
from .._runtime.protocols.client import ClientCore
from .._runtime.protocols.pagination import (
    Page,
    Pager,
    first_page,
    following_page,
    iterate_pages,
    resume_pages,
)
from ..options import UNSET, RequestOptions
from ..types.pets import ListPetsResponse
from . import PaginationOptions, _plans


class ProtocolHelpers:
    """The protocol helpers of this API."""

    def __init__(self, core: ClientCore_1) -> None:
        """Keep the client core its helpers send through."""
        self._core = ClientCore.from_client(core)

    @cached_property
    def pets(self) -> PetsProtocols:
        """The pets protocol helpers."""
        return PetsProtocols(self._core)


class PetsProtocols:
    """The pets protocol helpers."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core its helpers send through."""
        self._core = core

    @cached_property
    def all(self) -> PetsAllPagination:
        """The pets.all pagination helper."""
        return PetsAllPagination(self._core)


class PetsAllPagination:
    """The pets.all pagination helper of GET /pets."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the helper sends through."""
        self._core = core

    def page(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        pagination_options: PaginationOptions | None = None,
        options: RequestOptions | None = None,
    ) -> Page[models.Pet, ListPetsResponse]:
        """Fetch the first page of GET /pets."""
        return first_page(
            self._core,
            _plans.PLAN_0,
            (limit, cursor),
            pagination_options=pagination_options,
            options=options,
        )

    def iterate(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        pagination_options: PaginationOptions | None = None,
        options: RequestOptions | None = None,
    ) -> Pager[models.Pet, ListPetsResponse]:
        """Return a pager over the items of GET /pets; it sends nothing until it is iterated."""
        return iterate_pages(
            self._core,
            _plans.PLAN_0,
            (limit, cursor),
            pagination_options=pagination_options,
            options=options,
        )

    def next_page(
        self,
        page: Page[models.Pet, ListPetsResponse],
        *,
        pagination_options: PaginationOptions | None = None,
        options: RequestOptions | None = None,
    ) -> Page[models.Pet, ListPetsResponse] | None:
        """Fetch the page after a page of this helper, or return None after the last page."""
        return following_page(
            self._core,
            _plans.PLAN_0,
            page,
            pagination_options=pagination_options,
            options=options,
        )

    def resume(
        self,
        state: JSONValue,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        pagination_options: PaginationOptions | None = None,
        options: RequestOptions | None = None,
    ) -> Pager[models.Pet, ListPetsResponse]:
        """Return a pager continuing a checkpoint; it sends nothing until it is iterated."""
        return resume_pages(
            self._core,
            _plans.PLAN_0,
            state,
            (limit, cursor),
            pagination_options=pagination_options,
            options=options,
        )

--client-resource-names

Name the resources of tags (experimental).

The JSON object, inline or in a file, maps a tag to the dotted namespace of the resource its operations join, such as {"pets": "store.pets"} for client.store.pets. Other operations join the resource of their first tag, and operations without a tag join the resource default. In pyproject.toml, client-resource-names is a table, and a command-line value replaces the whole table.

Option relationships:

  • Requires: --generate-client - --client-resource-names requires --generate-client httpx2.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models --client-resource-names '{"pets": "animals"}' # (1)!
  1. --client-resource-names - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

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

"""The synchronous operations of the animals resource."""

from __future__ import annotations

from contextlib import AbstractContextManager
from functools import cached_property
from typing import Literal

import models

from ... import _operations
from ..._runtime.client.client import ClientCore
from ...options import UNSET, RequestOptions
from ...responses import RawResponse, Response
from ...types.animals import CreatePetResponse, ListPetsResponse


class AnimalsResource:
    """The animals operations."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    @cached_property
    def with_response(self) -> AnimalsWithResponse:
        """The same operations, returning each result with its response metadata."""
        return AnimalsWithResponse(self._core)

    @cached_property
    def with_raw_response(self) -> AnimalsWithRawResponse:
        """The same operations, returning each raw response with its body read into memory."""
        return AnimalsWithRawResponse(self._core)

    @cached_property
    def with_streaming_response(self) -> AnimalsWithStreamingResponse:
        """The same operations, returning blocks that send each call on entry and stream its response."""
        return AnimalsWithStreamingResponse(self._core)

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> ListPetsResponse:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        ).data

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> CreatePetResponse:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        ).data


class AnimalsWithResponse:
    """The animals operations, returning each result with its response metadata."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[ListPetsResponse]:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[CreatePetResponse]:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class AnimalsWithRawResponse:
    """The animals operations, returning each raw response with its body read into memory."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call GET /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call POST /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class AnimalsWithStreamingResponse:
    """The animals operations, returning blocks that send each call on entry and stream its response."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call GET /pets.
        """
        return self._core.stream(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call POST /pets.
        """
        return self._core.stream(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )

--client-server-base-url

Resolve relative server URLs against this base URL (experimental).

An absolute http or https URL without userinfo, query, or fragment. Without it, relative server URLs resolve against the document's URL when it is read from one.

Option relationships:

  • Requires: --generate-client - --client-server-base-url requires --generate-client httpx2.

Usage

datamodel-codegen --input options-relative.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models --client-server-base-url https://api.example.com/ # (1)!
  1. --client-server-base-url - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
servers:
  - url: /v1
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

# generated by datamodel-codegen:
#   filename:  options-relative.yaml

"""The operation registry of this package; regenerate it instead of editing."""

from __future__ import annotations

from typing import Final

from ._generated import model_bindings
from ._runtime.client.operations import (
    BodyMedia,
    OperationPlan,
    ParameterSpec,
    RequestBody,
    ResponseDecoder,
    ServerPlan,
    model_branch,
)
from ._runtime.model_codecs.parameters import ParameterPlan
from .types.pets import CreatePetResponse, ListPetsResponse

_SERVERS_0: Final = (ServerPlan(url='https://api.example.com/v1'),)

OPERATION_0: Final[OperationPlan[ListPetsResponse]] = OperationPlan(
    operation_id='listPets',
    method='GET',
    path='/pets',
    servers=_SERVERS_0,
    responses=ResponseDecoder(
        (model_branch('200', 'application/json', 'json', model_bindings.codec_2),), ()
    ),
    parameters=(
        ParameterSpec(
            plan=ParameterPlan(
                location='query',
                name='limit',
                style='form',
                explode=True,
                kind='integer',
            ),
            codec=model_bindings.codec_0,
        ),
        ParameterSpec(
            plan=ParameterPlan(
                location='query', name='cursor', style='form', explode=True
            ),
            codec=model_bindings.codec_1,
        ),
    ),
)

OPERATION_1: Final[OperationPlan[CreatePetResponse]] = OperationPlan(
    operation_id='createPet',
    method='POST',
    path='/pets',
    servers=_SERVERS_0,
    responses=ResponseDecoder(
        (model_branch('201', 'application/json', 'json', model_bindings.codec_4),), ()
    ),
    body=RequestBody(
        media=(
            BodyMedia(
                media_type='application/json', kind='json', codec=model_bindings.codec_3
            ),
        ),
        default='application/json',
        required=True,
    ),
)

--client-signature-style

Declare the arguments of the operation methods (experimental).

explicit (the default) declares each argument as a keyword parameter; unpack declares **kwargs: Unpack[TypedDict] with one TypedDict per overload of each operation, whose keys are the same arguments.

Option relationships:

  • Requires: --generate-client - --client-signature-style requires --generate-client httpx2.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models --client-signature-style unpack # (1)!
  1. --client-signature-style - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

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

"""The synchronous operations of the pets resource."""

from __future__ import annotations

from contextlib import AbstractContextManager
from functools import cached_property

from typing_extensions import Unpack

from ... import _operations
from ..._generated.client_arguments import (
    KEYWORDS_0,
    KEYWORDS_1,
    Operation0Arguments,
    Operation1Arguments,
)
from ..._runtime.client.client import ClientCore
from ...options import UNSET
from ...responses import RawResponse, Response
from ...types.pets import CreatePetResponse, ListPetsResponse


class PetsResource:
    """The pets operations."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    @cached_property
    def with_response(self) -> PetsWithResponse:
        """The same operations, returning each result with its response metadata."""
        return PetsWithResponse(self._core)

    @cached_property
    def with_raw_response(self) -> PetsWithRawResponse:
        """The same operations, returning each raw response with its body read into memory."""
        return PetsWithRawResponse(self._core)

    @cached_property
    def with_streaming_response(self) -> PetsWithStreamingResponse:
        """The same operations, returning blocks that send each call on entry and stream its response."""
        return PetsWithStreamingResponse(self._core)

    def list_pets(
        self,
        **kwargs: Unpack[Operation0Arguments],
    ) -> ListPetsResponse:
        """
        Call GET /pets.
        """
        KEYWORDS_0.check(kwargs)
        return self._core.execute(
            _operations.OPERATION_0,
            (kwargs.get('limit', UNSET), kwargs.get('cursor', UNSET)),
            options=kwargs.get('options'),
            response_media_type=kwargs.get('response_media_type'),
        ).data

    def create_pet(
        self,
        **kwargs: Unpack[Operation1Arguments],
    ) -> CreatePetResponse:
        """
        Call POST /pets.
        """
        KEYWORDS_1.check(kwargs)
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=kwargs['body'],
            media_type=kwargs.get('media_type'),
            options=kwargs.get('options'),
            response_media_type=kwargs.get('response_media_type'),
        ).data


class PetsWithResponse:
    """The pets operations, returning each result with its response metadata."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        **kwargs: Unpack[Operation0Arguments],
    ) -> Response[ListPetsResponse]:
        """
        Call GET /pets.
        """
        KEYWORDS_0.check(kwargs)
        return self._core.execute(
            _operations.OPERATION_0,
            (kwargs.get('limit', UNSET), kwargs.get('cursor', UNSET)),
            options=kwargs.get('options'),
            response_media_type=kwargs.get('response_media_type'),
        )

    def create_pet(
        self,
        **kwargs: Unpack[Operation1Arguments],
    ) -> Response[CreatePetResponse]:
        """
        Call POST /pets.
        """
        KEYWORDS_1.check(kwargs)
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=kwargs['body'],
            media_type=kwargs.get('media_type'),
            options=kwargs.get('options'),
            response_media_type=kwargs.get('response_media_type'),
        )


class PetsWithRawResponse:
    """The pets operations, returning each raw response with its body read into memory."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        **kwargs: Unpack[Operation0Arguments],
    ) -> RawResponse:
        """
        Call GET /pets.
        """
        KEYWORDS_0.check(kwargs)
        return self._core.execute_raw(
            _operations.OPERATION_0,
            (kwargs.get('limit', UNSET), kwargs.get('cursor', UNSET)),
            options=kwargs.get('options'),
            response_media_type=kwargs.get('response_media_type'),
        )

    def create_pet(
        self,
        **kwargs: Unpack[Operation1Arguments],
    ) -> RawResponse:
        """
        Call POST /pets.
        """
        KEYWORDS_1.check(kwargs)
        return self._core.execute_raw(
            _operations.OPERATION_1,
            (),
            body=kwargs['body'],
            media_type=kwargs.get('media_type'),
            options=kwargs.get('options'),
            response_media_type=kwargs.get('response_media_type'),
        )


class PetsWithStreamingResponse:
    """The pets operations, returning blocks that send each call on entry and stream its response."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        **kwargs: Unpack[Operation0Arguments],
    ) -> AbstractContextManager[RawResponse]:
        """
        Call GET /pets.
        """
        KEYWORDS_0.check(kwargs)
        return self._core.stream(
            _operations.OPERATION_0,
            (kwargs.get('limit', UNSET), kwargs.get('cursor', UNSET)),
            options=kwargs.get('options'),
            response_media_type=kwargs.get('response_media_type'),
        )

    def create_pet(
        self,
        **kwargs: Unpack[Operation1Arguments],
    ) -> AbstractContextManager[RawResponse]:
        """
        Call POST /pets.
        """
        KEYWORDS_1.check(kwargs)
        return self._core.stream(
            _operations.OPERATION_1,
            (),
            body=kwargs['body'],
            media_type=kwargs.get('media_type'),
            options=kwargs.get('options'),
            response_media_type=kwargs.get('response_media_type'),
        )

--generate-client

Generate an HTTPX2 client package for the models (experimental).

--generate-client httpx2 generates the models of an OpenAPI document as usual and, in the same run, an HTTPX2 client package at --client-output: a Client and an AsyncClient with a resource for each tag and a method for each operation. The models need the api scope (--openapi-scopes schemas api) and a target Python version of 3.11 or later. Like every client setting, it can also be set in [tool.datamodel-codegen] of pyproject.toml, here as generate-client = "httpx2". It cannot be used with --generate-server.

Option relationships:

  • Requires: --client-output - --generate-client requires --client-output.
  • Requires: --client-package - --generate-client requires --client-package.
  • Requires: --client-model-package - --generate-client requires --client-model-package.
  • Requires: --input-file-type - --generate-client requires --input-file-type openapi or --input-file-type asyncapi.
  • Conflicts: --generate-server - --generate-client can not be used with --generate-server.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-client httpx2 --client-output client --client-package client --client-model-package models # (1)!
  1. --generate-client - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info:
  title: Pets
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      summary: List the pets.
      parameters:
        - name: limit
          in: query
          schema: {type: integer}
        - name: cursor
          in: query
          schema: {type: string}
      responses:
        '200':
          description: A page of pets.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pets'}
    post:
      operationId: createPet
      tags: [pets]
      summary: Create a pet.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NewPet'}
      responses:
        '201':
          description: The created pet.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pet'}
components:
  schemas:
    NewPet:
      type: object
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string}
        tag: {type: string}
    Pets:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Pet'}
        next_cursor: {type: [string, 'null']}

Output:

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

"""The synchronous operations of the pets resource."""

from __future__ import annotations

from contextlib import AbstractContextManager
from functools import cached_property
from typing import Literal

import models

from ... import _operations
from ..._runtime.client.client import ClientCore
from ...options import UNSET, RequestOptions
from ...responses import RawResponse, Response
from ...types.pets import CreatePetResponse, ListPetsResponse


class PetsResource:
    """The pets operations."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    @cached_property
    def with_response(self) -> PetsWithResponse:
        """The same operations, returning each result with its response metadata."""
        return PetsWithResponse(self._core)

    @cached_property
    def with_raw_response(self) -> PetsWithRawResponse:
        """The same operations, returning each raw response with its body read into memory."""
        return PetsWithRawResponse(self._core)

    @cached_property
    def with_streaming_response(self) -> PetsWithStreamingResponse:
        """The same operations, returning blocks that send each call on entry and stream its response."""
        return PetsWithStreamingResponse(self._core)

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> ListPetsResponse:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        ).data

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> CreatePetResponse:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        ).data


class PetsWithResponse:
    """The pets operations, returning each result with its response metadata."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[ListPetsResponse]:
        """
        Call GET /pets.
        """
        return self._core.execute(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> Response[CreatePetResponse]:
        """
        Call POST /pets.
        """
        return self._core.execute(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithRawResponse:
    """The pets operations, returning each raw response with its body read into memory."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call GET /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> RawResponse:
        """
        Call POST /pets.
        """
        return self._core.execute_raw(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )


class PetsWithStreamingResponse:
    """The pets operations, returning blocks that send each call on entry and stream its response."""

    def __init__(self, core: ClientCore) -> None:
        """Keep the client core the operations send through."""
        self._core = core

    def list_pets(
        self,
        *,
        limit: int | UNSET = UNSET,
        cursor: str | UNSET = UNSET,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call GET /pets.
        """
        return self._core.stream(
            _operations.OPERATION_0,
            (limit, cursor),
            options=options,
            response_media_type=response_media_type,
        )

    def create_pet(
        self,
        *,
        body: models.NewPet,
        media_type: Literal['application/json'] | None = None,
        response_media_type: Literal['application/json'] | None = None,
        options: RequestOptions | None = None,
    ) -> AbstractContextManager[RawResponse]:
        """
        Call POST /pets.
        """
        return self._core.stream(
            _operations.OPERATION_1,
            (),
            body=body,
            media_type=media_type,
            options=options,
            response_media_type=response_media_type,
        )

--generate-server

Generate a FastAPI server package for the models (experimental).

--generate-server fastapi generates the models of an OpenAPI document as usual and, in the same run, a FastAPI server package at --server-output: routers, a service Protocol for each router group, and the application. The models need the api scope (--openapi-scopes schemas api), a Pydantic v2 output model type, and a target Python version of 3.11 or later. Like every server setting, it can also be set in [tool.datamodel-codegen] of pyproject.toml, here as generate-server = "fastapi".

Option relationships:

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models # (1)!
  1. --generate-server - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_pets(
        self,
        *,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    def create_pet(
        self,
        *,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        name: str,
        body: models.Pet,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-body-mode

Choose how service methods receive request bodies (experimental).

typed (the default) passes the body validated as its model; request passes the raw Starlette Request instead, for methods that read the body themselves. --server-body-modes overrides it for single operations.

Option relationships:

  • Requires: --generate-server - --server-body-mode requires --generate-server fastapi.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models --server-body-mode request # (1)!
  1. --server-body-mode - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi import Request
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_pets(
        self,
        *,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    def create_pet(
        self,
        *,
        request: Request,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        request: Request,
        name: str,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-body-modes

Set the body mode of single operations (experimental).

The JSON object, inline or in a file, maps operation references to typed or request, and overrides --server-body-mode for those operations. A relative document of an operation reference resolves against the JSON file that holds the reference, or without a file against the working directory, and against the pyproject.toml directory for a table.

Option relationships:

  • Requires: --generate-server - --server-body-modes requires --generate-server fastapi.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models --server-body-modes '{"/paths/~1pets~1{name}/put": "request"}' # (1)!
  1. --server-body-modes - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi import Request
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_pets(
        self,
        *,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    def create_pet(
        self,
        *,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        request: Request,
        name: str,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-handler-mode

Declare the service methods as plain or coroutine functions (experimental).

sync (the default) declares plain methods, which FastAPI runs in a thread pool; async declares coroutine methods. --server-handler-modes overrides it for single operations.

Option relationships:

  • Requires: --generate-server - --server-handler-mode requires --generate-server fastapi.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models --server-handler-mode async # (1)!
  1. --server-handler-mode - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    async def list_pets(
        self,
        *,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    async def create_pet(
        self,
        *,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    async def replace_pet(
        self,
        *,
        name: str,
        body: models.Pet,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-handler-modes

Set the handler mode of single operations (experimental).

The JSON object, inline or in a file, maps operation references to sync or async, and overrides --server-handler-mode for those operations. An operation reference is the JSON pointer of the path item method, such as /paths/~1pets/get, optionally after a document and #, such as pets.yaml#/paths/~1pets/get. A relative document of an operation reference resolves against the JSON file that holds the reference, or without a file against the working directory, and against the pyproject.toml directory for a table. In pyproject.toml, server-handler-modes is a table, and a command-line value replaces the whole table.

Option relationships:

  • Requires: --generate-server - --server-handler-modes requires --generate-server fastapi.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models --server-handler-modes '{"/paths/~1pets/post": "async"}' # (1)!
  1. --server-handler-modes - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_pets(
        self,
        *,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    async def create_pet(
        self,
        *,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        name: str,
        body: models.Pet,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-include-request

Pass the Starlette Request to every service method (experimental).

Each service method takes a request keyword argument as well as the operation's arguments. --no-server-include-request turns off a server-include-request = true of pyproject.toml.

Option relationships:

  • Requires: --generate-server - --server-include-request requires --generate-server fastapi.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models --server-include-request # (1)!
  1. --server-include-request - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi import Request
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_pets(
        self,
        *,
        request: Request,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    def create_pet(
        self,
        *,
        request: Request,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        request: Request,
        name: str,
        body: models.Pet,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-layout

Choose how the server package lays out its routes (experimental).

routers (the default) writes one router module per tag under routers/; single writes every route to one routes.py module.

Option relationships:

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models --server-layout single # (1)!
  1. --server-layout - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Endpoints of every operation; regenerate them instead of editing."""

from collections.abc import Sequence
from typing import Annotated, Final

import models
from fastapi import APIRouter, Body, Path, Query, params
from fastapi.responses import Response

from ._generated import contract
from ._generated.contract import OperationDependencies
from ._runtime.server.application import Wiring, build, checked
from ._runtime.server.responses import dispatch
from .services import Service


def _add_list_pets(
    router: APIRouter,
    wiring: Wiring,
) -> None:
    service: Service = wiring.services['service']
    list_pets_handler = checked(
        service.list_pets,
        'The service.list_pets method of GET /pets',
        ('limit',),
    )

    def list_pets(
        *,
        limit: Annotated[int, Query(alias='limit')] = 20,
    ) -> object:
        return dispatch(
            list_pets_handler(
                limit=limit,
            ),
            contract.ListPets.RESPONSES,
        )

    router.add_api_route(
        '/pets',
        list_pets,
        methods=['GET'],
        status_code=200,
        response_model=models.PetsGetResponse,
        response_model_by_alias=True,
        response_model_exclude_unset=True,
        operation_id='listPets',
        tags=['pets'],
        response_description='The pets.',
        dependencies=wiring.dependencies.get('list_pets'),
    )


def _add_create_pet(
    router: APIRouter,
    wiring: Wiring,
) -> None:
    service: Service = wiring.services['service']
    create_pet_handler = checked(
        service.create_pet,
        'The service.create_pet method of POST /pets',
        ('body',),
    )

    def create_pet(
        *,
        body: Annotated[models.Pet, Body(media_type='application/json')],
    ) -> object:
        return dispatch(
            create_pet_handler(
                body=body,
            ),
            contract.CreatePet.RESPONSES,
        )

    router.add_api_route(
        '/pets',
        create_pet,
        methods=['POST'],
        status_code=200,
        response_model=models.Pet,
        response_model_by_alias=True,
        response_model_exclude_unset=True,
        operation_id='createPet',
        tags=['pets'],
        response_description='Already there.',
        dependencies=wiring.dependencies.get('create_pet'),
    )


def _add_replace_pet(
    router: APIRouter,
    wiring: Wiring,
) -> None:
    service: Service = wiring.services['service']
    replace_pet_handler = checked(
        service.replace_pet,
        'The service.replace_pet method of PUT /pets/{name}',
        ('name', 'body'),
    )

    def replace_pet(
        *,
        name: Annotated[str, Path(alias='name')],
        body: Annotated[models.Pet, Body(media_type='application/json')],
    ) -> object:
        return dispatch(
            replace_pet_handler(
                name=name,
                body=body,
            ),
            contract.ReplacePet.RESPONSES,
        )

    router.add_api_route(
        '/pets/{name}',
        replace_pet,
        methods=['PUT'],
        status_code=204,
        response_model=None,
        response_class=Response,
        operation_id='replacePet',
        tags=['pets'],
        response_description='Replaced.',
        dependencies=wiring.dependencies.get('replace_pet'),
    )


LITERAL_ROUTES: Final = (
    ('list_pets', _add_list_pets),
    ('create_pet', _add_create_pet),
)
TEMPLATED_ROUTES: Final = (('replace_pet', _add_replace_pet),)


def build_router(
    *,
    service: Service,
    dependencies: Sequence[params.Depends] = (),
    operation_dependencies: OperationDependencies | None = None,
    prefix: str = "",
) -> APIRouter:
    """Register every operation on a new router, literal paths first."""
    return build(
        (*LITERAL_ROUTES, *TEMPLATED_ROUTES),
        services={'service': service},
        dependencies=dependencies,
        operation_dependencies=operation_dependencies,
        prefix=prefix,
    )

--server-model-package

Name the import path of the models the server package imports (experimental).

--server-model-package is required with --generate-server, and names the module or package --output generates.

Option relationships:

  • Requires: --generate-server - --server-model-package requires --generate-server fastapi.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models # (1)!
  1. --server-model-package - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_pets(
        self,
        *,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    def create_pet(
        self,
        *,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        name: str,
        body: models.Pet,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-operation-names

Name the service methods of single operations (experimental).

The JSON object, inline or in a file, maps operation references to method names. Other operations take the snake_case form of their operationId, or of their method and path. A relative document of an operation reference resolves against the JSON file that holds the reference, or without a file against the working directory, and against the pyproject.toml directory for a table.

Option relationships:

  • Requires: --generate-server - --server-operation-names requires --generate-server fastapi.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models --server-operation-names '{"/paths/~1pets/get": "list_all"}' # (1)!
  1. --server-operation-names - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_all(
        self,
        *,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    def create_pet(
        self,
        *,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        name: str,
        body: models.Pet,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-output

Write the server package to this directory (experimental).

--server-output is required with --generate-server. A path given on the command line is relative to the working directory, and the server-output key of pyproject.toml is relative to the pyproject.toml directory, as for --output.

Option relationships:

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models # (1)!
  1. --server-output - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_pets(
        self,
        *,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    def create_pet(
        self,
        *,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        name: str,
        body: models.Pet,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-package

Name the import path of the server package (experimental).

--server-package is required with --generate-server. The generated README and the dependency command a generation prints name the package by it; the package imports its own modules relatively.

Option relationships:

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models # (1)!
  1. --server-package - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_pets(
        self,
        *,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    def create_pet(
        self,
        *,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        name: str,
        body: models.Pet,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-parameter-names

Name the method arguments of single operations (experimental).

The JSON object, inline or in a file, maps operation references to objects that map a parameter, written as its location and name such as query:limit or header:X-Request-Id, to the argument name. A relative document of an operation reference resolves against the JSON file that holds the reference, or without a file against the working directory, and against the pyproject.toml directory for a table.

Option relationships:

  • Requires: --generate-server - --server-parameter-names requires --generate-server fastapi.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models --server-parameter-names '{"/paths/~1pets/get": {"query:limit": "page_size"}}' # (1)!
  1. --server-parameter-names - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class PetsService(Protocol):
    """Implement the pets operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_pets(
        self,
        *,
        page_size: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    def create_pet(
        self,
        *,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        name: str,
        body: models.Pet,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """

--server-primary-responses

Choose the response a bare return value of an operation takes (experimental).

The JSON object, inline or in a file, maps operation references to an object with a status_code and, when the response has several media types, its media_type. The status_code takes the response that declares that status exactly, by its range such as 2XX, or as default. Without an entry, the primary response is 200 when the operation declares it, or else its lowest success status, or else its 2XX or else its default response, sent as 200, or else its lowest status; an operation that declares only other ranges, such as 4XX, has none. A relative document of an operation reference resolves against the JSON file that holds the reference, or without a file against the working directory, and against the pyproject.toml directory for a table.

Option relationships:

  • Requires: --generate-server - --server-primary-responses requires --generate-server fastapi.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models --server-primary-responses '{"/paths/~1pets/post": {"status_code": 201}}' # (1)!
  1. --server-primary-responses - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Endpoints of the pets operations; regenerate them instead of editing."""

from collections.abc import Sequence
from typing import Annotated, Final

import models
from fastapi import APIRouter, Body, Path, Query, params
from fastapi.responses import Response

from .._generated import contract
from .._generated.contract import OperationDependencies
from .._runtime.server.application import Wiring, build, checked
from .._runtime.server.responses import dispatch
from ..services import PetsService


def _add_list_pets(
    router: APIRouter,
    wiring: Wiring,
) -> None:
    pets: PetsService = wiring.services['pets']
    list_pets_handler = checked(
        pets.list_pets,
        'The pets.list_pets method of GET /pets',
        ('limit',),
    )

    def list_pets(
        *,
        limit: Annotated[int, Query(alias='limit')] = 20,
    ) -> object:
        return dispatch(
            list_pets_handler(
                limit=limit,
            ),
            contract.ListPets.RESPONSES,
        )

    router.add_api_route(
        '/pets',
        list_pets,
        methods=['GET'],
        status_code=200,
        response_model=models.PetsGetResponse,
        response_model_by_alias=True,
        response_model_exclude_unset=True,
        operation_id='listPets',
        tags=['pets'],
        response_description='The pets.',
        dependencies=wiring.dependencies.get('list_pets'),
    )


def _add_create_pet(
    router: APIRouter,
    wiring: Wiring,
) -> None:
    pets: PetsService = wiring.services['pets']
    create_pet_handler = checked(
        pets.create_pet,
        'The pets.create_pet method of POST /pets',
        ('body',),
    )

    def create_pet(
        *,
        body: Annotated[models.Pet, Body(media_type='application/json')],
    ) -> object:
        return dispatch(
            create_pet_handler(
                body=body,
            ),
            contract.CreatePet.RESPONSES,
        )

    router.add_api_route(
        '/pets',
        create_pet,
        methods=['POST'],
        status_code=201,
        response_model=models.Pet,
        response_model_by_alias=True,
        response_model_exclude_unset=True,
        operation_id='createPet',
        tags=['pets'],
        response_description='Created.',
        dependencies=wiring.dependencies.get('create_pet'),
    )


def _add_replace_pet(
    router: APIRouter,
    wiring: Wiring,
) -> None:
    pets: PetsService = wiring.services['pets']
    replace_pet_handler = checked(
        pets.replace_pet,
        'The pets.replace_pet method of PUT /pets/{name}',
        ('name', 'body'),
    )

    def replace_pet(
        *,
        name: Annotated[str, Path(alias='name')],
        body: Annotated[models.Pet, Body(media_type='application/json')],
    ) -> object:
        return dispatch(
            replace_pet_handler(
                name=name,
                body=body,
            ),
            contract.ReplacePet.RESPONSES,
        )

    router.add_api_route(
        '/pets/{name}',
        replace_pet,
        methods=['PUT'],
        status_code=204,
        response_model=None,
        response_class=Response,
        operation_id='replacePet',
        tags=['pets'],
        response_description='Replaced.',
        dependencies=wiring.dependencies.get('replace_pet'),
    )


LITERAL_ROUTES: Final = (
    ('list_pets', _add_list_pets),
    ('create_pet', _add_create_pet),
)
TEMPLATED_ROUTES: Final = (('replace_pet', _add_replace_pet),)


def build_router(
    *,
    pets: PetsService,
    dependencies: Sequence[params.Depends] = (),
    operation_dependencies: OperationDependencies | None = None,
    prefix: str = "",
) -> APIRouter:
    """Register the pets operations on a new router, literal paths first."""
    return build(
        (*LITERAL_ROUTES, *TEMPLATED_ROUTES),
        services={'pets': pets},
        dependencies=dependencies,
        operation_dependencies=operation_dependencies,
        prefix=prefix,
    )

--server-router-names

Name router groups (experimental).

The JSON object, inline or in a file, maps group keys, such as tag:pets for the operations whose first tag is pets, to the name of the router module, the create_app argument, and the <Name>Service Protocol.

Option relationships:

  • Requires: --generate-server - --server-router-names requires --generate-server fastapi.

Usage

datamodel-codegen --input options.yaml --input-file-type openapi --output models.py --target-python-version 3.11 --openapi-scopes schemas api --output-model-type pydantic_v2.BaseModel --formatters builtin --disable-timestamp --generate-server fastapi --server-output server --server-package server --server-model-package models --server-router-names '{"tag:pets": "animals"}' # (1)!
  1. --server-router-names - the option documented here
Examples

Input Schema:

openapi: 3.1.0
info: {title: Pets, version: "1.0"}
paths:
  /pets:
    get:
      operationId: listPets
      tags: [pets]
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 20}}
      responses:
        "200":
          description: The pets.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Pet"}}
    post:
      operationId: createPet
      tags: [pets]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "200":
          description: Already there.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Pet"}
  /pets/{name}:
    put:
      operationId: replacePet
      tags: [pets]
      parameters:
        - {name: name, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/Pet"}
      responses:
        "204": {description: Replaced.}
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: {type: string}

Output:

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

"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol

import models
from fastapi.responses import Response

from ._runtime.server.responses import HTTPResult


class AnimalsService(Protocol):
    """Implement the animals operations: subclass this Protocol, or give an object its methods."""

    @abstractmethod
    def list_pets(
        self,
        *,
        limit: int,
    ) -> models.PetsGetResponse | HTTPResult[models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """

    @abstractmethod
    def create_pet(
        self,
        *,
        body: models.Pet,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Handle POST /pets.
        """

    @abstractmethod
    def replace_pet(
        self,
        *,
        name: str,
        body: models.Pet,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle PUT /pets/{name}.
        """