apigenie-generator client python
Tier 1 · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · Verification
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 or, since 0.12.0, a Swagger 2.0 document (see
Swagger 2.0 input). 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 (seegroup_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 (seeaction_naming). - arguments for the server (
base_url, orserverandserver_variables), one argument per security scheme (API keys, HTTP schemes, bearer tokens, OAuth 2.0 tokens or anOAuth2ClientCredentials, which requests and refreshes tokens),auth(anyhttpx.Auth),timeout,max_retries,headers,http_clientandfollow_redirects. Since 0.12.0, amutualTLSscheme 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 anhttp_clientyou 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
contentMediaTypeother than text or JSON are files - a body with several media types takes a
content_typeargument 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-ndjsonand the like) and JSON text sequence (application/json-seq) bodies are iterables of the items of theiritemSchema
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
allOfflattened into one class, and since 0.12.0if/then/else,dependentRequired,dependentSchemas,notand draft-07dependencieschecked by amodel_validatorwhen they only test the presence and the values of properties (other conditions aren’t checked) Enumclasses for string and integer enums of component schemas,Literaltypes otherwise- tagged unions for
oneOfandanyOfwith a discriminator, unions otherwise PetInputvariants for requests when a schema hasreadOnlyorwriteOnlypropertiesdatetime.date,datetime.datetime,uuid.UUID,DecimalandBase64Bytesfor formats,Annotatedconstraints forminimum,maxLengthand the like, andpatternchecked with Python’srebymatching()of_models.py(a patternrecan’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:
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.).
–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.
-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
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 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.
This target's support tier is Tier 1. 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 |