spec2py 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. spec2py-0.1.0/.github/workflows/ci.yml +66 -0
  2. spec2py-0.1.0/.github/workflows/release.yml +54 -0
  3. spec2py-0.1.0/.gitignore +214 -0
  4. spec2py-0.1.0/.python-version +1 -0
  5. spec2py-0.1.0/CLAUDE.md +87 -0
  6. spec2py-0.1.0/LICENSE +21 -0
  7. spec2py-0.1.0/PKG-INFO +228 -0
  8. spec2py-0.1.0/README.md +203 -0
  9. spec2py-0.1.0/corpus/manifest.toml +58 -0
  10. spec2py-0.1.0/corpus/run.py +168 -0
  11. spec2py-0.1.0/pyproject.toml +123 -0
  12. spec2py-0.1.0/src/spec2py/__init__.py +17 -0
  13. spec2py-0.1.0/src/spec2py/_version.py +24 -0
  14. spec2py-0.1.0/src/spec2py/build_ir.py +637 -0
  15. spec2py-0.1.0/src/spec2py/cli.py +351 -0
  16. spec2py-0.1.0/src/spec2py/config.py +199 -0
  17. spec2py-0.1.0/src/spec2py/emit/client.py +435 -0
  18. spec2py-0.1.0/src/spec2py/emit/models.py +239 -0
  19. spec2py-0.1.0/src/spec2py/emit/notes.py +65 -0
  20. spec2py-0.1.0/src/spec2py/emit/package.py +319 -0
  21. spec2py-0.1.0/src/spec2py/emit/pyast.py +372 -0
  22. spec2py-0.1.0/src/spec2py/emit/resources.py +425 -0
  23. spec2py-0.1.0/src/spec2py/emit/unasync.py +113 -0
  24. spec2py-0.1.0/src/spec2py/ir.py +229 -0
  25. spec2py-0.1.0/src/spec2py/jsonpath.py +456 -0
  26. spec2py-0.1.0/src/spec2py/lint.py +316 -0
  27. spec2py-0.1.0/src/spec2py/loader.py +136 -0
  28. spec2py-0.1.0/src/spec2py/naming.py +96 -0
  29. spec2py-0.1.0/src/spec2py/normalize/__init__.py +35 -0
  30. spec2py-0.1.0/src/spec2py/normalize/refs.py +205 -0
  31. spec2py-0.1.0/src/spec2py/normalize/swagger2.py +306 -0
  32. spec2py-0.1.0/src/spec2py/normalize/upgrade.py +76 -0
  33. spec2py-0.1.0/src/spec2py/overlay.py +106 -0
  34. spec2py-0.1.0/src/spec2py/pipeline.py +82 -0
  35. spec2py-0.1.0/src/spec2py/plan.py +1654 -0
  36. spec2py-0.1.0/src/spec2py/py.typed +0 -0
  37. spec2py-0.1.0/src/spec2py/score.py +73 -0
  38. spec2py-0.1.0/src/spec2py/surface.py +214 -0
  39. spec2py-0.1.0/tests/__init__.py +0 -0
  40. spec2py-0.1.0/tests/conftest.py +53 -0
  41. spec2py-0.1.0/tests/fastapi_app/__init__.py +0 -0
  42. spec2py-0.1.0/tests/fastapi_app/app.py +182 -0
  43. spec2py-0.1.0/tests/golden/acme/NOTES.md +34 -0
  44. spec2py-0.1.0/tests/golden/acme/__init__.py +58 -0
  45. spec2py-0.1.0/tests/golden/acme/_client.py +305 -0
  46. spec2py-0.1.0/tests/golden/acme/_version.py +3 -0
  47. spec2py-0.1.0/tests/golden/acme/models.py +192 -0
  48. spec2py-0.1.0/tests/golden/acme/py.typed +0 -0
  49. spec2py-0.1.0/tests/golden/acme/resources/__init__.py +62 -0
  50. spec2py-0.1.0/tests/golden/acme/resources/catalog.py +154 -0
  51. spec2py-0.1.0/tests/golden/acme/resources/completions.py +124 -0
  52. spec2py-0.1.0/tests/golden/acme/resources/customers.py +243 -0
  53. spec2py-0.1.0/tests/golden/acme/resources/events.py +101 -0
  54. spec2py-0.1.0/tests/golden/acme/resources/files.py +144 -0
  55. spec2py-0.1.0/tests/golden/acme/resources/invoices.py +428 -0
  56. spec2py-0.1.0/tests/golden/acme.ir.json +1342 -0
  57. spec2py-0.1.0/tests/golden/nullable_30/NOTES.md +14 -0
  58. spec2py-0.1.0/tests/golden/nullable_30/__init__.py +58 -0
  59. spec2py-0.1.0/tests/golden/nullable_30/_client.py +165 -0
  60. spec2py-0.1.0/tests/golden/nullable_30/_version.py +3 -0
  61. spec2py-0.1.0/tests/golden/nullable_30/models.py +26 -0
  62. spec2py-0.1.0/tests/golden/nullable_30/py.typed +0 -0
  63. spec2py-0.1.0/tests/golden/nullable_30/resources/__init__.py +17 -0
  64. spec2py-0.1.0/tests/golden/nullable_30/resources/notes.py +96 -0
  65. spec2py-0.1.0/tests/golden/petstore_swagger2/NOTES.md +15 -0
  66. spec2py-0.1.0/tests/golden/petstore_swagger2/__init__.py +58 -0
  67. spec2py-0.1.0/tests/golden/petstore_swagger2/_client.py +200 -0
  68. spec2py-0.1.0/tests/golden/petstore_swagger2/_version.py +3 -0
  69. spec2py-0.1.0/tests/golden/petstore_swagger2/models.py +30 -0
  70. spec2py-0.1.0/tests/golden/petstore_swagger2/py.typed +0 -0
  71. spec2py-0.1.0/tests/golden/petstore_swagger2/resources/__init__.py +7 -0
  72. spec2py-0.1.0/tests/golden/petstore_swagger2/resources/pets.py +268 -0
  73. spec2py-0.1.0/tests/runtime/__init__.py +0 -0
  74. spec2py-0.1.0/tests/runtime/helpers.py +70 -0
  75. spec2py-0.1.0/tests/runtime/test_auth_files_qs.py +238 -0
  76. spec2py-0.1.0/tests/runtime/test_client.py +393 -0
  77. spec2py-0.1.0/tests/runtime/test_models.py +178 -0
  78. spec2py-0.1.0/tests/runtime/test_pagination.py +336 -0
  79. spec2py-0.1.0/tests/runtime/test_streaming.py +134 -0
  80. spec2py-0.1.0/tests/specs/acme.yaml +479 -0
  81. spec2py-0.1.0/tests/specs/acme_overlay.yaml +10 -0
  82. spec2py-0.1.0/tests/specs/external/author.yaml +4 -0
  83. spec2py-0.1.0/tests/specs/external/common.yaml +13 -0
  84. spec2py-0.1.0/tests/specs/external/main.yaml +27 -0
  85. spec2py-0.1.0/tests/specs/nullable_30.yaml +31 -0
  86. spec2py-0.1.0/tests/specs/petstore_swagger2.json +73 -0
  87. spec2py-0.1.0/tests/test_cli.py +323 -0
  88. spec2py-0.1.0/tests/test_emit.py +250 -0
  89. spec2py-0.1.0/tests/test_fastapi_roundtrip.py +108 -0
  90. spec2py-0.1.0/tests/test_generated_client.py +384 -0
  91. spec2py-0.1.0/tests/test_jsonpath_overlay.py +106 -0
  92. spec2py-0.1.0/tests/test_normalize_ir.py +209 -0
  93. spec2py-0.1.0/tests/test_plan.py +958 -0
  94. spec2py-0.1.0/tests/test_properties.py +212 -0
  95. spec2py-0.1.0/tests/test_static_gates.py +93 -0
  96. spec2py-0.1.0/uv.lock +779 -0
@@ -0,0 +1,66 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ workflow_call:
8
+
9
+ jobs:
10
+ lint-and-test:
11
+ timeout-minutes: 30
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - name: Checkout repository
15
+ uses: actions/checkout@v7
16
+ with:
17
+ fetch-depth: 0 # full history, so hatch-vcs can see tags
18
+
19
+ - name: Set up uv
20
+ uses: astral-sh/setup-uv@v7
21
+ with:
22
+ version: "latest"
23
+ enable-cache: true
24
+
25
+ - name: Set up Python 3.14
26
+ run: uv python install 3.14
27
+
28
+ - name: Install dependencies
29
+ run: uv sync --locked --all-packages
30
+
31
+ - name: Ruff lint
32
+ run: uv run ruff check .
33
+
34
+ - name: Ruff format check
35
+ run: uv run ruff format --check .
36
+
37
+ - name: Mypy (strict)
38
+ run: uv run mypy
39
+
40
+ - name: Pyright
41
+ run: uv run pyright
42
+
43
+ - name: Tests (including generated-client static gates)
44
+ run: uv run pytest -q
45
+
46
+ corpus:
47
+ # Regenerates every real-world spec in corpus/manifest.toml and runs the
48
+ # static gates on each client. Large specs (Stripe, GitHub) included.
49
+ timeout-minutes: 30
50
+ runs-on: ubuntu-latest
51
+ steps:
52
+ - uses: actions/checkout@v7
53
+ with:
54
+ fetch-depth: 0
55
+ - uses: astral-sh/setup-uv@v7
56
+ with:
57
+ version: "latest"
58
+ enable-cache: true
59
+ - run: uv python install 3.14
60
+ - run: uv sync --locked --all-packages
61
+ - uses: actions/cache@v4
62
+ with:
63
+ path: corpus/specs
64
+ key: corpus-${{ hashFiles('corpus/manifest.toml') }}
65
+ - name: Corpus scorecard
66
+ run: uv run corpus/run.py --gates
@@ -0,0 +1,54 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*' # e.g. v0.1.0 publishes spec2py and spec2py-runtime at 0.1.0
7
+
8
+ jobs:
9
+ validate:
10
+ uses: ./.github/workflows/ci.yml
11
+
12
+ build-and-publish:
13
+ needs: validate
14
+ timeout-minutes: 15
15
+ name: Build packages and publish to PyPI
16
+ runs-on: ubuntu-latest
17
+ environment: pypi
18
+
19
+ # Required for PyPI Trusted Publishing (OIDC). Both projects, spec2py and
20
+ # spec2py-runtime, need this repository configured as a trusted publisher.
21
+ permissions:
22
+ id-token: write
23
+ contents: read
24
+
25
+ steps:
26
+ - name: Checkout repository
27
+ uses: actions/checkout@v7
28
+ with:
29
+ fetch-depth: 0 # full history, so hatch-vcs can resolve the tag's version
30
+
31
+ - name: Set up uv
32
+ uses: astral-sh/setup-uv@v7
33
+ with:
34
+ version: "latest"
35
+
36
+ - name: Set up Python
37
+ run: uv python install 3.14
38
+
39
+ - name: Build both distributions
40
+ run: uv build --all-packages
41
+
42
+ - name: Smoke test installed wheels
43
+ run: |
44
+ uv venv /tmp/spec2py-release-smoke --python 3.14
45
+ uv pip install --python /tmp/spec2py-release-smoke/bin/python dist/*.whl
46
+ cd /tmp
47
+ /tmp/spec2py-release-smoke/bin/spec2py --help
48
+ /tmp/spec2py-release-smoke/bin/python -c "import spec2py, spec2py_runtime"
49
+ /tmp/spec2py-release-smoke/bin/spec2py generate "$GITHUB_WORKSPACE/tests/specs/acme.yaml" -o /tmp/release-client --layout project
50
+ uv pip install --python /tmp/spec2py-release-smoke/bin/python /tmp/release-client
51
+ /tmp/spec2py-release-smoke/bin/python -c "from acme import Acme, AsyncAcme"
52
+
53
+ - name: Publish to PyPI
54
+ run: uv publish
@@ -0,0 +1,214 @@
1
+ # Downloaded corpus specs (pinned by hash in corpus/manifest.toml)
2
+ /corpus/specs/
3
+
4
+ # Generated at build time by hatch-vcs from the git tag
5
+ /src/spec2py/_version.py
6
+ /runtime/src/spec2py_runtime/_version.py
7
+
8
+ # Byte-compiled / optimized / DLL files
9
+ __pycache__/
10
+ *.py[codz]
11
+ *$py.class
12
+
13
+ # C extensions
14
+ *.so
15
+
16
+ # Distribution / packaging
17
+ .Python
18
+ build/
19
+ develop-eggs/
20
+ dist/
21
+ downloads/
22
+ eggs/
23
+ .eggs/
24
+ lib/
25
+ lib64/
26
+ parts/
27
+ sdist/
28
+ var/
29
+ wheels/
30
+ share/python-wheels/
31
+ *.egg-info/
32
+ .installed.cfg
33
+ *.egg
34
+ MANIFEST
35
+
36
+ # PyInstaller
37
+ # Usually these files are written by a python script from a template
38
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
39
+ *.manifest
40
+ *.spec
41
+
42
+ # Installer logs
43
+ pip-log.txt
44
+ pip-delete-this-directory.txt
45
+
46
+ # Unit test / coverage reports
47
+ htmlcov/
48
+ .tox/
49
+ .nox/
50
+ .coverage
51
+ .coverage.*
52
+ .cache
53
+ nosetests.xml
54
+ coverage.xml
55
+ *.cover
56
+ *.py.cover
57
+ .hypothesis/
58
+ .pytest_cache/
59
+ cover/
60
+
61
+ # Translations
62
+ *.mo
63
+ *.pot
64
+
65
+ # Django stuff:
66
+ *.log
67
+ local_settings.py
68
+ db.sqlite3
69
+ db.sqlite3-journal
70
+
71
+ # Flask stuff:
72
+ instance/
73
+ .webassets-cache
74
+
75
+ # Scrapy stuff:
76
+ .scrapy
77
+
78
+ # Sphinx documentation
79
+ docs/_build/
80
+
81
+ # PyBuilder
82
+ .pybuilder/
83
+ target/
84
+
85
+ # Jupyter Notebook
86
+ .ipynb_checkpoints
87
+
88
+ # IPython
89
+ profile_default/
90
+ ipython_config.py
91
+
92
+ # pyenv
93
+ # For a library or package, you might want to ignore these files since the code is
94
+ # intended to run in multiple environments; otherwise, check them in:
95
+ # .python-version
96
+
97
+ # pipenv
98
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
99
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
100
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
101
+ # install all needed dependencies.
102
+ #Pipfile.lock
103
+
104
+ # UV
105
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
106
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
107
+ # commonly ignored for libraries.
108
+ #uv.lock
109
+
110
+ # poetry
111
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
112
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
113
+ # commonly ignored for libraries.
114
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
115
+ #poetry.lock
116
+ #poetry.toml
117
+
118
+ # pdm
119
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
120
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
121
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
122
+ #pdm.lock
123
+ #pdm.toml
124
+ .pdm-python
125
+ .pdm-build/
126
+
127
+ # pixi
128
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
129
+ #pixi.lock
130
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
131
+ # in the .venv directory. It is recommended not to include this directory in version control.
132
+ .pixi
133
+
134
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
135
+ __pypackages__/
136
+
137
+ # Celery stuff
138
+ celerybeat-schedule
139
+ celerybeat.pid
140
+
141
+ # SageMath parsed files
142
+ *.sage.py
143
+
144
+ # Environments
145
+ .env
146
+ .envrc
147
+ .venv
148
+ env/
149
+ venv/
150
+ ENV/
151
+ env.bak/
152
+ venv.bak/
153
+
154
+ # Spyder project settings
155
+ .spyderproject
156
+ .spyproject
157
+
158
+ # Rope project settings
159
+ .ropeproject
160
+
161
+ # mkdocs documentation
162
+ /site
163
+
164
+ # mypy
165
+ .mypy_cache/
166
+ .dmypy.json
167
+ dmypy.json
168
+
169
+ # Pyre type checker
170
+ .pyre/
171
+
172
+ # pytype static type analyzer
173
+ .pytype/
174
+
175
+ # Cython debug symbols
176
+ cython_debug/
177
+
178
+ # PyCharm
179
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
180
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
181
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
182
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
183
+ #.idea/
184
+
185
+ # Abstra
186
+ # Abstra is an AI-powered process automation framework.
187
+ # Ignore directories containing user credentials, local state, and settings.
188
+ # Learn more at https://abstra.io/docs
189
+ .abstra/
190
+
191
+ # Visual Studio Code
192
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
193
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
194
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
195
+ # you could uncomment the following to ignore the entire vscode folder
196
+ # .vscode/
197
+
198
+ # Ruff stuff:
199
+ .ruff_cache/
200
+
201
+ # PyPI configuration file
202
+ .pypirc
203
+
204
+ # Cursor
205
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
206
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
207
+ # refer to https://docs.cursor.com/context/ignore-files
208
+ .cursorignore
209
+ .cursorindexingignore
210
+
211
+ # Marimo
212
+ marimo/_static/
213
+ marimo/_lsp/
214
+ __marimo__/
@@ -0,0 +1 @@
1
+ 3.14
@@ -0,0 +1,87 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## What this is
6
+
7
+ `spec2py` is a Python-only OpenAPI client generator (the design doc is
8
+ "A First-Class OpenAPI Client Generator for Python"). It's a uv workspace with
9
+ two distributions:
10
+
11
+ - `spec2py` (repo root, `src/spec2py/`): the generator and CLI.
12
+ - `spec2py-runtime` (`runtime/`, `runtime/src/spec2py_runtime/`): what
13
+ generated clients import at runtime. It depends only on httpx2, pydantic and
14
+ anyio. Request behaviour (retries, auth, pagination, streaming, errors) belongs
15
+ here, never in generated code.
16
+
17
+ Python 3.14 only. Use modern syntax freely: PEP 695 generics and `type` aliases,
18
+ PEP 649 lazy annotations (no `from __future__ import annotations`), PEP 758
19
+ `except A, B:`, `warnings.deprecated`.
20
+
21
+ ## Commands
22
+
23
+ ```bash
24
+ uv sync --all-packages
25
+ uv run pytest -q # everything (~230 tests, ~25s)
26
+ uv run pytest -q -m "not slow" # skip static gates on generated code
27
+ uv run pytest tests/test_plan.py::test_pagination_detection -q
28
+ uv run ruff check . && uv run ruff format --check . && uv run mypy && uv run pyright
29
+ SPEC2PY_UPDATE_GOLDEN=1 uv run pytest tests/test_emit.py tests/test_normalize_ir.py # accept output changes
30
+ uv run corpus/run.py --gates # real-world specs; --small skips Stripe/GitHub
31
+ uv run spec2py generate tests/specs/acme.yaml -o /tmp/acme --layout package
32
+ ```
33
+
34
+ mypy is strict everywhere. pyright is strict for `runtime/src` and standard for
35
+ the generator.
36
+
37
+ ## Architecture: a five-stage compiler
38
+
39
+ `pipeline.py` wires the stages together. Each stage only reads the previous one's output.
40
+
41
+ 1. **Load** (`loader.py`, `overlay.py`, `jsonpath.py`, `config.py`): a file, URL or
42
+ `module:app` FastAPI import. Overlays use our own RFC 9535 JSONPath, which
43
+ returns mutable locations.
44
+ 2. **Normalize** (`normalize/`): `swagger2.py` (2.0 → 3.0), `refs.py` (bundles
45
+ external `$ref`s into `#/components/schemas`), `upgrade.py` (3.0 → 3.1
46
+ semantics: `nullable` becomes a `type` array or an `anyOf` with null).
47
+ 3. **IR** (`ir.py`, `build_ir.py`): a `Schema` node per construct (`Kind` enum),
48
+ plus `Operation`, `Response` and `SecurityScheme`. Refs stay as
49
+ `Kind.REF(name)`, so there are no cycles. `spec2py ir` prints it, and
50
+ `tests/golden/acme.ir.json` snapshots it.
51
+ 4. **Plan** (`plan.py`, `naming.py`): every Python decision. That covers
52
+ model/field/method names, `type_of()` (the type mapping), resource grouping,
53
+ flat bodies (fields from the body model, validated by
54
+ `spec2py_runtime.build_body`), pagination detection (`detect_pagination`),
55
+ streaming (`stream_format`, `make_stream`), auth params, and `notes` (which
56
+ become NOTES.md).
57
+ 5. **Emit** (`emit/`): builds `ast.Module`s. `pyast.py` has the `TypeExpr` tree
58
+ and `Imports` (clash-safe imports, `shadowed` builtins, `TYPE_CHECKING`
59
+ deferral). Resources and the client are emitted as async code, and
60
+ `unasync.py` derives the sync class. `package.py` runs ruff (isort + format),
61
+ writes files, keeps `_custom/`, removes stale files and writes
62
+ `.spec2py-manifest.json` (file hashes and the API surface `update` diffs
63
+ against).
64
+
65
+ Rules learned from the corpus. Keep them:
66
+
67
+ - Never narrow an inherited field. Discriminator tags and type changes make the
68
+ model copy its base's fields instead (`declare_object`), because ty and mypy
69
+ reject it.
70
+ - A field or parameter named like a builtin (`object`, `type`, `list`) shadows it
71
+ in annotations (class scope, PEP 649) or in method bodies. Use
72
+ `Imports.shadowed` to render `builtins.x`.
73
+ - Over `SPLIT_THRESHOLD` models, `models` becomes a package (`_bases`,
74
+ `_aliases`, name-family chunks), because pyright gives up on huge modules.
75
+ Runtime imports must stay acyclic. `link_models()` plus `defer_build=True`
76
+ keep imports fast.
77
+ - `cast(type[X], X)` is used for `cast_to` with non-class types; strip
78
+ `Annotated` in `type[...]`.
79
+
80
+ ## Tests
81
+
82
+ - `tests/runtime/`: runtime behaviour against fault-injecting `MockTransport`s.
83
+ - `tests/test_generated_client.py`: the generated Acme client against a mock server.
84
+ - `tests/test_fastapi_roundtrip.py`: `spec2py fastapi` on `tests/fastapi_app/app.py`, then calls through `ASGITransport`.
85
+ - `tests/test_static_gates.py` (marked `slow`): mypy, pyright, ty and ruff on generated clients.
86
+ - `tests/test_emit.py`: golden snapshots in `tests/golden/`, determinism, regeneration safety.
87
+ - `tests/test_properties.py`: Hypothesis round trips of random schemas and payloads.
spec2py-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brendan Fahy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
spec2py-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,228 @@
1
+ Metadata-Version: 2.5
2
+ Name: spec2py
3
+ Version: 0.1.0
4
+ Summary: A Python-only OpenAPI client generator: Pydantic v2 models, an httpx2 runtime, sync and async from one source, with pagination, retries and streaming built in.
5
+ Project-URL: Homepage, https://github.com/f4hy/spec2py
6
+ Project-URL: Issues, https://github.com/f4hy/spec2py/issues
7
+ Author-email: Brendan Fahy <bmfahy@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: client,codegen,fastapi,httpx,openapi,pydantic,sdk,swagger
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Software Development :: Code Generators
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.14
19
+ Requires-Dist: pyyaml>=6.0.2
20
+ Requires-Dist: ruff>=0.15.0
21
+ Requires-Dist: spec2py-runtime<0.2.0,>=0.1.0
22
+ Provides-Extra: fastapi
23
+ Requires-Dist: fastapi>=0.120; extra == 'fastapi'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # spec2py
27
+
28
+ Ergonomic Python SDKs with pagination, streaming, and maintainable regeneration.
29
+
30
+ spec2py turns OpenAPI documents into resource-oriented Python clients with
31
+ Pydantic v2 models, sync and async interfaces, and a shared
32
+ [httpx2](https://github.com/pydantic/httpx2) runtime. Overlays, API diffs, and
33
+ preserved customization directories help you maintain a client as its API evolves.
34
+
35
+ **Experimental alpha.** Generated APIs and runtime behavior may change. Review
36
+ `NOTES.md` and test generated clients against your service before distributing them.
37
+
38
+ ```console
39
+ $ uvx spec2py generate https://api.acme.com/openapi.json -o clients/acme
40
+ $ uvx --with fastapi spec2py fastapi myapp.main:app -o clients/myapp
41
+ ```
42
+
43
+ ```python
44
+ from acme import Acme, AsyncAcme
45
+
46
+ client = Acme(api_key=..., timeout=20.0, max_retries=3)
47
+
48
+ invoice = client.invoices.create(customer_id="cus_1", amount=4200)
49
+
50
+ for inv in client.invoices.list(status="open"): # auto-paginates
51
+ print(inv.id)
52
+
53
+ with client.completions.stream(prompt="hi") as events: # SSE
54
+ for event in events:
55
+ print(event.text)
56
+
57
+ raw = client.with_raw_response.invoices.retrieve("inv_1") # headers, status
58
+ raw.headers["x-request-id"], raw.parse()
59
+
60
+ async with AsyncAcme() as aclient:
61
+ page = await aclient.invoices.list()
62
+ async for inv in aclient.invoices.list():
63
+ ...
64
+ ```
65
+
66
+ Requires Python 3.14 for both generation **and applications using generated clients**.
67
+
68
+ ## When to choose spec2py
69
+
70
+ Use it when you want a Python-only SDK with methods such as
71
+ `client.invoices.create(...)`, built-in pagination and streaming, and a repeatable
72
+ way to regenerate without losing your custom code. Runtime fixes can be delivered
73
+ through dependency updates within the supported compatibility range.
74
+
75
+ If your SDK must support older Python versions, or you need multiple target
76
+ languages, evaluate [OpenAPI Generator](https://openapi-generator.tech/).
77
+ [openapi-python-client](https://github.com/openapi-generators/openapi-python-client)
78
+ is another established Python-focused option with customizable templates.
79
+ spec2py emphasizes its integrated SDK interface and maintenance workflow; it does
80
+ not claim broader compatibility or better performance than those projects.
81
+
82
+ ## What you get
83
+
84
+ - **Code you'd write by hand.** One client object, resources as attributes,
85
+ path parameters positional, everything else keyword-only, docstrings from the
86
+ spec, `@deprecated` on deprecated operations. CI checks fixture and corpus clients with
87
+ `mypy --strict`, strict pyright, ty and ruff, including Stripe and GitHub specs.
88
+ These checks do not guarantee that every input spec produces correct behavior.
89
+ - **One source, two clients.** Resources are generated once as async code; the
90
+ sync variant is derived mechanically from the AST, so the two can't drift.
91
+ - **"Omit" versus "send null".** Optional parameters default to `NOT_GIVEN`, so
92
+ `update(memo=None)` sends `{"memo": null}` and `update()` sends `{}`.
93
+ - **Tolerant of additive changes.** Responses retain unknown fields and tolerate
94
+ unknown enum values. Structural response validation rejects malformed payloads
95
+ by default; explicit best-effort parsing can return raw values or missing
96
+ attributes. Request bodies are validated before sending. See the
97
+ [validation and compatibility policy](https://github.com/f4hy/spec2py/blob/main/runtime/README.md#validation-and-compatibility).
98
+ - **Typed errors.** `NotFoundError`, `RateLimitError`, `UnprocessableEntityError`
99
+ and others, each with `.body` plus `.parsed`, the error model declared for that
100
+ status.
101
+ - **Runtime behaviour that's fixed by upgrading, not regenerating.** Retries,
102
+ auth, pagination, streaming and uploads live in
103
+ [`spec2py-runtime`](https://github.com/f4hy/spec2py/blob/main/runtime/README.md), not in generated code.
104
+ - **Deterministic output.** The same spec, config, generator and formatter versions produce byte-identical
105
+ files, so diffs in review mean something.
106
+
107
+ ## Commands
108
+
109
+ | Command | What it does |
110
+ | --- | --- |
111
+ | `spec2py generate [SPEC]` | Generate a client from a file, URL or `module:app`. `--check` fails if the client on disk is stale. |
112
+ | `spec2py fastapi module:app` | Same, from a FastAPI app, in one command. |
113
+ | `spec2py lint [SPEC]` | Explains what will generate poorly, ranked by impact. `--fix-overlay fixes.yaml` writes a starter Overlay for the mechanical fixes. |
114
+ | `spec2py update` | Regenerates, prints the API diff (breaking changes flagged) and suggests a semver bump. `--check` is for CI. |
115
+ | `spec2py diff OLD NEW` | Compares the client API two specs would produce. `--fail-on-breaking`. |
116
+ | `spec2py score [SPEC]` | Quality scorecard: size, documentation, detected pagination and streaming, approximations, and `--typecheck`. |
117
+ | `spec2py ir [SPEC]` | Prints the IR (or the normalized spec) as JSON, for debugging. |
118
+
119
+ ## Inputs
120
+
121
+ Swagger 2.0, OpenAPI 3.0, 3.1 and 3.2 are supported. 2.0 and 3.0 are
122
+ up-converted to 3.1 semantics. External `$ref`s (files and URLs) are bundled.
123
+ OpenAPI 3.2 `itemSchema` types streaming events.
124
+
125
+ ## Fixing a spec without forking it
126
+
127
+ Real-world specs are often wrong. Instead of editing generated code, fix the
128
+ input:
129
+
130
+ - **Overlays.** [OpenAPI Overlay](https://spec.openapis.org/overlay/latest.html)
131
+ documents (JSONPath-targeted patches) are applied on load, so you can keep a
132
+ small file of fixes and keep pulling the vendor's spec.
133
+ - **Config** in `pyproject.toml`:
134
+
135
+ ```toml
136
+ [tool.spec2py]
137
+ spec = "https://api.acme.com/openapi.json"
138
+ output = "clients/acme"
139
+ package = "acme"
140
+ client-name = "Acme"
141
+ overlays = ["overlays/fixes.yaml"]
142
+ group-by = "tag" # or "path"
143
+ exclude-paths = ["/internal/*"]
144
+ idempotency-header = "Idempotency-Key"
145
+ package-version = "1.4.0"
146
+
147
+ [tool.spec2py.rename-models]
148
+ InvoiceDTO = "Invoice"
149
+
150
+ [tool.spec2py.operations."GET /invoices"]
151
+ name = "list"
152
+ resource = "invoices"
153
+ pagination = { style = "cursor", items = "data", cursor-param = "after", next-cursor = "last_id" }
154
+
155
+ [tool.spec2py.operations.createCompletion]
156
+ stream = "sse"
157
+ ```
158
+
159
+ ## Extending a client
160
+
161
+ Never edit generated files; regeneration overwrites them (and `--check` notices).
162
+ Instead:
163
+
164
+ - **`_custom/`.** Files in the package's `_custom/` directory are never touched.
165
+ Names in `_custom/__init__.py`'s `__all__` are re-exported from the package root.
166
+ - **Subclasses.** `custom-resources = { invoices = "invoices:Invoices" }` makes
167
+ the client instantiate your `_custom/invoices.py` subclass (`Invoices` and
168
+ `AsyncInvoices`) for that resource.
169
+ - **Hooks and auth.** `Hooks(on_request=[...], on_response=[...])` for logging,
170
+ signing and test doubles; any `httpx2.Auth` as `auth=`; `transport=` or
171
+ `http_client=` for your own stack.
172
+
173
+ ## How it works
174
+
175
+ The generator is a compiler with five stages. Each later stage reads only the
176
+ previous stage's output:
177
+
178
+ 1. **Load**: a file, URL or FastAPI app; Overlays and config are applied.
179
+ 2. **Normalize**: Swagger 2.0 and OpenAPI 3.0 are rewritten into 3.1 semantics,
180
+ and external `$ref`s are bundled.
181
+ 3. **Model IR**: a typed, language-neutral graph of schemas, operations and
182
+ security schemes (`spec2py ir` prints it).
183
+ 4. **Plan**: names, the schema-to-Python type mapping, resource grouping,
184
+ signatures, and pagination and streaming detection.
185
+ 5. **Emit**: Python AST (never string templates), formatted by ruff. `NOTES.md`
186
+ records every approximation.
187
+
188
+ ### Type mapping
189
+
190
+ | JSON Schema | Python |
191
+ | --- | --- |
192
+ | `object` with `properties` | `BaseModel` (`extra="allow"`) |
193
+ | required / optional field | `T` / `T \| None = None` (responses), `T \| NotGiven` (requests) |
194
+ | `nullable`, `type: [T, "null"]` | `T \| None`, absent vs null via `model_fields_set` |
195
+ | `oneOf` + `discriminator` | `Annotated[A \| B, Field(discriminator=...)]` |
196
+ | `oneOf` / `anyOf` | `A \| B` (lint warns) |
197
+ | `allOf` | inheritance from one base; extra bases are flattened, and so is a base whose field type would change |
198
+ | `enum` | `type X = Annotated[Literal[...], Tolerant]` (unknown values accepted on responses, rejected on requests) |
199
+ | `additionalProperties: {schema}` | `dict[str, T]` |
200
+ | recursive `$ref` | forward references (PEP 649) |
201
+ | `date-time`, `date`, `uuid`, `binary` | `datetime`, `date`, `UUID`, `FileTypes` in / `bytes` out |
202
+ | untyped `{}` | `object` (lint points at an Overlay fix) |
203
+
204
+ ### Pagination detection
205
+
206
+ Cursor (`cursor`/`after`/`page_token`... with a next-cursor field, or Stripe-style
207
+ `starting_after` with `has_more`), offset (`offset` + `limit`), page number
208
+ (`page`), and RFC 8288 `Link` headers are all detected. You can also declare
209
+ pagination with `x-pagination` or config. Sync list methods return a `Page[T]`;
210
+ async ones return a paginator you can `await` for the first page or `async for`
211
+ over for every item.
212
+
213
+ ## Development
214
+
215
+ ```bash
216
+ uv sync --all-packages # generator + runtime (uv workspace) + dev tools
217
+ uv run pytest -q # includes strict type checks of generated clients
218
+ uv run ruff check . && uv run ruff format --check . && uv run mypy && uv run pyright
219
+ uv run corpus/run.py --gates # real-world specs (Stripe, GitHub, OpenAI, Twilio...) + scorecard
220
+ SPEC2PY_UPDATE_GOLDEN=1 uv run pytest tests/test_emit.py tests/test_normalize_ir.py # accept output changes
221
+ ```
222
+
223
+ Releases: push a `v*` tag. CI builds `spec2py` and `spec2py-runtime` and
224
+ publishes both to PyPI through trusted publishing.
225
+
226
+ ## License
227
+
228
+ MIT