# apigenie-generator client python

Source: https://apigenie.pl/docs/reference/generator/client-python
Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md).
Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md).

[Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification)

Generate a Python client of an OpenAPI document, built on [httpx](https://www.python-httpx.org)
and [Pydantic](https://docs.pydantic.dev) 2.

From an AsyncAPI document, the command generates an asyncio Kafka client package instead; see
[`apigenie-generator client python` (AsyncAPI)](/docs/reference/generator/client-python-asyncapi).

## Usage

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

## Description

The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see
[Swagger 2.0 input](/docs/reference/generator#swagger-20-input)). The generated package needs Python
3.10 or later, `pydantic>=2.11` and `httpx` (or `httpx2`, see `http_library`).

```python
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:

```python
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`. Since 0.12.0, a
  `mutualTLS` scheme takes a client certificate: a PEM file holding the certificate and its key,
  or a pair of files. It applies only to the HTTP client the constructor creates; configure it
  on an `http_client` you pass.

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). Since 0.12.0, a parameter described with `content` is sent whole, as JSON
when its media type is JSON. Bodies are JSON, form, multipart (with `File` objects or bytes), text
or binary. Since 0.12.0:

- strings with a `contentMediaType` other than text or JSON are files
- a body with several media types takes a `content_type` argument choosing one; by default
  (`None`), JSON, else form, multipart, text, binary, JSON Lines or JSON text sequence, in that
  order
- JSON Lines (`application/jsonl`, `application/x-ndjson` and the like) and JSON text sequence
  (`application/json-seq`) bodies are iterables of the items of their `itemSchema`

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. Since 0.12.0, so do
operations answering with JSON Lines or JSON text sequences, with their items, when the response
has no JSON media type; text or binary media types beside them are not read. Since 0.12.0, when the response also has JSON, the
method returns the JSON and a `<method>_stream` method beside it returns the `Stream`, which reads
the items by the media type of the response.

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, and since 0.12.0
  `if`/`then`/`else`, `dependentRequired`, `dependentSchemas`, `not` and draft-07 `dependencies`
  checked by a `model_validator`
  when they only test the presence and the values of properties (other conditions aren't
  checked)
- `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`.

Since 0.12.0, operations marked `x-internal: true` (on the operation or its path item) are left
out, unless `internal_operations` is set.

Not supported: callbacks and webhooks, XML bodies, 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-internal` | since 0.12.0, `true` on an operation or its path item leaves the operation out, unless `internal_operations` is set |
| `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`:

```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]
```

```sh
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.`).

### --check

Writes nothing: compares what the generator would write with the output directory, prints the
files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See
[Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date).

### -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

```yaml
version: '1.0'
commands:
  generate:
    client_python:
      layout: package
      http_library: httpx
      internal_operations: false
      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 |
| `internal_operations` | Since 0.12.0. `true`: also generates the operations marked `x-internal: true`; `false` by default |
| `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.

## Verification

The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi).

This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first.

| Results | Level 1 | Level 2 | Level 3 |
| --- | --- | --- | --- |
| Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (python 3.12.11 httpx 0.28.1 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 38 of 38 operations pass (python) |
| Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release |
