unihttp-openapi-generator
Turn an OpenAPI spec into a typed Python API client built on
unihttp.
Point it at a spec; get back an installable package with data models, request
classes, a sync and/or async client, an exception hierarchy, and authentication
wiring. The output is formatted with ruff and type-checks clean under mypy --strict.
Table of Contents
Why
- Actually typed. Models, parameters, and return values carry real annotations;
the generated code passes
mypy --strict. Your editor knows the shape of every
request and response.
- Three model backends. Choose
adaptix (default), pydantic, or msgspec
for the generated models — same client, your serializer.
- Sync, async, or both. Backed by
httpx, aiohttp, requests, niquests, or
zapros, chosen per client.
- Faithful to the spec.
allOf/oneOf/anyOf, discriminated unions, enums,
formats, nullable, defaults, multipart uploads, query array styles, security
schemes, and error responses are all carried through.
- Proven on large specs. The Stripe, GitHub, OpenAI, and Kubernetes specs each
generate clean, importable code that passes
ruff and mypy --strict on every
serializer.
- Readable, regenerable output. Deterministic,
ruff-formatted, organized by tag.
Install
pip install unihttp-openapi-generator
# or, with uv:
uv tool install unihttp-openapi-generator
Quick start
unihttp-openapi-generator generate openapi.yaml \
--output-dir ./out --package-name acme_client
The spec can be a local path or a URL, in JSON or YAML. Install the result and use it:
from acme_client import AcmeClient
with AcmeClient(base_url="https://api.example.com", token="...") as client:
pet = client.pets.get_pet(pet_id=1) # -> a typed model
print(pet.name)
Alternative: the unihttp agent skills
No spec, or you would rather have the client written for you?
unihttp ships
agent skills for Claude Code, Codex,
and other .agents/-aware agents. unihttp-client scaffolds the same kind of packaged,
typed client — models, request classes, a client, ruff/mypy config, and tests —
from an OpenAPI 3.x spec or from a plain description of the API; unihttp teaches
the agent to write idiomatic unihttp code by hand.
claude plugin marketplace add goduni/unihttp
claude plugin install unihttp@unihttp
Which to use: this generator is deterministic and regenerable — the same spec always
produces the same package, and it swallows specs far larger than an agent's context.
Reach for the skills when there is no machine-readable spec at all, or when you want a
small client shaped by hand as it is written.
What you get
out/
├── pyproject.toml # installable; pins unihttp + your serializer + backend
├── README.md
└── acme_client/
├── __init__.py # exports the client(s), DEFAULT_BASE_URL, SERVERS
├── py.typed
├── models.py # dataclass / BaseModel / msgspec.Struct
├── _serialization.py # request/response (de)serialization wiring
├── exceptions.py # ApiError hierarchy + status -> exception map
├── auth.py # credential middlewares (when the spec defines security)
├── methods/<tag>.py # one request class per operation
└── client.py # the client(s)
A request class and the client constructor (real output):
@dataclass
class GetBooking(BaseMethod[GetBookingResponse]):
"""Get a booking
Returns the details of a specific booking.
"""
__url__ = "/bookings/{bookingId}"
__method__ = "GET"
booking_id: Path[UUID]
class TrainTravelAPIClient(RequestsSyncClient):
def __init__(
self,
base_url: str = DEFAULT_BASE_URL,
*,
session: Any = None,
middleware: list[Any] | None = None,
token: str | None = None,
) -> None: ...
Using the client
Clients are context managers and close their transport on exit.
from acme_client import AcmeClient
with AcmeClient(base_url="https://api.example.com", token="secret") as client:
booking = client.bookings.get_booking(booking_id=some_uuid) # grouped layout
# client.get_booking(...) # flat layout
Async clients expose the same surface; their methods are awaitables:
import asyncio
from acme_client import AsyncAcmeClient
async def main() -> None:
async with AsyncAcmeClient(token="secret") as client:
trips = await client.trips.get_trips(origin=a, destination=b, date=when)
asyncio.run(main())
Base URL and servers
The default base URL is taken from the spec's servers (preferring a production
entry). Every server is also exported:
from acme_client import DEFAULT_BASE_URL, SERVERS
client = AcmeClient(base_url=SERVERS["Production"])
Authentication
Each security scheme becomes a constructor keyword that is injected via middleware:
| Scheme |
Keyword |
Sent as |
| http bearer / oauth2 / openIdConnect |
token: str |
Authorization: Bearer <token> |
| apiKey (header or query) |
<scheme>: str |
the named header or query parameter |
| http basic |
<scheme>: tuple[str, str] |
Authorization: Basic <base64> |
Custom headers, cookies, timeouts
Build the underlying HTTP client yourself and pass it as session= (its type matches
the chosen backend — requests.Session by default, httpx.Client, aiohttp.ClientSession, …):
import requests
session = requests.Session()
session.headers["User-Agent"] = "acme/1.0"
client = AcmeClient(session=session)
Errors
Non-2xx responses raise. <package>.exceptions defines a base ApiError plus a
subclass per status code (NotFoundError, UnprocessableEntityError, …), with
4xx/5xx falling back to unihttp's ClientError/ServerError.
from acme_client.exceptions import ApiError, NotFoundError
try:
booking = client.bookings.get_booking(booking_id=bad_id)
except NotFoundError as exc:
print(exc.status_code, exc.response.data)
except ApiError:
...
Middleware
Pass any unihttp middleware; auth and error mapping are composed around it.
from unihttp.middlewares.retry import RetryMiddleware
client = AcmeClient(middleware=[RetryMiddleware(retries=3)])
CLI options
unihttp-openapi-generator generate SPEC [options]
| Option |
Values (default) |
-o, --output-dir |
path (required) |
--package-name |
identifier (required) |
--serializer |
adaptix · pydantic · msgspec (adaptix) |
--client |
both · sync · async (both) |
--sync-backend |
httpx · requests · niquests · zapros (requests) |
--async-backend |
httpx · aiohttp · niquests · zapros (aiohttp) |
--layout |
auto · flat · grouped (auto) |
--file-layout |
single · per-object (single) |
--style |
declarative · imperative (declarative) |
--optional |
none · omitted (none) — omitted distinguishes absent from null (adaptix) |
--strip-prefix |
auto or a dotted prefix to drop from schema names (e.g. io.k8s.api.core.v1.Pod → CoreV1Pod) |
--inheritance |
off by default — render allOf: [$ref] as a base class instead of merging its fields in |
--stubs |
off by default — also emit client.pyi so PyCharm sees every method signature (details) |
--check |
run ruff and mypy --strict on the output (details) |
--config |
TOML config file |
Config file
Keep your generation settings in a TOML file so a regenerate is a single command and
the configuration lives in version control.
Precedence. For every setting: an explicit CLI flag wins, otherwise the config
file, otherwise the built-in default. So you can pin a project's settings in the file
and still override one of them ad hoc on the command line:
unihttp-openapi-generator generate # use the discovered config
unihttp-openapi-generator generate --serializer msgspec # override just this one
Discovery order (the first that exists is used):
- the file passed to
--config FILE,
unihttp-openapi-generator.toml in the current directory,
- a
[tool.unihttp-openapi-generator] table in pyproject.toml.
Keys mirror the CLI options exactly. spec, output_dir, and package_name are
required (from the file or the command line); everything else is optional and falls
back to the default shown in the CLI options table. Unknown keys are
rejected so typos surface immediately.