spec2py
Ergonomic Python SDKs with pagination, streaming, and maintainable regeneration.
spec2py turns OpenAPI documents into resource-oriented Python clients with Pydantic v2 models, sync and async interfaces, and a shared httpx2 runtime. Overlays, API diffs, and preserved customization directories help you maintain a client as its API evolves.
Experimental alpha. Generated APIs and runtime behavior may change. Review
NOTES.md and test generated clients against your service before distributing them.
$ uvx spec2py generate https://api.acme.com/openapi.json -o clients/acme
$ uvx --with fastapi spec2py fastapi myapp.main:app -o clients/myapp
from acme import Acme, AsyncAcme
client = Acme(api_key=..., timeout=20.0, max_retries=3)
invoice = client.invoices.create(customer_id="cus_1", amount=4200)
for inv in client.invoices.list(status="open"): # auto-paginates
print(inv.id)
with client.completions.stream(prompt="hi") as events: # SSE
for event in events:
print(event.text)
raw = client.with_raw_response.invoices.retrieve("inv_1") # headers, status
raw.headers["x-request-id"], raw.parse()
async with AsyncAcme() as aclient:
page = await aclient.invoices.list()
async for inv in aclient.invoices.list():
...
Requires Python 3.14 for both generation and applications using generated clients.
When to choose spec2py
Use it when you want a Python-only SDK with methods such as
client.invoices.create(...), built-in pagination and streaming, and a repeatable
way to regenerate without losing your custom code. Runtime fixes can be delivered
through dependency updates within the supported compatibility range.
If your SDK must support older Python versions, or you need multiple target languages, evaluate OpenAPI Generator. openapi-python-client is another established Python-focused option with customizable templates. spec2py emphasizes its integrated SDK interface and maintenance workflow; it does not claim broader compatibility or better performance than those projects.
What you get
- Code you'd write by hand. One client object, resources as attributes,
path parameters positional, everything else keyword-only, docstrings from the
spec,
@deprecatedon deprecated operations. CI checks fixture and corpus clients withmypy --strict, strict pyright, ty and ruff, including Stripe and GitHub specs. These checks do not guarantee that every input spec produces correct behavior. - One source, two clients. Resources are generated once as async code; the sync variant is derived mechanically from the AST, so the two can't drift.
- "Omit" versus "send null". Optional parameters default to
NOT_GIVEN, soupdate(memo=None)sends{"memo": null}andupdate()sends{}. - Tolerant of additive changes. Responses retain unknown fields and tolerate unknown enum values. Structural response validation rejects malformed payloads by default; explicit best-effort parsing can return raw values or missing attributes. Request bodies are validated before sending. See the validation and compatibility policy.
- Typed errors.
NotFoundError,RateLimitError,UnprocessableEntityErrorand others, each with.bodyplus.parsed, the error model declared for that status. - Runtime behaviour that's fixed by upgrading, not regenerating. Retries,
auth, pagination, streaming and uploads live in
spec2py-runtime, not in generated code. - Deterministic output. The same spec, config, generator and formatter versions produce byte-identical files, so diffs in review mean something.
Commands
| Command | What it does |
|---|---|
spec2py generate [SPEC] |
Generate a client from a file, URL or module:app. --check fails if the client on disk is stale. |
spec2py fastapi module:app |
Same, from a FastAPI app, in one command. |
spec2py lint [SPEC] |
Explains what will generate poorly, ranked by impact. --fix-overlay fixes.yaml writes a starter Overlay for the mechanical fixes. |
spec2py update |
Regenerates, prints the API diff (breaking changes flagged) and suggests a semver bump. --check is for CI. |
spec2py diff OLD NEW |
Compares the client API two specs would produce. --fail-on-breaking. |
spec2py score [SPEC] |
Quality scorecard: size, documentation, detected pagination and streaming, approximations, and --typecheck. |
spec2py ir [SPEC] |
Prints the IR (or the normalized spec) as JSON, for debugging. |
Inputs
Swagger 2.0, OpenAPI 3.0, 3.1 and 3.2 are supported. 2.0 and 3.0 are
up-converted to 3.1 semantics. External $refs (files and URLs) are bundled.
OpenAPI 3.2 itemSchema types streaming events.
Fixing a spec without forking it
Real-world specs are often wrong. Instead of editing generated code, fix the input:
- Overlays. OpenAPI Overlay documents (JSONPath-targeted patches) are applied on load, so you can keep a small file of fixes and keep pulling the vendor's spec.
- Config in
pyproject.toml:
[tool.spec2py]
spec = "https://api.acme.com/openapi.json"
output = "clients/acme"
package = "acme"
client-name = "Acme"
overlays = ["overlays/fixes.yaml"]
group-by = "tag" # or "path"
exclude-paths = ["/internal/*"]
idempotency-header = "Idempotency-Key"
package-version = "1.4.0"
[tool.spec2py.rename-models]
InvoiceDTO = "Invoice"
[tool.spec2py.operations."GET /invoices"]
name = "list"
resource = "invoices"
pagination = { style = "cursor", items = "data", cursor-param = "after", next-cursor = "last_id" }
[tool.spec2py.operations.createCompletion]
stream = "sse"
Extending a client
Never edit generated files; regeneration overwrites them (and --check notices).
Instead:
_custom/. Files in the package's_custom/directory are never touched. Names in_custom/__init__.py's__all__are re-exported from the package root.- Subclasses.
custom-resources = { invoices = "invoices:Invoices" }makes the client instantiate your_custom/invoices.pysubclass (InvoicesandAsyncInvoices) for that resource. - Hooks and auth.
Hooks(on_request=[...], on_response=[...])for logging, signing and test doubles; anyhttpx2.Authasauth=;transport=orhttp_client=for your own stack.
How it works
The generator is a compiler with five stages. Each later stage reads only the previous stage's output:
- Load: a file, URL or FastAPI app; Overlays and config are applied.
- Normalize: Swagger 2.0 and OpenAPI 3.0 are rewritten into 3.1 semantics,
and external
$refs are bundled. - Model IR: a typed, language-neutral graph of schemas, operations and
security schemes (
spec2py irprints it). - Plan: names, the schema-to-Python type mapping, resource grouping, signatures, and pagination and streaming detection.
- Emit: Python AST (never string templates), formatted by ruff.
NOTES.mdrecords every approximation.
Type mapping
| JSON Schema | Python |
|---|---|
object with properties |
BaseModel (extra="allow") |
| required / optional field | T / T | None = None (responses), T | NotGiven (requests) |
nullable, type: [T, "null"] |
T | None, absent vs null via model_fields_set |
oneOf + discriminator |
Annotated[A | B, Field(discriminator=...)] |
oneOf / anyOf |
A | B (lint warns) |
allOf |
inheritance from one base; extra bases are flattened, and so is a base whose field type would change |
enum |
type X = Annotated[Literal[...], Tolerant] (unknown values accepted on responses, rejected on requests) |
additionalProperties: {schema} |
dict[str, T] |
recursive $ref |
forward references (PEP 649) |
date-time, date, uuid, binary |
datetime, date, UUID, FileTypes in / bytes out |
untyped {} |
object (lint points at an Overlay fix) |
Pagination detection
Cursor (cursor/after/page_token... with a next-cursor field, or Stripe-style
starting_after with has_more), offset (offset + limit), page number
(page), and RFC 8288 Link headers are all detected. You can also declare
pagination with x-pagination or config. Sync list methods return a Page[T];
async ones return a paginator you can await for the first page or async for
over for every item.
Development
uv sync --all-packages # generator + runtime (uv workspace) + dev tools
uv run pytest -q # includes strict type checks of generated clients
uv run ruff check . && uv run ruff format --check . && uv run mypy && uv run pyright
uv run corpus/run.py --gates # real-world specs (Stripe, GitHub, OpenAI, Twilio...) + scorecard
SPEC2PY_UPDATE_GOLDEN=1 uv run pytest tests/test_emit.py tests/test_normalize_ir.py # accept output changes
Releases: push a v* tag. CI builds spec2py and spec2py-runtime and
publishes both to PyPI through trusted publishing.
License
MIT
Metadata
Release files for spec2py 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| spec2py-0.1.0.tar.gz | 170.8 kB | Without provenance | Details for spec2py-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| spec2py-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for spec2py-0.1.0-py3-none-any.whl |
Total release size: 253.9 kB
Release files / spec2py-0.1.0.tar.gz
| Download URL | spec2py-0.1.0.tar.gz |
|---|---|
| Size | 170.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d2b5de4561dbc59cfda9ca011a943897644f27b4a5ca43fa2a6c4946b7f77054
|
|
BLAKE2b-256 checksum How to use checksums |
5a6bce12cef63a209baff25557a41bc5adc90fbc72ba891567134c5862c2cbd4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / spec2py-0.1.0-py3-none-any.whl
| Download URL | spec2py-0.1.0-py3-none-any.whl |
|---|---|
| Size | 83.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
df5a715dccab25d4fe9dba0be330dc95c8a9acedd8f851c8b4ef42080d80938c
|
|
BLAKE2b-256 checksum How to use checksums |
1a942b0fa571e88cb6a9d9dd9c5fb90446073f41787d8b70aa6af8f62c2655b4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for spec2py 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.