apiconn 0.1.0__py3-none-any.whl
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/__init__.py +13 -0
- apiconn/auth.py +48 -0
- apiconn/client.py +273 -0
- apiconn/graphql.py +45 -0
- apiconn/operations.py +118 -0
- apiconn/pagination.py +83 -0
- apiconn/py.typed +0 -0
- apiconn/resources.py +74 -0
- apiconn-0.1.0.dist-info/METADATA +72 -0
- apiconn-0.1.0.dist-info/RECORD +12 -0
- apiconn-0.1.0.dist-info/WHEEL +4 -0
- apiconn-0.1.0.dist-info/licenses/LICENSE +21 -0
apiconn/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Operation-first API connections over requ."""
|
|
2
|
+
|
|
3
|
+
from .auth import Auth, BasicAuth, BearerAuth, HeaderAuth
|
|
4
|
+
from .client import API, AsyncAPI, AsyncConnector, Connector
|
|
5
|
+
from .operations import APIStatusError, InvalidResponseError, Operation, ValidationError
|
|
6
|
+
from .resources import AsyncResource, Resource
|
|
7
|
+
from .graphql import GraphQLError
|
|
8
|
+
from .pagination import CursorPagination, PagePagination, PaginationError, PaginationLimitError
|
|
9
|
+
|
|
10
|
+
__version__ = '0.1.0'
|
|
11
|
+
__all__ = ['AsyncAPI', 'AsyncConnector', 'AsyncResource', 'GraphQLError', 'PagePagination',
|
|
12
|
+
'CursorPagination', 'PaginationError', 'PaginationLimitError', 'API', 'Connector', 'Operation', 'Resource', 'Auth', 'BasicAuth', 'BearerAuth',
|
|
13
|
+
'HeaderAuth', 'APIStatusError', 'InvalidResponseError', 'ValidationError']
|
apiconn/auth.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Explicit credential policies; no ambient lookup or token refresh."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Protocol, runtime_checkable
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@runtime_checkable
|
|
10
|
+
class Auth(Protocol):
|
|
11
|
+
def headers(self) -> Mapping[str, str]: ...
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True, slots=True)
|
|
15
|
+
class BearerAuth:
|
|
16
|
+
token: str = field(repr=False)
|
|
17
|
+
|
|
18
|
+
def __post_init__(self):
|
|
19
|
+
if not isinstance(self.token, str) or not self.token or not self.token.isascii() or any(ord(c) <= 32 or ord(c) == 127 for c in self.token):
|
|
20
|
+
raise ValueError('bearer token must be nonempty ASCII without whitespace or controls')
|
|
21
|
+
|
|
22
|
+
def headers(self) -> Mapping[str, str]:
|
|
23
|
+
return {'Authorization': 'Bearer ' + self.token}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class BasicAuth:
|
|
28
|
+
username: str = field(repr=False)
|
|
29
|
+
password: str = field(repr=False)
|
|
30
|
+
|
|
31
|
+
def __post_init__(self):
|
|
32
|
+
if not isinstance(self.username, str) or not isinstance(self.password, str):
|
|
33
|
+
raise TypeError('basic credentials must be strings')
|
|
34
|
+
if ':' in self.username or any(ord(c) < 32 or ord(c) == 127 for c in self.username + self.password):
|
|
35
|
+
raise ValueError('invalid basic credentials')
|
|
36
|
+
|
|
37
|
+
def headers(self) -> Mapping[str, str]:
|
|
38
|
+
token = base64.b64encode(f'{self.username}:{self.password}'.encode('utf-8')).decode('ascii')
|
|
39
|
+
return {'Authorization': 'Basic ' + token}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class HeaderAuth:
|
|
44
|
+
name: str
|
|
45
|
+
value: str = field(repr=False)
|
|
46
|
+
|
|
47
|
+
def headers(self) -> Mapping[str, str]:
|
|
48
|
+
return {self.name: self.value}
|
apiconn/client.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Operation-first API connections with explicit transport ownership."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
import re
|
|
5
|
+
from typing import Protocol, Self, runtime_checkable
|
|
6
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
7
|
+
|
|
8
|
+
from requ import AsyncClient, Client, ClientClosedError, JSONValue
|
|
9
|
+
|
|
10
|
+
from .auth import Auth, BearerAuth
|
|
11
|
+
from .operations import MISSING, Operation, decode_response, endpoint, path_fields, validate
|
|
12
|
+
|
|
13
|
+
_HEADER = re.compile(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+\Z")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def base_url(value: str) -> str:
|
|
17
|
+
if not isinstance(value, str):
|
|
18
|
+
raise TypeError('base URL must be a string')
|
|
19
|
+
if not value.isascii() or any(ord(c) <= 32 or ord(c) == 127 for c in value):
|
|
20
|
+
raise ValueError('base URL must be ASCII without whitespace or controls')
|
|
21
|
+
parts = urlsplit(value)
|
|
22
|
+
if parts.scheme not in {'http', 'https'} or not parts.hostname or parts.username is not None or parts.password is not None:
|
|
23
|
+
raise ValueError('absolute HTTP(S) base URL without credentials required')
|
|
24
|
+
if parts.query or parts.fragment or '\\' in parts.netloc or '%' in parts.netloc:
|
|
25
|
+
raise ValueError('base URL cannot contain query, fragment or invalid authority')
|
|
26
|
+
if parts.port is not None and not 1 <= parts.port <= 65535:
|
|
27
|
+
raise ValueError('invalid base URL port')
|
|
28
|
+
path_fields(parts.path)
|
|
29
|
+
if '{' in parts.path or '}' in parts.path:
|
|
30
|
+
raise ValueError('base URL cannot contain path parameters')
|
|
31
|
+
return urlunsplit((parts.scheme, parts.netloc.lower(), parts.path.rstrip('/'), '', ''))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def merge_headers(*sources: Mapping[str, str] | None) -> dict[str, str]:
|
|
35
|
+
result = {}
|
|
36
|
+
for source in sources:
|
|
37
|
+
if source is None:
|
|
38
|
+
continue
|
|
39
|
+
if not isinstance(source, Mapping):
|
|
40
|
+
raise TypeError('headers must be mappings')
|
|
41
|
+
seen = set()
|
|
42
|
+
for name, value in source.items():
|
|
43
|
+
if not isinstance(name, str) or not _HEADER.fullmatch(name) or not isinstance(value, str):
|
|
44
|
+
raise ValueError('invalid header name or value')
|
|
45
|
+
if any(ord(c) < 32 or ord(c) == 127 or ord(c) > 255 for c in value):
|
|
46
|
+
raise ValueError('invalid header value')
|
|
47
|
+
key = name.lower()
|
|
48
|
+
if key in seen:
|
|
49
|
+
raise ValueError('duplicate case-insensitive header')
|
|
50
|
+
seen.add(key)
|
|
51
|
+
result[key] = value
|
|
52
|
+
return result
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@runtime_checkable
|
|
56
|
+
class Connector(Protocol):
|
|
57
|
+
@property
|
|
58
|
+
def operations(self) -> tuple[Operation, ...]: ...
|
|
59
|
+
|
|
60
|
+
def call(self, name: str, **kwargs) -> JSONValue: ...
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class _Connection[T: (Client, AsyncClient)]:
|
|
64
|
+
"""Configured API origin; owns its client unless one is explicitly supplied."""
|
|
65
|
+
|
|
66
|
+
def __init__(self, url: str, *, client: T, owned: bool, auth: Auth | None = None,
|
|
67
|
+
token: str | None = None, headers: Mapping[str, str] | None = None):
|
|
68
|
+
self._base = base_url(url)
|
|
69
|
+
if token is not None:
|
|
70
|
+
if auth is not None:
|
|
71
|
+
raise ValueError('select auth or token, not both')
|
|
72
|
+
auth = BearerAuth(token)
|
|
73
|
+
self._auth = auth
|
|
74
|
+
self._headers = merge_headers(headers)
|
|
75
|
+
self._operations: dict[str, Operation] = {}
|
|
76
|
+
self._owned = owned
|
|
77
|
+
self._client = client
|
|
78
|
+
if self._client.allow_cross_origin_redirects:
|
|
79
|
+
raise ValueError('API clients must forbid cross-origin redirects')
|
|
80
|
+
self._closed = False
|
|
81
|
+
self._graphql = False
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def rest(cls, url: str, **kwargs) -> Self:
|
|
85
|
+
return cls(url, **kwargs)
|
|
86
|
+
|
|
87
|
+
@classmethod
|
|
88
|
+
def graphql(cls, url: str, **kwargs) -> Self:
|
|
89
|
+
api = cls(url, **kwargs)
|
|
90
|
+
api._graphql = True
|
|
91
|
+
return api
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def operations(self) -> tuple[Operation, ...]:
|
|
95
|
+
return tuple(self._operations.values())
|
|
96
|
+
|
|
97
|
+
def operation(self, name: str, *, method: str, path: str, **kwargs) -> Operation:
|
|
98
|
+
operation = Operation(name, method, path, **kwargs)
|
|
99
|
+
if name in self._operations:
|
|
100
|
+
raise ValueError('operation is already registered')
|
|
101
|
+
self._operations[name] = operation
|
|
102
|
+
return operation
|
|
103
|
+
|
|
104
|
+
def _prepare(self, operation: Operation, *, path_params=None, params=None,
|
|
105
|
+
json=MISSING, headers=None, **path_values):
|
|
106
|
+
if self._closed:
|
|
107
|
+
raise ClientClosedError('API is closed')
|
|
108
|
+
values = dict(path_params or {})
|
|
109
|
+
if set(values) & set(path_values):
|
|
110
|
+
raise ValueError('duplicate path parameter')
|
|
111
|
+
values.update(path_values)
|
|
112
|
+
url = endpoint(self._base, operation.path, values)
|
|
113
|
+
operation.validate_input(json)
|
|
114
|
+
selected = merge_headers(self._headers, headers)
|
|
115
|
+
if self._auth is not None:
|
|
116
|
+
credentials = merge_headers(self._auth.headers())
|
|
117
|
+
if set(credentials) & set(selected):
|
|
118
|
+
raise ValueError('credential headers cannot be overridden')
|
|
119
|
+
selected.update(credentials)
|
|
120
|
+
options = {'headers': selected, 'params': params}
|
|
121
|
+
if json is not MISSING:
|
|
122
|
+
options['json'] = json
|
|
123
|
+
return operation.method, url, options
|
|
124
|
+
|
|
125
|
+
class API(_Connection[Client]):
|
|
126
|
+
"""Synchronous REST/GraphQL connection with explicit transport ownership."""
|
|
127
|
+
|
|
128
|
+
def __init__(self, url: str, *, client: Client | None = None, **kwargs):
|
|
129
|
+
super().__init__(url, client=Client() if client is None else client, owned=client is None, **kwargs)
|
|
130
|
+
|
|
131
|
+
def resource(self, path: str):
|
|
132
|
+
if self._graphql:
|
|
133
|
+
raise ValueError('GraphQL does not define generic REST resources')
|
|
134
|
+
from .resources import Resource
|
|
135
|
+
return Resource(self, path)
|
|
136
|
+
|
|
137
|
+
def _execute(self, operation: Operation, **kwargs) -> JSONValue:
|
|
138
|
+
method, url, options = self._prepare(operation, **kwargs)
|
|
139
|
+
response = self._client.request(method, url, **options)
|
|
140
|
+
value = decode_response(response)
|
|
141
|
+
validate(operation.output_validator, value, 'output')
|
|
142
|
+
return value
|
|
143
|
+
|
|
144
|
+
def call(self, name: str, **kwargs) -> JSONValue:
|
|
145
|
+
return self._execute(self._operations[name], **kwargs)
|
|
146
|
+
|
|
147
|
+
def request(self, method: str, path: str, **kwargs) -> JSONValue:
|
|
148
|
+
return self._execute(Operation('request', method, path), **kwargs)
|
|
149
|
+
|
|
150
|
+
def query(self, document: str, *, variables=None, operation_name=None) -> JSONValue:
|
|
151
|
+
from .graphql import payload, result
|
|
152
|
+
if not self._graphql:
|
|
153
|
+
raise ValueError('select API.graphql for GraphQL operations')
|
|
154
|
+
operation = Operation('graphql', 'POST', '')
|
|
155
|
+
method, url, options = self._prepare(operation, json=payload(document, variables, operation_name))
|
|
156
|
+
return result(self._client.request(method, url, **options))
|
|
157
|
+
|
|
158
|
+
def mutate(self, document: str, **kwargs) -> JSONValue:
|
|
159
|
+
return self.query(document, **kwargs)
|
|
160
|
+
|
|
161
|
+
def paginate(self, name: str, *, pagination, params=None, **kwargs):
|
|
162
|
+
from .pagination import PaginationLimitError, advance, items, parameters
|
|
163
|
+
if self._operations[name].method != 'GET':
|
|
164
|
+
raise ValueError('REST pagination requires a GET operation')
|
|
165
|
+
selected = parameters(pagination, params)
|
|
166
|
+
state = pagination.start
|
|
167
|
+
seen = {state}
|
|
168
|
+
for _ in range(pagination.max_pages):
|
|
169
|
+
query = dict(selected)
|
|
170
|
+
if state is not None:
|
|
171
|
+
query[pagination.parameter] = state
|
|
172
|
+
value = self.call(name, params=query, **kwargs)
|
|
173
|
+
yield from items(value, pagination.items_key)
|
|
174
|
+
state = advance(pagination, value, state, seen)
|
|
175
|
+
if state is None:
|
|
176
|
+
return
|
|
177
|
+
raise PaginationLimitError('max_pages exhausted before pagination completed')
|
|
178
|
+
|
|
179
|
+
def close(self) -> None:
|
|
180
|
+
self._closed = True
|
|
181
|
+
if self._owned:
|
|
182
|
+
self._client.close()
|
|
183
|
+
|
|
184
|
+
def __enter__(self):
|
|
185
|
+
if self._closed:
|
|
186
|
+
raise ClientClosedError('API is closed')
|
|
187
|
+
return self
|
|
188
|
+
|
|
189
|
+
def __exit__(self, *exc) -> None:
|
|
190
|
+
self.close()
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
@runtime_checkable
|
|
194
|
+
class AsyncConnector(Protocol):
|
|
195
|
+
@property
|
|
196
|
+
def operations(self) -> tuple[Operation, ...]: ...
|
|
197
|
+
|
|
198
|
+
async def call(self, name: str, **kwargs) -> JSONValue: ...
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class AsyncAPI(_Connection[AsyncClient]):
|
|
202
|
+
"""Asynchronous connection using requ's bounded worker-thread transport."""
|
|
203
|
+
|
|
204
|
+
def __init__(self, url: str, *, client: AsyncClient | None = None, **kwargs):
|
|
205
|
+
super().__init__(url, client=AsyncClient() if client is None else client, owned=client is None, **kwargs)
|
|
206
|
+
|
|
207
|
+
async def _execute(self, operation: Operation, **kwargs) -> JSONValue:
|
|
208
|
+
method, url, options = self._prepare(operation, **kwargs)
|
|
209
|
+
response = await self._client.request(method, url, **options)
|
|
210
|
+
value = decode_response(response)
|
|
211
|
+
validate(operation.output_validator, value, 'output')
|
|
212
|
+
return value
|
|
213
|
+
|
|
214
|
+
async def call(self, name: str, **kwargs) -> JSONValue:
|
|
215
|
+
return await self._execute(self._operations[name], **kwargs)
|
|
216
|
+
|
|
217
|
+
async def request(self, method: str, path: str, **kwargs) -> JSONValue:
|
|
218
|
+
return await self._execute(Operation('request', method, path), **kwargs)
|
|
219
|
+
|
|
220
|
+
def resource(self, path: str):
|
|
221
|
+
from .resources import AsyncResource
|
|
222
|
+
if self._graphql:
|
|
223
|
+
raise ValueError('GraphQL does not define generic REST resources')
|
|
224
|
+
return AsyncResource(self, path)
|
|
225
|
+
|
|
226
|
+
async def query(self, document: str, *, variables=None, operation_name=None) -> JSONValue:
|
|
227
|
+
from .graphql import payload, result
|
|
228
|
+
if not self._graphql:
|
|
229
|
+
raise ValueError('select AsyncAPI.graphql for GraphQL operations')
|
|
230
|
+
operation = Operation('graphql', 'POST', '')
|
|
231
|
+
method, url, options = self._prepare(operation, json=payload(document, variables, operation_name))
|
|
232
|
+
return result(await self._client.request(method, url, **options))
|
|
233
|
+
|
|
234
|
+
async def mutate(self, document: str, **kwargs) -> JSONValue:
|
|
235
|
+
return await self.query(document, **kwargs)
|
|
236
|
+
|
|
237
|
+
async def paginate(self, name: str, *, pagination, params=None, **kwargs):
|
|
238
|
+
from .pagination import PaginationLimitError, advance, items, parameters
|
|
239
|
+
if self._operations[name].method != 'GET':
|
|
240
|
+
raise ValueError('REST pagination requires a GET operation')
|
|
241
|
+
selected = parameters(pagination, params)
|
|
242
|
+
state = pagination.start
|
|
243
|
+
seen = {state}
|
|
244
|
+
for _ in range(pagination.max_pages):
|
|
245
|
+
query = dict(selected)
|
|
246
|
+
if state is not None:
|
|
247
|
+
query[pagination.parameter] = state
|
|
248
|
+
value = await self.call(name, params=query, **kwargs)
|
|
249
|
+
for item in items(value, pagination.items_key):
|
|
250
|
+
yield item
|
|
251
|
+
state = advance(pagination, value, state, seen)
|
|
252
|
+
if state is None:
|
|
253
|
+
return
|
|
254
|
+
raise PaginationLimitError('max_pages exhausted before pagination completed')
|
|
255
|
+
|
|
256
|
+
async def aclose(self) -> None:
|
|
257
|
+
self._closed = True
|
|
258
|
+
if self._owned:
|
|
259
|
+
await self._client.aclose()
|
|
260
|
+
|
|
261
|
+
async def __aenter__(self):
|
|
262
|
+
if self._closed:
|
|
263
|
+
raise ClientClosedError('API is closed')
|
|
264
|
+
return self
|
|
265
|
+
|
|
266
|
+
async def __aexit__(self, *exc) -> None:
|
|
267
|
+
await self.aclose()
|
|
268
|
+
|
|
269
|
+
def close(self) -> None:
|
|
270
|
+
raise TypeError('use await aclose() for AsyncAPI')
|
|
271
|
+
|
|
272
|
+
def __enter__(self):
|
|
273
|
+
raise TypeError('use async with for AsyncAPI')
|
apiconn/graphql.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Native GraphQL request envelopes and explicit partial-error results."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
import re
|
|
5
|
+
from requ import JSONValue, Response
|
|
6
|
+
from .operations import InvalidResponseError, decode_response
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class GraphQLError(RuntimeError):
|
|
10
|
+
"""A valid GraphQL error result; partial data and response are preserved."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, errors: list, data: JSONValue, response: Response):
|
|
13
|
+
self.errors = errors
|
|
14
|
+
self.data = data
|
|
15
|
+
self.response = response
|
|
16
|
+
super().__init__(f'GraphQL returned {len(errors)} error(s)')
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def payload(document: str, variables: Mapping | None, operation_name: str | None) -> dict:
|
|
20
|
+
if not isinstance(document, str) or not document.strip():
|
|
21
|
+
raise ValueError('GraphQL document must be a nonempty string')
|
|
22
|
+
result = {'query': document}
|
|
23
|
+
if variables is not None:
|
|
24
|
+
if not isinstance(variables, Mapping):
|
|
25
|
+
raise TypeError('GraphQL variables must be a mapping')
|
|
26
|
+
result['variables'] = dict(variables)
|
|
27
|
+
if operation_name is not None:
|
|
28
|
+
if not isinstance(operation_name, str) or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', operation_name):
|
|
29
|
+
raise ValueError('invalid GraphQL operation name')
|
|
30
|
+
result['operationName'] = operation_name
|
|
31
|
+
return result
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def result(response: Response) -> JSONValue:
|
|
35
|
+
value = decode_response(response)
|
|
36
|
+
if not isinstance(value, dict) or not ({'data', 'errors'} & value.keys()):
|
|
37
|
+
raise InvalidResponseError('invalid GraphQL response envelope', response)
|
|
38
|
+
if 'data' in value and value['data'] is not None and not isinstance(value['data'], dict):
|
|
39
|
+
raise InvalidResponseError('GraphQL data must be an object or null', response)
|
|
40
|
+
if 'errors' in value:
|
|
41
|
+
errors = value['errors']
|
|
42
|
+
if not isinstance(errors, list) or not errors or any(not isinstance(e, dict) or not isinstance(e.get('message'), str) for e in errors):
|
|
43
|
+
raise InvalidResponseError('invalid GraphQL errors', response)
|
|
44
|
+
raise GraphQLError(errors, value.get('data'), response)
|
|
45
|
+
return value['data']
|
apiconn/operations.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Explicit operation definitions and JSON boundary validation."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Mapping
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
import re
|
|
6
|
+
from string import Formatter
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
from requ import HTTPStatusError, JSONValue, Response, encode_json
|
|
10
|
+
|
|
11
|
+
MISSING = object()
|
|
12
|
+
_NAME = re.compile(r'[A-Za-z_][A-Za-z0-9_.-]*\Z')
|
|
13
|
+
_FIELD = re.compile(r'[A-Za-z_][A-Za-z0-9_]*\Z')
|
|
14
|
+
_METHOD = re.compile(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+\Z")
|
|
15
|
+
type Validator = Callable[[JSONValue], None]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ValidationError(ValueError):
|
|
19
|
+
"""A selected input/output validator rejected a value."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InvalidResponseError(ValueError):
|
|
23
|
+
def __init__(self, message: str, response: Response):
|
|
24
|
+
self.response = response
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class APIStatusError(HTTPStatusError):
|
|
29
|
+
"""An API operation returned a non-2xx status, including redirects."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def path_fields(path: str) -> tuple[str, ...]:
|
|
33
|
+
if not isinstance(path, str):
|
|
34
|
+
raise TypeError('operation path must be a string')
|
|
35
|
+
if path.startswith('//') or any(c in path for c in ('?', '#', '\\', '%')) or any(ord(c) <= 32 or ord(c) == 127 for c in path):
|
|
36
|
+
raise ValueError('path must be an unencoded relative endpoint without query or fragment')
|
|
37
|
+
if '://' in path or any(part in {'.', '..'} for part in path.split('/')):
|
|
38
|
+
raise ValueError('absolute URLs and dot path segments are forbidden')
|
|
39
|
+
fields = []
|
|
40
|
+
for _, name, spec, conversion in Formatter().parse(path):
|
|
41
|
+
if name is not None:
|
|
42
|
+
if not _FIELD.fullmatch(name) or spec or conversion:
|
|
43
|
+
raise ValueError('path fields must be simple names without formatting')
|
|
44
|
+
fields.append(name)
|
|
45
|
+
return tuple(dict.fromkeys(fields))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def endpoint(base: str, path: str, values: Mapping | None = None) -> str:
|
|
49
|
+
fields = path_fields(path)
|
|
50
|
+
values = dict(values or {})
|
|
51
|
+
if set(values) != set(fields):
|
|
52
|
+
raise ValueError('path parameters must exactly match the operation fields')
|
|
53
|
+
quoted = {}
|
|
54
|
+
for name, value in values.items():
|
|
55
|
+
if isinstance(value, bool) or not isinstance(value, (str, int)):
|
|
56
|
+
raise TypeError('path values must be strings or integers')
|
|
57
|
+
text = str(value)
|
|
58
|
+
if not text or text in {'.', '..'}:
|
|
59
|
+
raise ValueError('empty and dot path values are forbidden')
|
|
60
|
+
quoted[name] = quote(text, safe='')
|
|
61
|
+
pieces = []
|
|
62
|
+
for literal, name, _, _ in Formatter().parse(path):
|
|
63
|
+
pieces.append(quote(literal, safe="/:@-._~!$&'()*+,;="))
|
|
64
|
+
if name is not None:
|
|
65
|
+
pieces.append(quoted[name])
|
|
66
|
+
suffix = ''.join(pieces).lstrip('/')
|
|
67
|
+
return base + ('/' + suffix if suffix else '')
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True, slots=True)
|
|
71
|
+
class Operation:
|
|
72
|
+
name: str
|
|
73
|
+
method: str
|
|
74
|
+
path: str
|
|
75
|
+
description: str = ''
|
|
76
|
+
input_validator: Validator | None = field(default=None, repr=False, compare=False)
|
|
77
|
+
output_validator: Validator | None = field(default=None, repr=False, compare=False)
|
|
78
|
+
|
|
79
|
+
def __post_init__(self):
|
|
80
|
+
if not isinstance(self.name, str) or not _NAME.fullmatch(self.name):
|
|
81
|
+
raise ValueError('operation name must be a simple nonempty identifier')
|
|
82
|
+
if not isinstance(self.method, str) or not _METHOD.fullmatch(self.method) or self.method.upper() in {'CONNECT', 'TRACE'}:
|
|
83
|
+
raise ValueError('unsupported operation method')
|
|
84
|
+
object.__setattr__(self, 'method', self.method.upper())
|
|
85
|
+
path_fields(self.path)
|
|
86
|
+
for validator in (self.input_validator, self.output_validator):
|
|
87
|
+
if validator is not None and not callable(validator):
|
|
88
|
+
raise TypeError('validators must be callable')
|
|
89
|
+
|
|
90
|
+
def validate_input(self, value):
|
|
91
|
+
if value is not MISSING:
|
|
92
|
+
encode_json(value)
|
|
93
|
+
if self.input_validator is not None:
|
|
94
|
+
if value is MISSING:
|
|
95
|
+
raise ValidationError('operation requires JSON input')
|
|
96
|
+
validate(self.input_validator, value, 'input')
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def validate(validator: Validator | None, value: JSONValue, direction: str) -> None:
|
|
100
|
+
if validator is not None:
|
|
101
|
+
try:
|
|
102
|
+
validator(value)
|
|
103
|
+
except Exception as error:
|
|
104
|
+
raise ValidationError(f'operation {direction} validation failed') from error
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def decode_response(response: Response) -> JSONValue:
|
|
108
|
+
if not 200 <= response.status < 300:
|
|
109
|
+
raise APIStatusError(response)
|
|
110
|
+
if not response.body:
|
|
111
|
+
return None
|
|
112
|
+
media = (response.header('content-type') or '').split(';', 1)[0].strip().lower()
|
|
113
|
+
if media != 'application/json' and not (media.startswith('application/') and media.endswith('+json')):
|
|
114
|
+
raise InvalidResponseError('API response must declare a JSON media type', response)
|
|
115
|
+
try:
|
|
116
|
+
return response.json()
|
|
117
|
+
except (ValueError, TypeError, RecursionError) as error:
|
|
118
|
+
raise InvalidResponseError('API response contains invalid finite JSON', response) from error
|
apiconn/pagination.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Explicit REST page/cursor strategies with finite request bounds."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PaginationError(ValueError):
|
|
7
|
+
"""A page shape, cursor or pagination policy is invalid."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PaginationLimitError(PaginationError):
|
|
11
|
+
"""The selected page count was exhausted before completion."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _configure(strategy):
|
|
15
|
+
for name in ('items_key', 'parameter'):
|
|
16
|
+
value = getattr(strategy, name)
|
|
17
|
+
if not isinstance(value, str) or not value:
|
|
18
|
+
raise ValueError('pagination keys must be nonempty strings')
|
|
19
|
+
if isinstance(strategy.max_pages, bool) or not isinstance(strategy.max_pages, int) or strategy.max_pages < 1:
|
|
20
|
+
raise ValueError('max_pages must be a positive integer')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def items(document, key: str) -> list:
|
|
24
|
+
if not isinstance(document, dict) or not isinstance(document.get(key), list):
|
|
25
|
+
raise PaginationError('page must contain the configured items array')
|
|
26
|
+
return document[key]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True, slots=True)
|
|
30
|
+
class PagePagination:
|
|
31
|
+
items_key: str = 'items'
|
|
32
|
+
parameter: str = 'page'
|
|
33
|
+
start: int = 1
|
|
34
|
+
max_pages: int = 100
|
|
35
|
+
|
|
36
|
+
def __post_init__(self):
|
|
37
|
+
_configure(self)
|
|
38
|
+
if isinstance(self.start, bool) or not isinstance(self.start, int) or self.start < 0:
|
|
39
|
+
raise ValueError('start must be a nonnegative integer')
|
|
40
|
+
|
|
41
|
+
def next(self, document, state):
|
|
42
|
+
return state + 1 if items(document, self.items_key) else None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, slots=True)
|
|
46
|
+
class CursorPagination:
|
|
47
|
+
items_key: str = 'items'
|
|
48
|
+
parameter: str = 'cursor'
|
|
49
|
+
next_cursor_key: str = 'next_cursor'
|
|
50
|
+
start: str | None = None
|
|
51
|
+
max_pages: int = 100
|
|
52
|
+
|
|
53
|
+
def __post_init__(self):
|
|
54
|
+
_configure(self)
|
|
55
|
+
if not isinstance(self.next_cursor_key, str) or not self.next_cursor_key:
|
|
56
|
+
raise ValueError('next cursor key must be nonempty')
|
|
57
|
+
if self.start is not None and (not isinstance(self.start, str) or not self.start):
|
|
58
|
+
raise ValueError('start cursor must be a nonempty string or None')
|
|
59
|
+
|
|
60
|
+
def next(self, document, state):
|
|
61
|
+
if self.next_cursor_key not in document:
|
|
62
|
+
raise PaginationError('page is missing its configured next cursor')
|
|
63
|
+
cursor = document[self.next_cursor_key]
|
|
64
|
+
if cursor is not None and (not isinstance(cursor, str) or not cursor):
|
|
65
|
+
raise PaginationError('next cursor must be a nonempty string or null')
|
|
66
|
+
return cursor
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def parameters(strategy, params):
|
|
70
|
+
if not isinstance(strategy, (PagePagination, CursorPagination)):
|
|
71
|
+
raise TypeError('select a page or cursor pagination strategy')
|
|
72
|
+
result = dict(params or {})
|
|
73
|
+
if strategy.parameter in result:
|
|
74
|
+
raise ValueError('pagination owns its configured query parameter')
|
|
75
|
+
return result
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def advance(strategy, document, state, seen):
|
|
79
|
+
next_state = strategy.next(document, state)
|
|
80
|
+
if next_state is not None and next_state in seen:
|
|
81
|
+
raise PaginationError('pagination cursor cycle')
|
|
82
|
+
seen.add(next_state)
|
|
83
|
+
return next_state
|
apiconn/py.typed
ADDED
|
File without changes
|
apiconn/resources.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""REST resource conveniences implemented through ordinary operations."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Protocol
|
|
5
|
+
from requ import JSONValue
|
|
6
|
+
from .operations import MISSING, Operation, path_fields
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class _Executor(Protocol):
|
|
10
|
+
def _execute(self, operation: Operation, **kwargs) -> JSONValue: ...
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class _AsyncExecutor(Protocol):
|
|
14
|
+
async def _execute(self, operation: Operation, **kwargs) -> JSONValue: ...
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def fields_body(json, fields):
|
|
18
|
+
if json is not MISSING and fields:
|
|
19
|
+
raise ValueError('select json or keyword fields, not both')
|
|
20
|
+
return fields if json is MISSING else json
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class Resource:
|
|
25
|
+
api: _Executor
|
|
26
|
+
path: str
|
|
27
|
+
|
|
28
|
+
def __post_init__(self):
|
|
29
|
+
if path_fields(self.path):
|
|
30
|
+
raise ValueError('resource collection path cannot contain fields')
|
|
31
|
+
if not self.path.strip('/'):
|
|
32
|
+
raise ValueError('resource collection path must be nonempty')
|
|
33
|
+
|
|
34
|
+
def list(self, *, params=None):
|
|
35
|
+
return self.api._execute(Operation('list', 'GET', self.path), params=params)
|
|
36
|
+
|
|
37
|
+
def get(self, identifier, *, params=None):
|
|
38
|
+
return self.api._execute(Operation('get', 'GET', self.path.rstrip('/') + '/{id}'), id=identifier, params=params)
|
|
39
|
+
|
|
40
|
+
def create(self, *, json=MISSING, **fields):
|
|
41
|
+
return self.api._execute(Operation('create', 'POST', self.path), json=fields_body(json, fields))
|
|
42
|
+
|
|
43
|
+
def update(self, identifier, *, json=MISSING, **fields):
|
|
44
|
+
return self.api._execute(Operation('update', 'PATCH', self.path.rstrip('/') + '/{id}'), id=identifier, json=fields_body(json, fields))
|
|
45
|
+
|
|
46
|
+
def delete(self, identifier):
|
|
47
|
+
return self.api._execute(Operation('delete', 'DELETE', self.path.rstrip('/') + '/{id}'), id=identifier)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True, slots=True)
|
|
51
|
+
class AsyncResource:
|
|
52
|
+
api: _AsyncExecutor
|
|
53
|
+
path: str
|
|
54
|
+
|
|
55
|
+
def __post_init__(self):
|
|
56
|
+
if path_fields(self.path):
|
|
57
|
+
raise ValueError('resource collection path cannot contain fields')
|
|
58
|
+
if not self.path.strip('/'):
|
|
59
|
+
raise ValueError('resource collection path must be nonempty')
|
|
60
|
+
|
|
61
|
+
async def list(self, *, params=None):
|
|
62
|
+
return await self.api._execute(Operation('list', 'GET', self.path), params=params)
|
|
63
|
+
|
|
64
|
+
async def get(self, identifier, *, params=None):
|
|
65
|
+
return await self.api._execute(Operation('get', 'GET', self.path.rstrip('/') + '/{id}'), id=identifier, params=params)
|
|
66
|
+
|
|
67
|
+
async def create(self, *, json=MISSING, **fields):
|
|
68
|
+
return await self.api._execute(Operation('create', 'POST', self.path), json=fields_body(json, fields))
|
|
69
|
+
|
|
70
|
+
async def update(self, identifier, *, json=MISSING, **fields):
|
|
71
|
+
return await self.api._execute(Operation('update', 'PATCH', self.path.rstrip('/') + '/{id}'), id=identifier, json=fields_body(json, fields))
|
|
72
|
+
|
|
73
|
+
async def delete(self, identifier):
|
|
74
|
+
return await self.api._execute(Operation('delete', 'DELETE', self.path.rstrip('/') + '/{id}'), id=identifier)
|
|
@@ -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`.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
apiconn/__init__.py,sha256=LqbmPtOze3y0xudinWnrkFniafECkgJQwNnwNKXt2us,790
|
|
2
|
+
apiconn/auth.py,sha256=n52FLbmHsDJkuWgmjuTwu7Afy80xDFOvL_GtuqSk01Q,1636
|
|
3
|
+
apiconn/client.py,sha256=XSR3rr_ouIbA4mlHgcD4kaIV-QJ30eBoarJ0HdJ_VlU,11305
|
|
4
|
+
apiconn/graphql.py,sha256=CeL67ZB4fGHJctAH0S5awf-IZ_55eToKt4z3eX9sM0A,2089
|
|
5
|
+
apiconn/operations.py,sha256=mFZrmWtJ-3A-GI8Mu_cFV-Td-gSfLpc23PVqTdJCUL4,4933
|
|
6
|
+
apiconn/pagination.py,sha256=MqGUnkvAwTrqOTelvP2PV6vrrr0zURpGUThTqdVibCY,3028
|
|
7
|
+
apiconn/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
apiconn/resources.py,sha256=DSZgoDJUBb8aztISJEyLBW522LYD79WSyRnsl7Yx1LI,2972
|
|
9
|
+
apiconn-0.1.0.dist-info/licenses/LICENSE,sha256=pAeG0B2X4uxLV9iLuLxEEk4YSQamiNrWf4E6P5vch1Q,1069
|
|
10
|
+
apiconn-0.1.0.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
|
|
11
|
+
apiconn-0.1.0.dist-info/METADATA,sha256=MXBC3iJbqgECzdL2CV1b5JRwRIGFyN5jW_IDaJy4Rzk,2815
|
|
12
|
+
apiconn-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|