companystack 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.
@@ -0,0 +1,41 @@
1
+ """CompanyStack API client: UK company data from Companies House.
2
+
3
+ .. code-block:: python
4
+
5
+ from companystack import CompanyStack
6
+
7
+ cs = CompanyStack() # reads COMPANYSTACK_API_KEY
8
+ print(cs.get_company("00445790")["company_name"])
9
+ """
10
+ from ._base import (
11
+ DEFAULT_BASE_URL,
12
+ APIConnectionError,
13
+ AuthenticationError,
14
+ CompanyStackError,
15
+ ConflictError,
16
+ NotFoundError,
17
+ PermissionDeniedError,
18
+ RateLimitError,
19
+ ServerError,
20
+ ValidationError,
21
+ )
22
+ from ._generated import * # noqa: F401,F403 (models: Company, HealthScore, …)
23
+ from ._generated import API_VERSION, AsyncCompanyStack, CompanyStack
24
+ from ._version import __version__
25
+
26
+ __all__ = [
27
+ "CompanyStack",
28
+ "AsyncCompanyStack",
29
+ "API_VERSION",
30
+ "DEFAULT_BASE_URL",
31
+ "CompanyStackError",
32
+ "ValidationError",
33
+ "AuthenticationError",
34
+ "PermissionDeniedError",
35
+ "NotFoundError",
36
+ "ConflictError",
37
+ "RateLimitError",
38
+ "ServerError",
39
+ "APIConnectionError",
40
+ "__version__",
41
+ ]
companystack/_base.py ADDED
@@ -0,0 +1,384 @@
1
+ """Runtime for the generated client: httpx transport, retries, errors and pagination.
2
+
3
+ Hand-written; ``_generated.py`` builds the typed methods on top of it.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import json
9
+ import os
10
+ import random
11
+ import time
12
+ import uuid
13
+ from typing import Any, AsyncIterator, Awaitable, Callable, Dict, Iterator, List, Mapping, Optional, TypeVar
14
+ from urllib.parse import quote
15
+
16
+ import httpx
17
+
18
+ from ._version import __version__
19
+
20
+ DEFAULT_BASE_URL = "https://api.companystack.co.uk"
21
+ T = TypeVar("T")
22
+
23
+
24
+ class CompanyStackError(Exception):
25
+ """Any non-2xx response, or a request that never got one (``status == 0``)."""
26
+
27
+ def __init__(self, message: str, *, status: int, body: Any = None, headers: Optional[httpx.Headers] = None) -> None:
28
+ super().__init__(message)
29
+ self.status = status
30
+ self.body = body
31
+ self.headers = headers
32
+ b = body if isinstance(body, dict) else {}
33
+ #: Stable machine-readable code, e.g. ``plan_upgrade_required`` or ``rate_limited``
34
+ self.code: Optional[str] = b.get("code") if isinstance(b.get("code"), str) else None
35
+ #: Where to upgrade, on plan and quota errors
36
+ self.upgrade_url: Optional[str] = b.get("upgrade_url") if isinstance(b.get("upgrade_url"), str) else None
37
+ retry = headers.get("retry-after") if headers is not None else None
38
+ if retry is None:
39
+ retry = b.get("retry_after_seconds")
40
+ try:
41
+ #: Seconds to wait, on a 429
42
+ self.retry_after: Optional[float] = float(retry) if retry is not None else None
43
+ except (TypeError, ValueError):
44
+ self.retry_after = None
45
+ #: The Idempotency-Key a write was sent with: send the same request with it to get its result without acting twice
46
+ self.idempotency_key: Optional[str] = None
47
+ #: CompanyStack kept the write during an outage (X-Request-Journaled: true) and will carry it out
48
+ self.journaled: bool = headers is not None and headers.get("x-request-journaled") == "true"
49
+
50
+
51
+ class ValidationError(CompanyStackError):
52
+ """400 / 422: the request was invalid."""
53
+
54
+
55
+ class AuthenticationError(CompanyStackError):
56
+ """401: missing, malformed or revoked API key."""
57
+
58
+
59
+ class PermissionDeniedError(CompanyStackError):
60
+ """403: the plan does not include this endpoint (see ``upgrade_url``), or the key may not call it."""
61
+
62
+
63
+ class NotFoundError(CompanyStackError):
64
+ """404."""
65
+
66
+
67
+ class ConflictError(CompanyStackError):
68
+ """409."""
69
+
70
+
71
+ class RateLimitError(CompanyStackError):
72
+ """429: rate limit reached after the retries (see ``retry_after``)."""
73
+
74
+
75
+ class ServerError(CompanyStackError):
76
+ """5xx."""
77
+
78
+
79
+ class APIConnectionError(CompanyStackError):
80
+ """The request did not get a response (network error or timeout)."""
81
+
82
+
83
+ def _error_for(status: int, body: Any, headers: httpx.Headers) -> CompanyStackError:
84
+ detail = body.get("error") if isinstance(body, dict) and isinstance(body.get("error"), str) else (str(body)[:200] if body else "request failed")
85
+ message = f"{status} {detail}"
86
+ cls: type[CompanyStackError] = CompanyStackError
87
+ if status in (400, 422):
88
+ cls = ValidationError
89
+ elif status == 401:
90
+ cls = AuthenticationError
91
+ elif status == 403:
92
+ cls = PermissionDeniedError
93
+ elif status == 404:
94
+ cls = NotFoundError
95
+ elif status == 409:
96
+ cls = ConflictError
97
+ elif status == 429:
98
+ cls = RateLimitError
99
+ elif status >= 500:
100
+ cls = ServerError
101
+ return cls(message, status=status, body=body, headers=headers)
102
+
103
+
104
+ def _seg(value: Any) -> str:
105
+ """Encode one path segment."""
106
+ return quote(str(value), safe="")
107
+
108
+
109
+ def _query(query: Optional[Mapping[str, Any]]) -> Dict[str, str]:
110
+ out: Dict[str, str] = {}
111
+ for key, value in (query or {}).items():
112
+ if value is None or value == "":
113
+ continue
114
+ if isinstance(value, bool):
115
+ out[key] = "true" if value else "false"
116
+ elif isinstance(value, (list, tuple)):
117
+ out[key] = ",".join(str(v) for v in value)
118
+ else:
119
+ out[key] = str(value)
120
+ return out
121
+
122
+
123
+ class _Base:
124
+ def __init__(
125
+ self,
126
+ api_key: Optional[str] = None,
127
+ *,
128
+ base_url: Optional[str] = None,
129
+ timeout: float = 30.0,
130
+ max_retries: int = 2,
131
+ max_retry_delay: float = 60.0,
132
+ headers: Optional[Mapping[str, str]] = None,
133
+ ) -> None:
134
+ #: Your API key (starts with ``cs_``). Defaults to the ``COMPANYSTACK_API_KEY`` environment variable.
135
+ self.api_key = api_key if api_key is not None else os.environ.get("COMPANYSTACK_API_KEY")
136
+ self.base_url = (base_url or os.environ.get("COMPANYSTACK_API_URL") or DEFAULT_BASE_URL).rstrip("/")
137
+ self.timeout = timeout
138
+ #: Retries after a 429 (any method) or a 5xx / network error (GET only)
139
+ self.max_retries = max_retries
140
+ self.max_retry_delay = max_retry_delay
141
+ self._extra_headers = dict(headers or {})
142
+ #: Rate-limit headers from the most recent response
143
+ self.last_rate_limit: Dict[str, int] = {}
144
+
145
+ def _headers(self, response: str, has_body: bool, auth: bool) -> Dict[str, str]:
146
+ h = {
147
+ "Accept": "application/json" if response == "json" else "*/*",
148
+ "User-Agent": f"companystack-python/{__version__}",
149
+ **self._extra_headers,
150
+ }
151
+ if auth and self.api_key:
152
+ h["Authorization"] = f"Bearer {self.api_key}"
153
+ if has_body:
154
+ h["Content-Type"] = "application/json"
155
+ return h
156
+
157
+ def _delay(self, attempt: int, retry_after: Optional[str]) -> float:
158
+ """Retry-After when given, else exponential backoff with jitter; capped at max_retry_delay."""
159
+ if retry_after is not None:
160
+ try:
161
+ return min(max(float(retry_after), 0.0), self.max_retry_delay)
162
+ except ValueError:
163
+ pass
164
+ return float(min(min(8.0, 0.5 * 2**attempt) * (0.75 + random.random() * 0.5), self.max_retry_delay))
165
+
166
+ def _record(self, headers: httpx.Headers) -> None:
167
+ if "x-ratelimit-limit" not in headers:
168
+ return
169
+ names = {
170
+ "limit": "x-ratelimit-limit", "remaining": "x-ratelimit-remaining", "reset": "x-ratelimit-reset",
171
+ "daily_limit": "x-ratelimit-daily-limit", "daily_remaining": "x-ratelimit-daily-remaining",
172
+ }
173
+ self.last_rate_limit = {k: int(headers[v]) for k, v in names.items() if v in headers and headers[v].lstrip("-").isdigit()}
174
+
175
+ @staticmethod
176
+ def _write_key(method: str, headers: Dict[str, str]) -> Optional[str]:
177
+ """Every write carries an Idempotency-Key: the caller's (in ``headers``), or a new UUID kept for its retries.
178
+
179
+ A write CompanyStack lists as keyed is then carried out once however often it is sent, and is kept through an
180
+ outage (503 with ``X-Request-Journaled: true``); sending it again with the same key returns its result.
181
+ """
182
+ if method == "GET":
183
+ return None
184
+ for name, value in headers.items():
185
+ if name.lower() == "idempotency-key":
186
+ return value
187
+ key = str(uuid.uuid4())
188
+ headers["Idempotency-Key"] = key
189
+ return key
190
+
191
+ @staticmethod
192
+ def _kept(key: Optional[str], res: httpx.Response) -> bool:
193
+ """A write CompanyStack kept during an outage: asked for again with the same key."""
194
+ return key is not None and res.headers.get("x-request-journaled") == "true"
195
+
196
+ @staticmethod
197
+ def _raise_with_key(res: httpx.Response, key: Optional[str]) -> None:
198
+ try:
199
+ _Base._raise(res)
200
+ except CompanyStackError as err:
201
+ err.idempotency_key = key
202
+ raise
203
+
204
+ @staticmethod
205
+ def _retryable(method: str, status: int) -> bool:
206
+ # A 429 is refused before the request is processed, so any method can be retried
207
+ return status == 429 or (method == "GET" and status >= 500 and status != 501)
208
+
209
+ @staticmethod
210
+ def _decode(res: httpx.Response, response: str) -> Any:
211
+ if response == "none":
212
+ return None
213
+ if response == "text":
214
+ return res.text
215
+ if response == "bytes":
216
+ return res.content
217
+ return res.json() if res.content else None
218
+
219
+ @staticmethod
220
+ def _raise(res: httpx.Response) -> None:
221
+ try:
222
+ body: Any = res.json()
223
+ except (json.JSONDecodeError, ValueError):
224
+ body = res.text
225
+ raise _error_for(res.status_code, body, res.headers)
226
+
227
+
228
+ class SyncTransport(_Base):
229
+ def __init__(self, api_key: Optional[str] = None, *, http_client: Optional[httpx.Client] = None, **kwargs: Any) -> None:
230
+ super().__init__(api_key, **kwargs)
231
+ self._owns_client = http_client is None
232
+ self._client = http_client or httpx.Client(timeout=self.timeout)
233
+
234
+ def close(self) -> None:
235
+ if self._owns_client:
236
+ self._client.close()
237
+
238
+ def __enter__(self: T) -> T:
239
+ return self
240
+
241
+ def __exit__(self, *exc: Any) -> None:
242
+ self.close()
243
+
244
+ def _request(self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, body: Any = None,
245
+ response: str = "json", auth: bool = True) -> Any:
246
+ url = self.base_url + path
247
+ headers = self._headers(response, body is not None, auth)
248
+ key = self._write_key(method, headers)
249
+ content = json.dumps(body) if body is not None else None
250
+ for attempt in range(self.max_retries + 1):
251
+ try:
252
+ res = self._client.request(method, url, params=_query(query), headers=headers, content=content, timeout=self.timeout)
253
+ except httpx.HTTPError as err:
254
+ if method == "GET" and attempt < self.max_retries:
255
+ time.sleep(self._delay(attempt, None))
256
+ continue
257
+ failure = APIConnectionError(f"Could not reach {self.base_url}: {err}", status=0)
258
+ failure.idempotency_key = key
259
+ raise failure from err
260
+ self._record(res.headers)
261
+ if (self._retryable(method, res.status_code) or self._kept(key, res)) and attempt < self.max_retries:
262
+ time.sleep(self._delay(attempt, res.headers.get("retry-after")))
263
+ continue
264
+ if res.status_code >= 400:
265
+ self._raise_with_key(res, key)
266
+ return self._decode(res, response)
267
+ raise AssertionError("unreachable")
268
+
269
+ def _paginate_offset(self, fetch: Callable[[int], Any], offset: int, items_key: str, total_key: Optional[str],
270
+ limit: Optional[int], max_items: Optional[int]) -> Iterator[Any]:
271
+ yielded = 0
272
+ while True:
273
+ page = fetch(offset)
274
+ items = page.get(items_key) or []
275
+ if page.get("offset", offset) != offset:
276
+ return # the server did not honour offset (Free plan): do not repeat the first page
277
+ for item in items:
278
+ if max_items is not None and yielded >= max_items:
279
+ return
280
+ yield item
281
+ yielded += 1
282
+ if _offset_done(page, offset, items, total_key, limit):
283
+ return
284
+ offset += len(items)
285
+
286
+ def _paginate_cursor(self, fetch: Callable[[Optional[str]], Any], cursor: Optional[str], items_key: str,
287
+ max_items: Optional[int]) -> Iterator[Any]:
288
+ yielded = 0
289
+ while True:
290
+ page = fetch(cursor)
291
+ for item in page.get(items_key) or []:
292
+ if max_items is not None and yielded >= max_items:
293
+ return
294
+ yield item
295
+ yielded += 1
296
+ nxt = page.get("next_cursor")
297
+ if not page.get("has_more") or not nxt or nxt == cursor:
298
+ return
299
+ cursor = nxt
300
+
301
+
302
+ class AsyncTransport(_Base):
303
+ def __init__(self, api_key: Optional[str] = None, *, http_client: Optional[httpx.AsyncClient] = None, **kwargs: Any) -> None:
304
+ super().__init__(api_key, **kwargs)
305
+ self._owns_client = http_client is None
306
+ self._client = http_client or httpx.AsyncClient(timeout=self.timeout)
307
+
308
+ async def close(self) -> None:
309
+ if self._owns_client:
310
+ await self._client.aclose()
311
+
312
+ async def __aenter__(self: T) -> T:
313
+ return self
314
+
315
+ async def __aexit__(self, *exc: Any) -> None:
316
+ await self.close()
317
+
318
+ async def _request(self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, body: Any = None,
319
+ response: str = "json", auth: bool = True) -> Any:
320
+ url = self.base_url + path
321
+ headers = self._headers(response, body is not None, auth)
322
+ key = self._write_key(method, headers)
323
+ content = json.dumps(body) if body is not None else None
324
+ for attempt in range(self.max_retries + 1):
325
+ try:
326
+ res = await self._client.request(method, url, params=_query(query), headers=headers, content=content, timeout=self.timeout)
327
+ except httpx.HTTPError as err:
328
+ if method == "GET" and attempt < self.max_retries:
329
+ await asyncio.sleep(self._delay(attempt, None))
330
+ continue
331
+ failure = APIConnectionError(f"Could not reach {self.base_url}: {err}", status=0)
332
+ failure.idempotency_key = key
333
+ raise failure from err
334
+ self._record(res.headers)
335
+ if (self._retryable(method, res.status_code) or self._kept(key, res)) and attempt < self.max_retries:
336
+ await asyncio.sleep(self._delay(attempt, res.headers.get("retry-after")))
337
+ continue
338
+ if res.status_code >= 400:
339
+ self._raise_with_key(res, key)
340
+ return self._decode(res, response)
341
+ raise AssertionError("unreachable")
342
+
343
+ async def _paginate_offset(self, fetch: Callable[[int], Awaitable[Any]], offset: int, items_key: str,
344
+ total_key: Optional[str], limit: Optional[int], max_items: Optional[int]) -> AsyncIterator[Any]:
345
+ yielded = 0
346
+ while True:
347
+ page = await fetch(offset)
348
+ items = page.get(items_key) or []
349
+ if page.get("offset", offset) != offset:
350
+ return # the server did not honour offset (Free plan): do not repeat the first page
351
+ for item in items:
352
+ if max_items is not None and yielded >= max_items:
353
+ return
354
+ yield item
355
+ yielded += 1
356
+ if _offset_done(page, offset, items, total_key, limit):
357
+ return
358
+ offset += len(items)
359
+
360
+ async def _paginate_cursor(self, fetch: Callable[[Optional[str]], Awaitable[Any]], cursor: Optional[str],
361
+ items_key: str, max_items: Optional[int]) -> AsyncIterator[Any]:
362
+ yielded = 0
363
+ while True:
364
+ page = await fetch(cursor)
365
+ for item in page.get(items_key) or []:
366
+ if max_items is not None and yielded >= max_items:
367
+ return
368
+ yield item
369
+ yielded += 1
370
+ nxt = page.get("next_cursor")
371
+ if not page.get("has_more") or not nxt or nxt == cursor:
372
+ return
373
+ cursor = nxt
374
+
375
+
376
+ def _offset_done(page: Dict[str, Any], offset: int, items: List[Any], total_key: Optional[str], limit: Optional[int]) -> bool:
377
+ """Last page: empty, short, or the total is reached."""
378
+ if not items:
379
+ return True
380
+ page_limit = page.get("limit", limit)
381
+ if page_limit is not None and len(items) < int(page_limit):
382
+ return True
383
+ total = page.get(total_key) if total_key else None
384
+ return isinstance(total, int) and offset + len(items) >= total