dataandapis 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,40 @@
1
+ """Official Python client for Data and APIs (https://dataandapis.com).
2
+
3
+ 128 REST data APIs behind one API key::
4
+
5
+ from dataandapis import DataAndApis
6
+
7
+ client = DataAndApis() # reads DATAANDAPIS_API_KEY
8
+ check = client.vat.validate_vat_number(vat="IE6388047V")
9
+ print(check["valid"], check["name"])
10
+ """
11
+
12
+ from ._client import DataAndApis
13
+ from ._errors import (
14
+ ApiConnectionError,
15
+ ApiError,
16
+ ApiTimeoutError,
17
+ AuthenticationError,
18
+ DataAndApisError,
19
+ PaymentRequiredError,
20
+ QuotaExceededError,
21
+ )
22
+ from ._types import HttpResponse, ParamValue, RequestOptions, ResponseInfo, Transport
23
+ from ._version import __version__
24
+
25
+ __all__ = [
26
+ "ApiConnectionError",
27
+ "ApiError",
28
+ "ApiTimeoutError",
29
+ "AuthenticationError",
30
+ "DataAndApis",
31
+ "DataAndApisError",
32
+ "HttpResponse",
33
+ "ParamValue",
34
+ "PaymentRequiredError",
35
+ "QuotaExceededError",
36
+ "RequestOptions",
37
+ "ResponseInfo",
38
+ "Transport",
39
+ "__version__",
40
+ ]
dataandapis/_client.py ADDED
@@ -0,0 +1,327 @@
1
+ """The client: authentication, retries, errors and the request escape hatch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.client
6
+ import json
7
+ import os
8
+ import random
9
+ import re
10
+ import socket
11
+ import time
12
+ import urllib.parse
13
+ from typing import Any, Callable, Dict, Iterable, Mapping, Optional, cast
14
+
15
+ from ._errors import ApiConnectionError, ApiError, ApiTimeoutError, AuthenticationError, DataAndApisError, PaymentRequiredError, QuotaExceededError
16
+ from ._generated.apis import API_NAMES, Apis
17
+ from ._transport import KeepAliveTransport
18
+ from ._types import HttpResponse, ParamValue, RequestOptions, ResponseInfo, Transport
19
+ from ._version import __version__
20
+
21
+ DEFAULT_TIMEOUT = 30.0
22
+ DEFAULT_MAX_RETRIES = 2
23
+ RETRY_STATUSES = frozenset({408, 502, 503, 504})
24
+ MAX_RETRY_WAIT = 10.0
25
+ HOST = "dataandapis.com"
26
+ KEY_ENV = "DATAANDAPIS_API_KEY"
27
+
28
+ _PATH_PARAM = re.compile(r"\{(\w+)\}")
29
+
30
+
31
+ def _text(value: Any) -> str:
32
+ """A parameter value as the API expects it: ``true``/``false``, plain numbers, lists joined with commas."""
33
+ if isinstance(value, bool):
34
+ return "true" if value else "false"
35
+ if isinstance(value, str):
36
+ return value
37
+ if isinstance(value, (list, tuple, set, frozenset)):
38
+ return ",".join(_text(item) for item in cast(Iterable[Any], value))
39
+ if isinstance(value, float) and value.is_integer() and abs(value) < 1e15:
40
+ return str(int(value))
41
+ return str(value)
42
+
43
+
44
+ def _error_message(status: int, body: Any, fallback: str) -> str:
45
+ if isinstance(body, dict):
46
+ fields = cast(Dict[str, Any], body)
47
+ for field in ("message", "error"):
48
+ text = fields.get(field)
49
+ if isinstance(text, str) and text:
50
+ return text
51
+ if isinstance(body, str) and body and len(body) < 300:
52
+ return body
53
+ return fallback or f"Request failed with status {status}"
54
+
55
+
56
+ def _parse_body(response: HttpResponse) -> Any:
57
+ if response.status in (204, 205):
58
+ return None
59
+ kind = response.headers.get("content-type", "").lower()
60
+ if "json" in kind:
61
+ if not response.body:
62
+ return None
63
+ text = response.body.decode("utf-8", errors="replace")
64
+ try:
65
+ return json.loads(text)
66
+ except ValueError:
67
+ return text
68
+ if kind.startswith("text/") or kind.startswith("application/xml"):
69
+ match = re.search(r"charset=([\w-]+)", kind)
70
+ try:
71
+ return response.body.decode(match.group(1) if match else "utf-8", errors="replace")
72
+ except LookupError:
73
+ return response.body.decode("utf-8", errors="replace")
74
+ return response.body
75
+
76
+
77
+ def _backoff(attempt: int) -> float:
78
+ """0.5 s, 1 s, 2 s ... with jitter, capped."""
79
+ return min(0.5 * 2.0 ** (attempt - 1), MAX_RETRY_WAIT) * (0.75 + random.random() * 0.5)
80
+
81
+
82
+ class DataAndApis(Apis):
83
+ """Client for the Data and APIs catalog (https://dataandapis.com).
84
+
85
+ Every API is an attribute of the client and every endpoint a method on it::
86
+
87
+ from dataandapis import DataAndApis
88
+
89
+ client = DataAndApis() # reads DATAANDAPIS_API_KEY
90
+ check = client.vat.validate_vat_number(vat="IE6388047V")
91
+ print(check["valid"], check["name"])
92
+
93
+ :param api_key: Your Data and APIs key. Create one for free at
94
+ https://dataandapis.com/sign-up. Defaults to the ``DATAANDAPIS_API_KEY``
95
+ environment variable.
96
+ :param timeout: Seconds to wait for the server on each attempt. Default 30.
97
+ Zero means no limit.
98
+ :param max_retries: How many times to retry a GET request after a network
99
+ error or a 408, 502, 503 or 504 response. Default 2. Other methods are
100
+ never retried.
101
+ :param headers: Extra headers sent with every request.
102
+ :param on_response: Called with a :class:`ResponseInfo` after every
103
+ response, including failed attempts. Useful for logging and for
104
+ tracking your token balance.
105
+ :param transport: A callable that sends one HTTP request, to use instead of
106
+ the built-in one (for tests, or to route requests through your own
107
+ HTTP stack). See :data:`dataandapis.Transport`.
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ api_key: Optional[str] = None,
113
+ *,
114
+ timeout: float = DEFAULT_TIMEOUT,
115
+ max_retries: int = DEFAULT_MAX_RETRIES,
116
+ headers: Optional[Mapping[str, str]] = None,
117
+ on_response: Optional[Callable[[ResponseInfo], None]] = None,
118
+ transport: Optional[Transport] = None,
119
+ ) -> None:
120
+ key = api_key if api_key is not None else os.environ.get(KEY_ENV)
121
+ if not key:
122
+ raise DataAndApisError(
123
+ f"Missing API key. Pass api_key or set the {KEY_ENV} environment variable. Create a free key at https://dataandapis.com/sign-up"
124
+ )
125
+ self.__api_key = key
126
+ self._timeout = timeout
127
+ self._max_retries = max_retries
128
+ self._headers = dict(headers or {})
129
+ self._on_response = on_response
130
+ self._own_transport = KeepAliveTransport() if transport is None else None
131
+ self._transport: Transport = transport if transport is not None else self._own_transport # type: ignore[assignment]
132
+
133
+ def __repr__(self) -> str:
134
+ return f"<DataAndApis {__version__}: {len(API_NAMES)} APIs>"
135
+
136
+ def __enter__(self) -> "DataAndApis":
137
+ return self
138
+
139
+ def __exit__(self, *exc: object) -> None:
140
+ self.close()
141
+
142
+ def close(self) -> None:
143
+ """Close the idle connections the client keeps open between calls.
144
+
145
+ Optional: they are also closed when the client is garbage-collected.
146
+ The client can still be used afterwards.
147
+ """
148
+ if self._own_transport is not None:
149
+ self._own_transport.close()
150
+
151
+ # ── Calling ──────────────────────────────────────────────────────────────
152
+
153
+ def request(
154
+ self,
155
+ api: str,
156
+ path: str,
157
+ *,
158
+ method: str = "GET",
159
+ query: Optional[Mapping[str, Optional[ParamValue]]] = None,
160
+ body: Any = None,
161
+ options: Optional[RequestOptions] = None,
162
+ ) -> Any:
163
+ """Call any endpoint by path. Use it for endpoints newer than this version of the SDK.
164
+
165
+ ::
166
+
167
+ data = client.request("vat", "/v1/vat/validate", query={"vat": "IE6388047V"})
168
+
169
+ :param api: The API's catalog slug (``"ip-intelligence"``), its name on
170
+ the client (``"ip_intelligence"``) or its ``https://`` base URL.
171
+ :param path: Path on that API, starting with ``/v1/``.
172
+ :param method: HTTP method. Default ``"GET"``.
173
+ :param query: Query parameters.
174
+ :param body: JSON request body.
175
+ """
176
+ known = API_NAMES.get(api)
177
+ if known is not None:
178
+ slug, base = known
179
+ elif api.lower().startswith("https://"):
180
+ base = api.rstrip("/")
181
+ slug = re.sub(r"^api-", "", (urllib.parse.urlsplit(base).hostname or "").split(".")[0])
182
+ else:
183
+ raise DataAndApisError(f'Unknown API "{api}". Use a slug from https://dataandapis.com/apis or the API\'s https:// base URL.')
184
+ target = base + (path if path.startswith("/") else f"/{path}")
185
+ return self._send(slug, method.upper(), target, query, body, options)
186
+
187
+ def _call(
188
+ self,
189
+ name: str,
190
+ slug: str,
191
+ base_url: str,
192
+ method: str,
193
+ template: str,
194
+ params: Dict[str, Any],
195
+ body: Any,
196
+ options: Optional[RequestOptions],
197
+ ) -> Any:
198
+ """Called by the generated methods: fill the path, send the rest as the query."""
199
+
200
+ def fill(match: "re.Match[str]") -> str:
201
+ key = match.group(1)
202
+ value = params.pop(key, None)
203
+ if value is None or value == "":
204
+ raise DataAndApisError(f'Missing "{key}" for {name}(): it is part of the path {template}')
205
+ # "/" is kept so that values such as the timezone "America/New_York" stay path segments.
206
+ return urllib.parse.quote(_text(value), safe="/-_.!~*'()")
207
+
208
+ path = _PATH_PARAM.sub(fill, template)
209
+ query: Dict[str, Any] = params
210
+ extra = options.get("query") if options else None
211
+ if extra:
212
+ query = {**params, **extra}
213
+ return self._send(slug, method, base_url + path, query, None if method == "GET" else body, options)
214
+
215
+ def _send(
216
+ self,
217
+ slug: str,
218
+ method: str,
219
+ target: str,
220
+ query: Optional[Mapping[str, Any]],
221
+ body: Any,
222
+ options: Optional[RequestOptions],
223
+ ) -> Any:
224
+ parts = urllib.parse.urlsplit(target)
225
+ host = (parts.hostname or "").lower()
226
+ if parts.scheme != "https" or not (host == HOST or host.endswith(f".{HOST}")):
227
+ raise DataAndApisError(f"Refusing to send the API key to {parts.scheme}://{parts.netloc}: only https://*.{HOST} is allowed.")
228
+ pairs = urllib.parse.parse_qsl(parts.query, keep_blank_values=True)
229
+ if query:
230
+ named = {key: _text(value) for key, value in query.items() if value is not None}
231
+ pairs = [(key, value) for key, value in pairs if key not in named] + list(named.items())
232
+ url = urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, urllib.parse.urlencode(pairs), ""))
233
+
234
+ options = options or {}
235
+ headers: Dict[str, str] = {"Accept": "application/json", "User-Agent": f"dataandapis-python/{__version__}"}
236
+ headers.update(self._headers)
237
+ headers.update(options.get("headers") or {})
238
+ for name in [name for name in headers if name.lower() == "x-api-key"]:
239
+ del headers[name]
240
+ headers["X-Api-Key"] = self.__api_key
241
+ payload: Optional[bytes] = None
242
+ if body is not None:
243
+ if isinstance(body, (bytes, bytearray)):
244
+ payload = bytes(body)
245
+ elif isinstance(body, str):
246
+ payload = body.encode("utf-8")
247
+ else:
248
+ payload = json.dumps(body, separators=(",", ":")).encode("utf-8")
249
+ if not any(name.lower() == "content-type" for name in headers):
250
+ headers["Content-Type"] = "application/json"
251
+
252
+ timeout = options.get("timeout", self._timeout)
253
+ max_retries = max(0, options.get("max_retries", self._max_retries)) if method == "GET" else 0
254
+
255
+ attempt = 0
256
+ while True:
257
+ attempt += 1
258
+ can_retry = attempt <= max_retries
259
+ started = time.monotonic()
260
+ try:
261
+ response = self._transport(method, url, headers, payload, timeout)
262
+ except (socket.timeout, TimeoutError) as err:
263
+ if can_retry:
264
+ time.sleep(_backoff(attempt))
265
+ continue
266
+ raise ApiTimeoutError(f"{method} {url} timed out after {timeout:g} s") from err
267
+ except (OSError, EOFError, http.client.HTTPException) as err:
268
+ # http.client reports a broken exchange (a closed connection, a bad
269
+ # status line) with its own exception family.
270
+ if can_retry:
271
+ time.sleep(_backoff(attempt))
272
+ continue
273
+ raise ApiConnectionError(f"{method} {url} failed: {_describe(err)}") from err
274
+
275
+ ok = 200 <= response.status <= 299
276
+ remaining = response.headers.get("ratelimit-requests-remaining", "")
277
+ tokens_remaining: Optional[int] = None
278
+ try:
279
+ tokens_remaining = int(float(remaining)) if remaining.strip() else None
280
+ except ValueError:
281
+ tokens_remaining = None
282
+ if self._on_response is not None:
283
+ info = ResponseInfo(
284
+ api=slug,
285
+ method=method,
286
+ url=url,
287
+ status=response.status,
288
+ ok=ok,
289
+ duration_ms=round((time.monotonic() - started) * 1000, 1),
290
+ tokens_remaining=tokens_remaining,
291
+ attempt=attempt,
292
+ )
293
+ try:
294
+ self._on_response(info)
295
+ except Exception:
296
+ pass # A logging hook must not break the request.
297
+
298
+ if not ok and can_retry and response.status in RETRY_STATUSES:
299
+ try:
300
+ retry_after = float(response.headers.get("retry-after", ""))
301
+ except ValueError:
302
+ retry_after = 0.0
303
+ time.sleep(min(retry_after, MAX_RETRY_WAIT) if retry_after > 0 else _backoff(attempt))
304
+ continue
305
+
306
+ data = _parse_body(response)
307
+ if ok:
308
+ return data
309
+ details: Dict[str, Any] = dict(status=response.status, api=slug, method=method, url=url, body=data, tokens_remaining=tokens_remaining)
310
+ message = _error_message(response.status, data, response.reason)
311
+ if response.status == 401:
312
+ raise AuthenticationError(message, **details)
313
+ if response.status == 402:
314
+ raise PaymentRequiredError(message, **details)
315
+ if response.status == 429:
316
+ raise QuotaExceededError(message, **details)
317
+ raise ApiError(message, **details)
318
+
319
+
320
+ def _describe(err: BaseException) -> str:
321
+ text = str(err) or type(err).__name__
322
+ if "CERTIFICATE_VERIFY_FAILED" in text:
323
+ text += (
324
+ ". Python could not find the root certificates of this machine. On macOS with Python from python.org, "
325
+ "run the 'Install Certificates.command' that came with it."
326
+ )
327
+ return text
dataandapis/_errors.py ADDED
@@ -0,0 +1,85 @@
1
+ """Errors raised by the client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import builtins
6
+ from typing import Any, Dict, Optional, cast
7
+
8
+
9
+ class DataAndApisError(Exception):
10
+ """Base class of every error raised by the SDK."""
11
+
12
+
13
+ class ApiError(DataAndApisError):
14
+ """The API answered with a status outside 200-299."""
15
+
16
+ #: HTTP status code.
17
+ status: int
18
+ #: Catalog slug of the API that answered, for example ``"ip-intelligence"``.
19
+ api: str
20
+ method: str
21
+ url: str
22
+ #: The parsed response body: usually ``{"message": ...}`` or ``{"error": ..., "message": ...}``.
23
+ body: Any
24
+ #: Tokens left on the key, when the API reports it.
25
+ tokens_remaining: Optional[int]
26
+
27
+ def __init__(
28
+ self,
29
+ message: str,
30
+ *,
31
+ status: int,
32
+ api: str,
33
+ method: str,
34
+ url: str,
35
+ body: Any = None,
36
+ tokens_remaining: Optional[int] = None,
37
+ ) -> None:
38
+ super().__init__(message)
39
+ self.message = message
40
+ self.status = status
41
+ self.api = api
42
+ self.method = method
43
+ self.url = url
44
+ self.body = body
45
+ self.tokens_remaining = tokens_remaining
46
+
47
+ def __str__(self) -> str:
48
+ return f"{self.message} (HTTP {self.status})"
49
+
50
+
51
+ class AuthenticationError(ApiError):
52
+ """401: the API key is missing or not valid."""
53
+
54
+
55
+ class PaymentRequiredError(ApiError):
56
+ """402: the subscription is past due. ``payment_url`` is where to settle it."""
57
+
58
+ @property
59
+ def payment_url(self) -> Optional[str]:
60
+ body: Any = self.body
61
+ if not isinstance(body, dict):
62
+ return None
63
+ url = cast(Dict[str, Any], body).get("payment_url")
64
+ return url if isinstance(url, str) else None
65
+
66
+
67
+ class QuotaExceededError(ApiError):
68
+ """429: the plan's monthly token allowance is used up.
69
+
70
+ Retrying will not help until it resets or the plan is upgraded.
71
+ """
72
+
73
+
74
+ class ApiConnectionError(DataAndApisError):
75
+ """The request never got a response: DNS, TLS or network failure.
76
+
77
+ The original exception is in ``__cause__``.
78
+ """
79
+
80
+
81
+ class ApiTimeoutError(DataAndApisError, builtins.TimeoutError):
82
+ """No response arrived within the timeout.
83
+
84
+ Also an instance of the built-in ``TimeoutError``.
85
+ """
@@ -0,0 +1 @@
1
+ # Generated by scripts/generate.py from catalog/catalog.json. Do not edit by hand.