apiconn 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.
- apiconn-0.1.0/CHANGELOG.md +9 -0
- apiconn-0.1.0/LICENSE +21 -0
- apiconn-0.1.0/PKG-INFO +72 -0
- apiconn-0.1.0/README.md +51 -0
- apiconn-0.1.0/docs/api.md +154 -0
- apiconn-0.1.0/examples/local_service.py +52 -0
- apiconn-0.1.0/pyproject.toml +41 -0
- apiconn-0.1.0/pyproject.toml.orig +32 -0
- apiconn-0.1.0/scripts/check_distribution.py +229 -0
- apiconn-0.1.0/src/apiconn/__init__.py +13 -0
- apiconn-0.1.0/src/apiconn/auth.py +48 -0
- apiconn-0.1.0/src/apiconn/client.py +273 -0
- apiconn-0.1.0/src/apiconn/graphql.py +45 -0
- apiconn-0.1.0/src/apiconn/operations.py +118 -0
- apiconn-0.1.0/src/apiconn/pagination.py +83 -0
- apiconn-0.1.0/src/apiconn/py.typed +0 -0
- apiconn-0.1.0/src/apiconn/resources.py +74 -0
- apiconn-0.1.0/tests/test_graphql_pagination.py +213 -0
- apiconn-0.1.0/tests/test_rest.py +161 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- Explicit API connections, operation definitions, finite JSON validators and
|
|
6
|
+
REST resource CRUD with selected redacted credentials and confined endpoints.
|
|
7
|
+
- Native GraphQL query/mutation requests and partial-error results.
|
|
8
|
+
- Bounded REST page/cursor iteration and sync/async interfaces over requ with
|
|
9
|
+
explicit ownership, status/response errors and no automatic mutation retries.
|
apiconn-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Outside Labs
|
|
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.
|
apiconn-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: apiconn
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Operation-first REST and GraphQL API connections over requ
|
|
5
|
+
Author: ellainng
|
|
6
|
+
Author-email: ellainng <299958882+ellainng@users.noreply.github.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Dist: requ>=0.1.0,<0.2.0
|
|
16
|
+
Requires-Python: >=3.14
|
|
17
|
+
Project-URL: Homepage, https://github.com/wispsy/apiconn
|
|
18
|
+
Project-URL: Repository, https://github.com/wispsy/apiconn
|
|
19
|
+
Project-URL: Issues, https://github.com/wispsy/apiconn/issues
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# apiconn
|
|
23
|
+
|
|
24
|
+
Operation-first REST and GraphQL API connections over
|
|
25
|
+
[requ](https://github.com/wispsy/requ). Python 3.14+, MIT.
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pip install apiconn
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from apiconn import API
|
|
33
|
+
|
|
34
|
+
with API.rest('https://api.example.com/v1', token='selected-token') as api:
|
|
35
|
+
users = api.resource('users')
|
|
36
|
+
user = users.get(123)
|
|
37
|
+
users.update(123, name='Ash')
|
|
38
|
+
|
|
39
|
+
api.operation('activate_user', method='POST', path='users/{id}/activate')
|
|
40
|
+
result = api.call('activate_user', id=123, json={'active': True})
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from apiconn import AsyncAPI
|
|
45
|
+
|
|
46
|
+
async def user_name():
|
|
47
|
+
async with AsyncAPI.graphql('https://api.example.com/graphql') as api:
|
|
48
|
+
data = await api.query('query { user { name } }')
|
|
49
|
+
return data['user']['name']
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- Explicit discoverable operations, optional input/output validators and Connector
|
|
53
|
+
protocols. REST resource CRUD is a convenience over operations.
|
|
54
|
+
- Native GraphQL documents/variables, with partial data and errors preserved.
|
|
55
|
+
- Selected bearer/basic/header credentials, confined endpoints and finite JSON.
|
|
56
|
+
- Bounded page/cursor iteration with cycle detection and no automatic next-URL fetch.
|
|
57
|
+
- Sync and async interfaces with explicit owned/borrowed transport lifecycle.
|
|
58
|
+
|
|
59
|
+
HTTP methods, TLS, pooling, headers, timeouts and request/response bytes belong to
|
|
60
|
+
requ. Its async I/O runs in worker threads; canceling an await does not undo a
|
|
61
|
+
request already sent. Mutations are never automatically retried. No OAuth,
|
|
62
|
+
provider discovery, caching or persistence is installed implicitly.
|
|
63
|
+
|
|
64
|
+
See [the API contract](docs/api.md) for examples, bounds and error semantics.
|
|
65
|
+
Run [the local service example](examples/local_service.py) without external
|
|
66
|
+
credentials. `expose_api` serves APIs; apiconn consumes them. Other Wispsy packages
|
|
67
|
+
are optional consumers, not core dependencies.
|
|
68
|
+
|
|
69
|
+
Development: `uv sync`, then
|
|
70
|
+
`uv run python -W error::ResourceWarning -m unittest discover -s tests -v`.
|
|
71
|
+
Verify exact archives and independent installations with
|
|
72
|
+
`uv run python scripts/check_distribution.py`.
|
apiconn-0.1.0/README.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# apiconn
|
|
2
|
+
|
|
3
|
+
Operation-first REST and GraphQL API connections over
|
|
4
|
+
[requ](https://github.com/wispsy/requ). Python 3.14+, MIT.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
pip install apiconn
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from apiconn import API
|
|
12
|
+
|
|
13
|
+
with API.rest('https://api.example.com/v1', token='selected-token') as api:
|
|
14
|
+
users = api.resource('users')
|
|
15
|
+
user = users.get(123)
|
|
16
|
+
users.update(123, name='Ash')
|
|
17
|
+
|
|
18
|
+
api.operation('activate_user', method='POST', path='users/{id}/activate')
|
|
19
|
+
result = api.call('activate_user', id=123, json={'active': True})
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from apiconn import AsyncAPI
|
|
24
|
+
|
|
25
|
+
async def user_name():
|
|
26
|
+
async with AsyncAPI.graphql('https://api.example.com/graphql') as api:
|
|
27
|
+
data = await api.query('query { user { name } }')
|
|
28
|
+
return data['user']['name']
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
- Explicit discoverable operations, optional input/output validators and Connector
|
|
32
|
+
protocols. REST resource CRUD is a convenience over operations.
|
|
33
|
+
- Native GraphQL documents/variables, with partial data and errors preserved.
|
|
34
|
+
- Selected bearer/basic/header credentials, confined endpoints and finite JSON.
|
|
35
|
+
- Bounded page/cursor iteration with cycle detection and no automatic next-URL fetch.
|
|
36
|
+
- Sync and async interfaces with explicit owned/borrowed transport lifecycle.
|
|
37
|
+
|
|
38
|
+
HTTP methods, TLS, pooling, headers, timeouts and request/response bytes belong to
|
|
39
|
+
requ. Its async I/O runs in worker threads; canceling an await does not undo a
|
|
40
|
+
request already sent. Mutations are never automatically retried. No OAuth,
|
|
41
|
+
provider discovery, caching or persistence is installed implicitly.
|
|
42
|
+
|
|
43
|
+
See [the API contract](docs/api.md) for examples, bounds and error semantics.
|
|
44
|
+
Run [the local service example](examples/local_service.py) without external
|
|
45
|
+
credentials. `expose_api` serves APIs; apiconn consumes them. Other Wispsy packages
|
|
46
|
+
are optional consumers, not core dependencies.
|
|
47
|
+
|
|
48
|
+
Development: `uv sync`, then
|
|
49
|
+
`uv run python -W error::ResourceWarning -m unittest discover -s tests -v`.
|
|
50
|
+
Verify exact archives and independent installations with
|
|
51
|
+
`uv run python scripts/check_distribution.py`.
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# API contract
|
|
2
|
+
|
|
3
|
+
`API.rest(base_url, *, token=None, auth=None, headers=None, client=None)` selects a
|
|
4
|
+
synchronous REST connection. `API.graphql(endpoint_url, ...)` selects a GraphQL
|
|
5
|
+
endpoint. `AsyncAPI.rest` / `AsyncAPI.graphql` use `requ.AsyncClient`; their call,
|
|
6
|
+
request, query, mutate and resource methods are awaited. Pagination uses `async for`.
|
|
7
|
+
Python 3.14+ is required. The only runtime dependency is `requ>=0.1.0,<0.2.0`.
|
|
8
|
+
|
|
9
|
+
## Transport ownership
|
|
10
|
+
|
|
11
|
+
Contexts close transports they create. Supplied `requ.Client` / `AsyncClient`
|
|
12
|
+
instances remain caller-owned. Closing an API prevents new operations even when
|
|
13
|
+
its borrowed transport remains open. Sync APIs use `with` / `close`; async APIs
|
|
14
|
+
use `async with` / `await aclose()`.
|
|
15
|
+
|
|
16
|
+
To configure HTTP limits, supply an explicitly configured requ client:
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
from apiconn import API
|
|
20
|
+
from requ import Client
|
|
21
|
+
|
|
22
|
+
with Client(timeout=5, max_bytes=1_000_000, max_connections=4) as transport:
|
|
23
|
+
with API.rest('https://api.example.com/v1', client=transport) as api:
|
|
24
|
+
result = api.resource('users').get(123)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
requ owns TLS, pooling, query encoding, headers, byte/JSON bodies, framing and
|
|
28
|
+
transport errors. Its socket timeout is not a DNS or total deadline. Async I/O runs
|
|
29
|
+
in worker threads; cancellation stops waiting but a dispatched mutation can still
|
|
30
|
+
complete. There is no implicit retry, replay or rate-limit sleep. Reconcile remote
|
|
31
|
+
state before explicitly retrying any uncertain mutation.
|
|
32
|
+
|
|
33
|
+
## Operations and REST resources
|
|
34
|
+
|
|
35
|
+
`api.operation(name, *, method, path, description='', input_validator=None,
|
|
36
|
+
output_validator=None)` registers a frozen `Operation`. Duplicate names fail;
|
|
37
|
+
`api.operations` returns an ordered tuple. `Connector` / `AsyncConnector` are small
|
|
38
|
+
structural protocols exposing this inventory and `call`.
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
api.operation('activate_user', method='POST', path='users/{id}/activate')
|
|
42
|
+
value = api.call('activate_user', id=123, json={'active': True})
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`call(name, *, path_params=None, params=None, json=..., headers=None, **path_values)`
|
|
46
|
+
uses only a registered operation. Path values may be supplied as keywords or a
|
|
47
|
+
mapping, without duplicates. Names must exactly match simple template fields;
|
|
48
|
+
attribute access, formatting, empty/dot values and non-string/non-integer values
|
|
49
|
+
are rejected. Each value is URL quoted as a path component. `params` is passed to
|
|
50
|
+
requ and supports repeated keys. `json=None` sends JSON null; omitting JSON sends
|
|
51
|
+
no JSON body. `request(method, path, ...)` performs an explicit unregistered action.
|
|
52
|
+
|
|
53
|
+
Leading `/` on an endpoint is relative to the configured base path. Absolute URLs,
|
|
54
|
+
network paths, query/fragment text, backslashes, encoded template text and dot
|
|
55
|
+
segments fail. Static endpoint text is encoded automatically. Base URLs cannot
|
|
56
|
+
contain credentials, query strings or fragments. Cross-origin redirect clients
|
|
57
|
+
are rejected; requ also rejects HTTP downgrade. Redirects for mutation methods
|
|
58
|
+
remain non-2xx errors. These rules select an API origin, not an SSRF/network policy.
|
|
59
|
+
|
|
60
|
+
`api.resource('users')` provides:
|
|
61
|
+
|
|
62
|
+
| Method | Request |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| list(params=None) | GET users |
|
|
65
|
+
| get(identifier, params=None) | GET users/{id} |
|
|
66
|
+
| create(json=..., **fields) | POST users |
|
|
67
|
+
| update(identifier, json=..., **fields) | PATCH users/{id} |
|
|
68
|
+
| delete(identifier) | DELETE users/{id} |
|
|
69
|
+
|
|
70
|
+
Select either explicit JSON or keyword fields for create/update. Resource methods
|
|
71
|
+
return finite JSON, or None for an empty response. PUT and other conventions use
|
|
72
|
+
explicit operations. GraphQL has no generic resource CRUD interface.
|
|
73
|
+
|
|
74
|
+
Validators are `Callable[[JSONValue], None]`: return normally to accept, raise to
|
|
75
|
+
reject. Input validation occurs before dispatch; output validation follows JSON
|
|
76
|
+
parsing. No model/schema framework is required. Validators do not transform data.
|
|
77
|
+
Applications can compose frozen operation metadata with their own typed contracts.
|
|
78
|
+
|
|
79
|
+
## Credentials
|
|
80
|
+
|
|
81
|
+
Select `token='...'` as shorthand for `BearerAuth`, or pass `auth=BearerAuth(...)`,
|
|
82
|
+
`BasicAuth(username, password)` (UTF-8), or `HeaderAuth(name, value)`. Representations
|
|
83
|
+
redact credential values. An `Auth` protocol permits explicitly supplied policies
|
|
84
|
+
whose `headers()` returns a mapping. There is no environment credential lookup,
|
|
85
|
+
OAuth negotiation, token refresh or credential persistence. Common headers are
|
|
86
|
+
copied; per-call headers may override common headers case-insensitively, but cannot
|
|
87
|
+
override selected credential headers. requ reserves transport/framing headers.
|
|
88
|
+
Credentials travel in headers to the selected API origin. Use HTTPS for external
|
|
89
|
+
services. HTTP remains available for local services and deliberately selected APIs.
|
|
90
|
+
|
|
91
|
+
## GraphQL
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
with API.graphql('https://api.example.com/graphql', token='selected-token') as api:
|
|
95
|
+
data = api.query('query User($id: ID!) { user(id: $id) { name } }',
|
|
96
|
+
variables={'id': '123'}, operation_name='User')
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`query(document, *, variables=None, operation_name=None)` and `mutate(...)` POST
|
|
100
|
+
the native GraphQL envelope. The document, not the method name, determines query
|
|
101
|
+
or mutation semantics; apiconn does not rewrite or parse GraphQL syntax. Variables
|
|
102
|
+
must contain finite JSON; operation names are GraphQL names. Successful calls
|
|
103
|
+
return `data` (object or null). Errors raise `GraphQLError` with `.errors`, optional
|
|
104
|
+
partial `.data`, and `.response`. HTTP failures stay `APIStatusError`; malformed
|
|
105
|
+
finite JSON or GraphQL envelopes raise `InvalidResponseError`.
|
|
106
|
+
|
|
107
|
+
## Explicit bounded pagination
|
|
108
|
+
|
|
109
|
+
Register a GET operation, then iterate items:
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from apiconn import CursorPagination, PagePagination
|
|
113
|
+
|
|
114
|
+
api.operation('users.list', method='GET', path='users')
|
|
115
|
+
for user in api.paginate('users.list', pagination=PagePagination(max_pages=20)):
|
|
116
|
+
print(user)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`PagePagination(items_key='items', parameter='page', start=1, max_pages=100)`
|
|
120
|
+
expects an object containing an items array and stops on an empty array. It may
|
|
121
|
+
need one extra empty request after the last nonempty page. `CursorPagination(
|
|
122
|
+
items_key='items', parameter='cursor', next_cursor_key='next_cursor', start=None,
|
|
123
|
+
max_pages=100)` requires a next cursor string or explicit null on every page and
|
|
124
|
+
stops on null. Cursors are opaque query values, never navigable URLs. Repeated
|
|
125
|
+
cursors fail before another request. API-specific keys/initial state are explicit.
|
|
126
|
+
|
|
127
|
+
`paginate(name, *, pagination, params=None, **call_options)` owns its strategy's
|
|
128
|
+
query parameter; passing that same key in params fails. Strategies use top-level
|
|
129
|
+
JSON keys. Every page is bounded by requ; items are yielded without aggregating
|
|
130
|
+
all pages. A page-limit error may follow already yielded items. Limits cause an
|
|
131
|
+
error rather than silently claiming a complete collection. Only GET operations
|
|
132
|
+
are paginated in this release; GraphQL connections use explicit query calls.
|
|
133
|
+
|
|
134
|
+
## Errors
|
|
135
|
+
|
|
136
|
+
| Error | Meaning |
|
|
137
|
+
| --- | --- |
|
|
138
|
+
| APIStatusError (requ.HTTPStatusError) | Any non-2xx API status, including redirects; response preserved |
|
|
139
|
+
| InvalidResponseError (ValueError) | Invalid JSON media type, finite JSON or GraphQL envelope; response preserved |
|
|
140
|
+
| ValidationError (ValueError) | Selected input/output validator rejected the value; original error chained |
|
|
141
|
+
| GraphQLError (RuntimeError) | Native GraphQL errors, preserving partial data and response |
|
|
142
|
+
| PaginationError / PaginationLimitError (ValueError) | Invalid page, cursor cycle or exhausted bound |
|
|
143
|
+
| requ transport/limit/lifecycle errors | Propagate unchanged; inspect requ's contract |
|
|
144
|
+
|
|
145
|
+
Nonempty API responses must declare application/json or application/*+json.
|
|
146
|
+
Unknown operation names raise KeyError; invalid configuration/paths raise
|
|
147
|
+
TypeError or ValueError. No error automatically triggers another request.
|
|
148
|
+
|
|
149
|
+
## Extension scope
|
|
150
|
+
|
|
151
|
+
A Connector can expose explicit operations for a provider without importing other
|
|
152
|
+
Wispsy frameworks. Provider discovery, OpenAPI import, OAuth refresh, explicit retry
|
|
153
|
+
policies, model relationships, persistence and framework adapters remain future
|
|
154
|
+
work. This release does not claim universal third-party schema compatibility.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Exercise REST and GraphQL without external accounts or credentials."""
|
|
2
|
+
import asyncio
|
|
3
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
4
|
+
import json
|
|
5
|
+
import threading
|
|
6
|
+
from apiconn import API, AsyncAPI
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Handler(BaseHTTPRequestHandler):
|
|
10
|
+
def log_message(self, *args):
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
def do_GET(self):
|
|
14
|
+
self.reply({'id': 123, 'name': 'Ash'})
|
|
15
|
+
|
|
16
|
+
def do_POST(self):
|
|
17
|
+
body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
|
|
18
|
+
self.reply({'data': {'user': {'name': 'Ash'}}} if self.path == '/graphql' else body)
|
|
19
|
+
|
|
20
|
+
def reply(self, value):
|
|
21
|
+
body = json.dumps(value).encode()
|
|
22
|
+
self.send_response(200)
|
|
23
|
+
self.send_header('Content-Type', 'application/json')
|
|
24
|
+
self.send_header('Content-Length', str(len(body)))
|
|
25
|
+
self.end_headers()
|
|
26
|
+
self.wfile.write(body)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def query(base):
|
|
30
|
+
async with AsyncAPI.graphql(base + '/graphql') as api:
|
|
31
|
+
result = await api.query('query { user { name } }')
|
|
32
|
+
assert result == {'user': {'name': 'Ash'}}
|
|
33
|
+
print(result)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main():
|
|
37
|
+
with ThreadingHTTPServer(('127.0.0.1', 0), Handler) as server:
|
|
38
|
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
39
|
+
thread.start()
|
|
40
|
+
base = f'http://127.0.0.1:{server.server_port}'
|
|
41
|
+
try:
|
|
42
|
+
with API.rest(base) as api:
|
|
43
|
+
assert api.resource('users').get(123) == {'id': 123, 'name': 'Ash'}
|
|
44
|
+
assert api.resource('users').create(name='Ella') == {'name': 'Ella'}
|
|
45
|
+
asyncio.run(query(base))
|
|
46
|
+
finally:
|
|
47
|
+
server.shutdown()
|
|
48
|
+
thread.join()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
if __name__ == '__main__':
|
|
52
|
+
main()
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "apiconn"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Operation-first REST and GraphQL API connections over requ"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
dependencies = ["requ>=0.1.0,<0.2.0"]
|
|
8
|
+
license = "MIT"
|
|
9
|
+
license-files = ["LICENSE"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 3 - Alpha",
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"Operating System :: OS Independent",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3.14",
|
|
16
|
+
"Typing :: Typed",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[[project.authors]]
|
|
20
|
+
name = "ellainng"
|
|
21
|
+
email = "299958882+ellainng@users.noreply.github.com"
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://github.com/wispsy/apiconn"
|
|
25
|
+
Repository = "https://github.com/wispsy/apiconn"
|
|
26
|
+
Issues = "https://github.com/wispsy/apiconn/issues"
|
|
27
|
+
|
|
28
|
+
[build-system]
|
|
29
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
30
|
+
build-backend = "uv_build"
|
|
31
|
+
|
|
32
|
+
[tool.uv.build-backend]
|
|
33
|
+
source-include = [
|
|
34
|
+
"tests/**",
|
|
35
|
+
"docs/**",
|
|
36
|
+
"examples/**",
|
|
37
|
+
"scripts/**",
|
|
38
|
+
"LICENSE",
|
|
39
|
+
"README.md",
|
|
40
|
+
"CHANGELOG.md",
|
|
41
|
+
]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "apiconn"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Operation-first REST and GraphQL API connections over requ"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "ellainng", email = "299958882+ellainng@users.noreply.github.com" }
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.14"
|
|
10
|
+
dependencies = ["requ>=0.1.0,<0.2.0"]
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.14",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://github.com/wispsy/apiconn"
|
|
24
|
+
Repository = "https://github.com/wispsy/apiconn"
|
|
25
|
+
Issues = "https://github.com/wispsy/apiconn/issues"
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
29
|
+
build-backend = "uv_build"
|
|
30
|
+
|
|
31
|
+
[tool.uv.build-backend]
|
|
32
|
+
source-include = ["tests/**", "docs/**", "examples/**", "scripts/**", "LICENSE", "README.md", "CHANGELOG.md"]
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Build and verify exact distributions and independent installs."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import base64
|
|
5
|
+
import csv
|
|
6
|
+
from email.parser import BytesParser
|
|
7
|
+
from email.policy import default
|
|
8
|
+
import hashlib
|
|
9
|
+
import io
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import tarfile
|
|
17
|
+
import tempfile
|
|
18
|
+
import tomllib
|
|
19
|
+
import venv
|
|
20
|
+
import zipfile
|
|
21
|
+
|
|
22
|
+
PACKAGE_FILES = {'apiconn/__init__.py', 'apiconn/auth.py', 'apiconn/client.py',
|
|
23
|
+
'apiconn/operations.py', 'apiconn/resources.py', 'apiconn/graphql.py',
|
|
24
|
+
'apiconn/pagination.py', 'apiconn/py.typed'}
|
|
25
|
+
TEST_FILES = {'test_rest.py', 'test_graphql_pagination.py'}
|
|
26
|
+
TEST_DATA_FILES = set()
|
|
27
|
+
EXAMPLE_FILES = {'local_service.py'}
|
|
28
|
+
DIAGNOSTIC_FILES = set()
|
|
29
|
+
SOURCE_FILES = ({'README.md', 'LICENSE', 'CHANGELOG.md', 'docs/api.md',
|
|
30
|
+
'scripts/check_distribution.py'}
|
|
31
|
+
| {f'src/{name}' for name in PACKAGE_FILES}
|
|
32
|
+
| {f'tests/{name}' for name in TEST_FILES}
|
|
33
|
+
| {f'examples/{name}' for name in EXAMPLE_FILES})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def valid_requirements(requirements):
|
|
37
|
+
return len(requirements or []) == 1 and requirements[0].replace(' ', '') in {
|
|
38
|
+
'requ>=0.1.0,<0.2.0', 'requ<0.2.0,>=0.1.0'}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def require(condition: bool, message: str) -> None:
|
|
42
|
+
if not condition:
|
|
43
|
+
raise RuntimeError(message)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def run(args: list[str], *, cwd: Path, capture: bool = False) -> str:
|
|
47
|
+
env = os.environ.copy()
|
|
48
|
+
env.pop('PYTHONPATH', None)
|
|
49
|
+
env.pop('VIRTUAL_ENV', None)
|
|
50
|
+
result = subprocess.run(args, cwd=cwd, env=env, text=True, check=True,
|
|
51
|
+
stdout=subprocess.PIPE if capture else None)
|
|
52
|
+
return result.stdout if capture else ''
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def wheel_files(path: Path) -> dict[str, bytes]:
|
|
56
|
+
with zipfile.ZipFile(path) as archive:
|
|
57
|
+
entries = [entry for entry in archive.infolist() if not entry.is_dir()]
|
|
58
|
+
names = [entry.filename for entry in entries]
|
|
59
|
+
require(len(names) == len(set(names)), 'duplicate wheel entries')
|
|
60
|
+
return {name: archive.read(name) for name in names}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def source_files(path: Path, prefix: str) -> dict[str, bytes]:
|
|
64
|
+
result: dict[str, bytes] = {}
|
|
65
|
+
with tarfile.open(path, 'r:gz') as archive:
|
|
66
|
+
for member in archive:
|
|
67
|
+
require(not member.issym() and not member.islnk(), 'links are forbidden in sdist')
|
|
68
|
+
require(member.isdir() or member.isfile(), 'unexpected sdist member type')
|
|
69
|
+
if member.isdir():
|
|
70
|
+
continue
|
|
71
|
+
require(member.name.startswith(prefix + '/'), 'unexpected sdist root')
|
|
72
|
+
name = member.name.removeprefix(prefix + '/')
|
|
73
|
+
require(name not in result, 'duplicate sdist member')
|
|
74
|
+
file = archive.extractfile(member)
|
|
75
|
+
require(file is not None, 'unreadable sdist member')
|
|
76
|
+
with file:
|
|
77
|
+
result[name] = file.read()
|
|
78
|
+
return result
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def verify_metadata(data: bytes, readme: bytes, version: str) -> None:
|
|
82
|
+
metadata = BytesParser(policy=default).parsebytes(data)
|
|
83
|
+
for key, expected in {'Name': 'apiconn', 'Version': version,
|
|
84
|
+
'Requires-Python': '>=3.14', 'License-Expression': 'MIT',
|
|
85
|
+
'Description-Content-Type': 'text/markdown'}.items():
|
|
86
|
+
require(metadata.get(key) == expected, f'incorrect metadata: {key}')
|
|
87
|
+
require(valid_requirements(metadata.get_all('Requires-Dist')), 'unexpected runtime dependencies')
|
|
88
|
+
require(metadata.get_all('License-File') == ['LICENSE'], 'incorrect license metadata')
|
|
89
|
+
require('Typing :: Typed' in metadata.get_all('Classifier', []), 'missing typing classifier')
|
|
90
|
+
payload = metadata.get_payload(decode=True)
|
|
91
|
+
require(payload is not None, 'README metadata payload is missing')
|
|
92
|
+
require(payload.decode('utf-8').strip() == readme.decode('utf-8').strip(), 'README metadata differs')
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def verify_record(files: dict[str, bytes], dist_info: str) -> None:
|
|
96
|
+
record = f'{dist_info}/RECORD'
|
|
97
|
+
rows = list(csv.reader(io.StringIO(files[record].decode())))
|
|
98
|
+
require(len(rows) == len(files), 'RECORD file count differs')
|
|
99
|
+
require(len({row[0] for row in rows}) == len(rows), 'duplicate RECORD paths')
|
|
100
|
+
require({row[0] for row in rows} == set(files), 'RECORD paths differ')
|
|
101
|
+
for name, digest, size in rows:
|
|
102
|
+
if name == record:
|
|
103
|
+
require(digest == size == '', 'RECORD must not hash itself')
|
|
104
|
+
continue
|
|
105
|
+
expected = base64.urlsafe_b64encode(hashlib.sha256(files[name]).digest()).rstrip(b'=').decode()
|
|
106
|
+
require(digest == f'sha256={expected}', f'RECORD digest differs: {name}')
|
|
107
|
+
require(size == str(len(files[name])), f'RECORD size differs: {name}')
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def verify_install(artifact: Path, sandbox: Path, root: Path, version: str) -> None:
|
|
111
|
+
sandbox.mkdir()
|
|
112
|
+
environment = sandbox / 'environment'
|
|
113
|
+
venv.EnvBuilder(with_pip=False).create(environment)
|
|
114
|
+
python = environment / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')
|
|
115
|
+
# Resolve the released transport from the public index, never a sibling checkout.
|
|
116
|
+
run(['uv', 'pip', 'install', '--python', str(python), '--index-url',
|
|
117
|
+
'https://pypi.org/simple', 'requ==0.1.0'], cwd=sandbox)
|
|
118
|
+
# Source installation may resolve only the already-declared build backend.
|
|
119
|
+
args = ['uv', 'pip', 'install', '--python', str(python), '--no-deps']
|
|
120
|
+
if artifact.suffix == '.whl':
|
|
121
|
+
args.append('--no-index')
|
|
122
|
+
run([*args, str(artifact)], cwd=sandbox)
|
|
123
|
+
probe = (
|
|
124
|
+
'import apiconn, requ, importlib.metadata, json; '
|
|
125
|
+
'print(json.dumps({"file": apiconn.__file__, "version": apiconn.__version__, '
|
|
126
|
+
'"metadata": importlib.metadata.version("apiconn"), '
|
|
127
|
+
'"requirements": importlib.metadata.requires("apiconn"), '
|
|
128
|
+
'"transport_file": requ.__file__, "transport_version": importlib.metadata.version("requ"), '
|
|
129
|
+
'"transport_direct": importlib.metadata.distribution("requ").read_text("direct_url.json")}))'
|
|
130
|
+
)
|
|
131
|
+
installed = json.loads(run([str(python), '-I', '-c', probe], cwd=sandbox, capture=True))
|
|
132
|
+
require(Path(installed['file']).resolve().is_relative_to(environment.resolve()),
|
|
133
|
+
'package imported from outside its isolated environment')
|
|
134
|
+
require(installed['version'] == installed['metadata'] == version, 'installed version differs')
|
|
135
|
+
require(valid_requirements(installed['requirements']), 'installed runtime requirements differ')
|
|
136
|
+
require(installed['transport_version'] == '0.1.0' and installed['transport_direct'] is None,
|
|
137
|
+
'transport must be the released registry distribution')
|
|
138
|
+
require(Path(installed['transport_file']).resolve().is_relative_to(environment.resolve()),
|
|
139
|
+
'transport imported outside its isolated environment')
|
|
140
|
+
tests, examples = sandbox / 'tests', sandbox / 'examples'
|
|
141
|
+
tests.mkdir()
|
|
142
|
+
examples.mkdir()
|
|
143
|
+
for name in TEST_FILES:
|
|
144
|
+
shutil.copyfile(root / 'tests' / name, tests / name)
|
|
145
|
+
for name in TEST_DATA_FILES:
|
|
146
|
+
target = tests / name
|
|
147
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
148
|
+
shutil.copyfile(root / 'tests' / name, target)
|
|
149
|
+
for name in EXAMPLE_FILES:
|
|
150
|
+
shutil.copyfile(root / 'examples' / name, examples / name)
|
|
151
|
+
scripts = sandbox / 'scripts'
|
|
152
|
+
scripts.mkdir()
|
|
153
|
+
for name in DIAGNOSTIC_FILES | {'check_distribution.py'}:
|
|
154
|
+
shutil.copyfile(root / 'scripts' / name, scripts / name)
|
|
155
|
+
run([str(python), '-I', '-W', 'error::ResourceWarning', '-m', 'unittest',
|
|
156
|
+
'discover', '-s', str(tests), '-v'], cwd=sandbox)
|
|
157
|
+
for name in sorted(EXAMPLE_FILES):
|
|
158
|
+
run([str(python), '-I', str(examples / name)], cwd=sandbox)
|
|
159
|
+
print(f'Independent install passed: {artifact.name}', flush=True)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def main() -> None:
|
|
163
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
164
|
+
parser.add_argument('--tag', default='')
|
|
165
|
+
parser.add_argument('--output-dir', type=Path, default=Path('dist'))
|
|
166
|
+
args = parser.parse_args()
|
|
167
|
+
root = Path(__file__).resolve().parents[1]
|
|
168
|
+
config = tomllib.loads((root / 'pyproject.toml').read_text())
|
|
169
|
+
version = config['project']['version']
|
|
170
|
+
require(not args.tag or args.tag == f'v{version}',
|
|
171
|
+
'release tag must match the package version')
|
|
172
|
+
require(config['project']['dependencies'] == ['requ>=0.1.0,<0.2.0'], 'unexpected runtime dependencies')
|
|
173
|
+
output = args.output_dir.resolve()
|
|
174
|
+
output.mkdir(parents=True, exist_ok=True)
|
|
175
|
+
wheel = output / f'apiconn-{version}-py3-none-any.whl'
|
|
176
|
+
source = output / f'apiconn-{version}.tar.gz'
|
|
177
|
+
require({path.name for path in output.iterdir()} <= {wheel.name, source.name, '.gitignore'},
|
|
178
|
+
'output directory contains unexpected files; use an empty build directory')
|
|
179
|
+
run(['uv', 'build', '--sdist', '--wheel', '--no-create-gitignore',
|
|
180
|
+
'--out-dir', str(output), str(root)], cwd=root)
|
|
181
|
+
require(wheel.is_file() and source.is_file(), 'expected distributions were not built')
|
|
182
|
+
files = wheel_files(wheel)
|
|
183
|
+
dist_info = f'apiconn-{version}.dist-info'
|
|
184
|
+
expected_wheel = PACKAGE_FILES | {f'{dist_info}/{name}' for name in
|
|
185
|
+
('METADATA', 'WHEEL', 'RECORD', 'licenses/LICENSE')}
|
|
186
|
+
require(set(files) == expected_wheel, f'wheel allowlist differs: {set(files) ^ expected_wheel}')
|
|
187
|
+
for name in PACKAGE_FILES:
|
|
188
|
+
require(files[name] == (root / 'src' / name).read_bytes(), f'wheel source differs: {name}')
|
|
189
|
+
require(files[f'{dist_info}/licenses/LICENSE'] == (root / 'LICENSE').read_bytes(), 'wheel license differs')
|
|
190
|
+
wheel_metadata = BytesParser(policy=default).parsebytes(files[f'{dist_info}/WHEEL'])
|
|
191
|
+
require(wheel_metadata.get('Root-Is-Purelib') == 'true', 'wheel must be pure Python')
|
|
192
|
+
require(wheel_metadata.get_all('Tag') == ['py3-none-any'], 'unexpected wheel tag')
|
|
193
|
+
verify_metadata(files[f'{dist_info}/METADATA'], (root / 'README.md').read_bytes(), version)
|
|
194
|
+
verify_record(files, dist_info)
|
|
195
|
+
archived = source_files(source, f'apiconn-{version}')
|
|
196
|
+
expected_source = SOURCE_FILES | {'PKG-INFO', 'pyproject.toml', 'pyproject.toml.orig'}
|
|
197
|
+
require(set(archived) == expected_source, f'sdist allowlist differs: {set(archived) ^ expected_source}')
|
|
198
|
+
for name in SOURCE_FILES:
|
|
199
|
+
require(archived[name] == (root / name).read_bytes(), f'sdist source differs: {name}')
|
|
200
|
+
require(archived['pyproject.toml.orig'] == (root / 'pyproject.toml').read_bytes(), 'original configuration differs')
|
|
201
|
+
require(tomllib.loads(archived['pyproject.toml'].decode()) == config, 'sdist configuration semantics differ')
|
|
202
|
+
require(archived['PKG-INFO'] == files[f'{dist_info}/METADATA'], 'sdist and wheel metadata differ')
|
|
203
|
+
with tempfile.TemporaryDirectory(prefix='apiconn-distributions-') as temporary:
|
|
204
|
+
sandbox = Path(temporary)
|
|
205
|
+
rebuild = sandbox / 'rebuild'
|
|
206
|
+
run(['uv', 'build', '--wheel', '--no-create-gitignore', '--out-dir', str(rebuild), str(source)], cwd=sandbox)
|
|
207
|
+
rebuilt = wheel_files(rebuild / wheel.name)
|
|
208
|
+
require(set(rebuilt) == expected_wheel, 'source rebuild allowlist differs')
|
|
209
|
+
build_headers = {f'{dist_info}/WHEEL', f'{dist_info}/RECORD'}
|
|
210
|
+
require({name: data for name, data in rebuilt.items() if name not in build_headers}
|
|
211
|
+
== {name: data for name, data in files.items() if name not in build_headers},
|
|
212
|
+
'source rebuild package, license or metadata bytes differ')
|
|
213
|
+
rebuilt_metadata = BytesParser(policy=default).parsebytes(rebuilt[f'{dist_info}/WHEEL'])
|
|
214
|
+
# The declared backend range can resolve a newer uv_build than the
|
|
215
|
+
# invoking uv binary. Only the build-tool Generator header may differ.
|
|
216
|
+
require([(key, value) for key, value in rebuilt_metadata.items() if key != 'Generator']
|
|
217
|
+
== [(key, value) for key, value in wheel_metadata.items() if key != 'Generator'],
|
|
218
|
+
'source rebuild wheel compatibility metadata differs')
|
|
219
|
+
require(len(rebuilt_metadata.get_all('Generator', [])) == 1, 'missing build generator')
|
|
220
|
+
verify_record(rebuilt, dist_info)
|
|
221
|
+
verify_install(wheel, sandbox / 'wheel-install', root, version)
|
|
222
|
+
verify_install(source, sandbox / 'source-install', root, version)
|
|
223
|
+
print('Exact archives, metadata, RECORD, rebuild parity, installed tests and examples passed.')
|
|
224
|
+
for artifact in (wheel, source):
|
|
225
|
+
print(f'{hashlib.sha256(artifact.read_bytes()).hexdigest()} {artifact.name}')
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
if __name__ == '__main__':
|
|
229
|
+
main()
|