apigenie-generatorOpenAPI clientsclient python

client python

Generate a Python client of an OpenAPI document, built on httpx and Pydantic 2.

From an AsyncAPI document, the command generates an asyncio Kafka client package instead; see apigenie-generator client python (AsyncAPI).

Usage

apigenie-generator client python [...OPTIONS] INPUT_FILE

Description

The input must be an OpenAPI 3.0, 3.1 or 3.2 document. The generated package needs Python 3.10 or later, pydantic>=2.11 and httpx (or httpx2, see http_library).

from pet_store_client import Client, NotFoundError, models

with Client(api_key="...") as client:
    pets = client.pets.list_pets(limit=10)
    pet = client.pets.create_pet(models.PetInput(name="Rex"))
    try:
        client.pets.get_pet(42)
    except NotFoundError as error:
        print(error.body)

AsyncClient has the same methods, as coroutines:

async with AsyncClient(api_key="...") as client:
    pets = await client.pets.list_pets()

The clients have:

  • one resource per group of operations, e.g. client.pets, with one method per operation. Operations are grouped by their first tag (see group_by); the methods of operations without a group belong to the client. Method names come from operation IDs, or from the method and the path (see action_naming).
  • arguments for the server (base_url, or server and server_variables), one argument per security scheme (API keys, HTTP schemes, bearer tokens, OAuth 2.0 tokens or an OAuth2ClientCredentials, which requests and refreshes tokens), auth (any httpx.Auth), timeout, max_retries, headers, http_client and follow_redirects.

Each method takes the operation’s required parameters as positional arguments, optional ones as keyword arguments (left out unless given; UNSET by default), the request body, and request_options, which override the timeout and retries and add headers and query parameters. Parameters are serialized with their style (form, spaceDelimited, pipeDelimited, deepObject, simple, label, matrix). Bodies are JSON, form, multipart (with File objects or bytes), text or binary. Requests use the credentials of the first alternative of the operation’s security requirements for which the client has credentials.

Methods return the parsed body of a successful response, chosen by status code (200, 2XX, default): a model, a list, text, bytes, or None. Error statuses raise an ApiStatusError subclass (BadRequestError, AuthenticationError, NotFoundError, RateLimitError, InternalServerError, …) whose body is parsed with the documented schema. Connection errors, timeouts, and 408, 409, 429 and 5xx responses are retried with exponential backoff, honoring Retry-After; timeouts and server errors only for idempotent methods. client.pets.with_raw_response returns responses with their status and headers, client.pets.with_streaming_response returns them before reading their bodies (e.g. to download a file in chunks). Operations answering with server-sent events (text/event-stream) return a Stream of events.

Models are Pydantic classes in the models module. Fields have Python names (pet_id for petId) and are serialized with the names of the API. Requests send the fields that were set: a field left out is omitted, one set to None is sent as null. Unknown properties of responses are kept in model_extra. Schemas become:

  • classes for objects, with allOf flattened into one class
  • Enum classes for string and integer enums of component schemas, Literal types otherwise
  • tagged unions for oneOf and anyOf with a discriminator, unions otherwise
  • PetInput variants for requests when a schema has readOnly or writeOnly properties
  • datetime.date, datetime.datetime, uuid.UUID, Decimal and Base64Bytes for formats, Annotated constraints for minimum, maxLength and the like, and pattern checked with Python’s re by matching() of _models.py (a pattern re can’t compile, such as one using \p{L}, isn’t checked)

The generated package contains pyproject.toml, README.md and the package: client.py, models.py, resources/ (one module per group), _metadata.py (servers and security schemes), the runtime (_base_client.py, _types.py, _auth.py, _exceptions.py, _serialization.py, _response.py, _sse.py, _models.py), _http.py and py.typed. The code passes mypy --strict.

Not supported: callbacks and webhooks, XML bodies, x-internal (such operations are part of the client), parameters described with content (they are serialized with the form style), mutual TLS (configure it on an http_client), and pagination.

Extensions

Extension Effect
x-apigenie.codegen.name name of the model class of a component schema
x-enum-varnames, x-enumNames names of the members of an enum
x-apigenie.codegen.controller-name on an operation or its path item: the resource of the operation, when group_by lists extension
x-apigenie.codegen.action-name name of the method of an operation, when action_naming lists extension
x-apigenie.codegen.disabled true on an operation or its path item leaves the operation out
x-defaultMapping defaultMapping of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn’t mapped

The extensions can live in an overlay for this target instead of in the document, e.g. python.overlay.yaml:

overlay: 1.0.0
info:
  title: Python names
  version: 1.0.0
actions:
  - target: $.components.schemas.Pet
    update:
      x-apigenie:
        codegen:
          name: Animal
  - target: $.components.schemas.PetStatus
    update:
      x-enum-varnames: [AVAILABLE, ON_HOLD, SOLD]
apigenie-generator client python openapi.yaml --overlay python.overlay.yaml -o out

Options

-c, –config

Path to the configuration file to use. See the “Configuration” section for more information.

–overlay OVERLAY

Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the “Extensions” section. Can be repeated: the overlays apply in order, after those listed under commands.generate.client_python.overlay in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay.

–strict

Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.).

-o, –output

Directory where the package is generated.

–package-name

Name of the distribution, e.g. pet-store-client; the package is named after it (pet_store_client). Defaults to the title of the API followed by -client.

–package-version

Version of the package. Defaults to the version of the API.

Configuration

version: '1.0'
commands:
  generate:
    client_python:
      layout: package
      http_library: httpx
      group_by: tag
      action_naming: [id, url]
      raise_on_error: true
      enum_style: enum
      field_prefix: field_
      class_overrides:
        pet-v2: Pet
Option Description
layout package (default): pyproject.toml, README.md and the package directory; sources: the modules only, directly in the output directory
http_library httpx (default) or httpx2, Pydantic’s continuation of httpx with the same API
group_by How operations are grouped into resources: tag (default), url, extension (x-apigenie codegen/controller-name), or an array of them, tried in order
action_naming Sources of method names: id, extension (x-apigenie codegen/action-name), url, or an array of them, tried in order; [id, url] by default
raise_on_error true (default): documented error responses raise errors; false: methods return their parsed bodies
enum_style enum (default): Enum classes for enums of component schemas; literal: Literal types everywhere
field_prefix Prefix of field names that would be invalid or clash with Pydantic, e.g. json becomes field_json; field_ by default
class_overrides Class names of component schemas, by schema name

Unknown options are errors.