axioapi 1.0.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.
axioapi/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from .client import VERSION as __version__, AxioAPI
2
+ from .errors import (APIConnectionError, AuthenticationError, AxioAPIError, InsufficientCreditsError,
3
+ NotFoundError, RateLimitError, ValidationError)
4
+
5
+ __all__ = ["AxioAPI", "AxioAPIError", "AuthenticationError", "InsufficientCreditsError", "NotFoundError",
6
+ "RateLimitError", "ValidationError", "APIConnectionError", "__version__"]
axioapi/client.py ADDED
@@ -0,0 +1,84 @@
1
+ import json
2
+ import os
3
+ import time
4
+ from typing import Any, Callable, Dict, Optional
5
+
6
+ from .errors import APIConnectionError
7
+ from .groups import OperationGroup
8
+ from .registry import Operation, Registry
9
+ from .request_builder import build_request, encode_query
10
+ from .responses import build_error, parse_success
11
+ from .retry import RetryPolicy
12
+ from .transport import ConnectionFailure, UrllibTransport
13
+
14
+ DEFAULT_BASE_URL = "https://axioapi.com"
15
+ VERSION = "1.0.0"
16
+
17
+
18
+ class AxioAPI:
19
+ """Client for https://axioapi.com.
20
+
21
+ client = AxioAPI("ak_...")
22
+ client.seo.keyword_metrics(keywords=["api gateway"], country="us")
23
+ """
24
+
25
+ def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None, timeout: float = 30.0,
26
+ max_retries: int = 2, user_agent: Optional[str] = None,
27
+ sleep: Callable[[float], None] = time.sleep):
28
+ self.api_key = api_key or os.environ.get("AXIOAPI_KEY")
29
+ if not self.api_key:
30
+ raise ValueError("Pass api_key or set the AXIOAPI_KEY environment variable.")
31
+ self.base_url = (base_url or os.environ.get("AXIOAPI_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
32
+ self.user_agent = user_agent or f"axioapi-python/{VERSION}"
33
+ self.registry = Registry.load()
34
+ self._retry = RetryPolicy(max_retries, sleep)
35
+ self._transport = UrllibTransport(timeout)
36
+
37
+ def operations(self) -> Dict[str, Operation]:
38
+ return self.registry.all()
39
+
40
+ def __getattr__(self, name: str) -> OperationGroup:
41
+ if name.startswith("_") or "registry" not in self.__dict__ or not self.registry.has_group(name):
42
+ raise AttributeError(name)
43
+ return OperationGroup(self, name)
44
+
45
+ def call(self, operation: str, **params: Any) -> Any:
46
+ """Calls an operation by capability key (for example "seo.keyword-metrics") and returns `data`."""
47
+ found = self.registry.find(operation)
48
+ if found is None:
49
+ raise ValueError(f"Unknown operation '{operation}'. See client.operations().")
50
+ prepared = build_request(found, params)
51
+ return self.request(prepared.method, prepared.path, params=prepared.query or None, json_body=prepared.body)
52
+
53
+ def request(self, method: str, path: str, *, params: Optional[dict] = None, json_body: Any = None,
54
+ raw: bool = False) -> Any:
55
+ """Sends a request with retries; returns `data`, the envelope with raw=True, or bytes for files."""
56
+ method = method.upper()
57
+ url = self._url(path, params)
58
+ payload = json.dumps(json_body).encode("utf-8") if json_body is not None else None
59
+ headers = self._headers(has_body=payload is not None)
60
+
61
+ for attempt in range(self._retry.max_retries + 1):
62
+ try:
63
+ response = self._transport.send(method, url, headers, payload)
64
+ except ConnectionFailure as failure:
65
+ if self._retry.should_retry_connection(method, attempt):
66
+ self._retry.wait(attempt)
67
+ continue
68
+ raise APIConnectionError(f"Could not reach {self.base_url}: {failure}") from None
69
+ if response.ok:
70
+ return parse_success(response, raw)
71
+ if self._retry.should_retry_status(response.status, method, attempt):
72
+ self._retry.wait(attempt, response.header("Retry-After"))
73
+ continue
74
+ raise build_error(response)
75
+
76
+ def _url(self, path: str, params: Optional[dict]) -> str:
77
+ url = self.base_url + (path if path.startswith("/") else "/" + path)
78
+ return f"{url}?{encode_query(params)}" if params else url
79
+
80
+ def _headers(self, has_body: bool) -> Dict[str, str]:
81
+ headers = {"Authorization": f"Bearer {self.api_key}", "Accept": "application/json", "User-Agent": self.user_agent}
82
+ if has_body:
83
+ headers["Content-Type"] = "application/json"
84
+ return headers
axioapi/errors.py ADDED
@@ -0,0 +1,57 @@
1
+ """Exceptions raised by the AxioAPI client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+
8
+ class AxioAPIError(Exception):
9
+ """Base class. Every API error carries the HTTP status, error code and request_id for support."""
10
+
11
+ def __init__(self, message: str, *, status: Optional[int] = None, code: Optional[str] = None,
12
+ request_id: Optional[str] = None, fields: Optional[dict] = None, body: Any = None):
13
+ super().__init__(message)
14
+ self.message = message
15
+ self.status = status
16
+ self.code = code
17
+ self.request_id = request_id
18
+ self.fields = fields or {}
19
+ self.body = body
20
+
21
+ def __str__(self) -> str:
22
+ parts = [self.message]
23
+ if self.status:
24
+ parts.append(f"status={self.status}")
25
+ if self.code:
26
+ parts.append(f"code={self.code}")
27
+ if self.request_id:
28
+ parts.append(f"request_id={self.request_id}")
29
+ return " | ".join(parts)
30
+
31
+
32
+ class AuthenticationError(AxioAPIError):
33
+ """401: the API key is missing or invalid."""
34
+
35
+
36
+ class InsufficientCreditsError(AxioAPIError):
37
+ """402: not enough credits for this call."""
38
+
39
+
40
+ class NotFoundError(AxioAPIError):
41
+ """404: the resource does not exist, expired or is not yours."""
42
+
43
+
44
+ class ValidationError(AxioAPIError):
45
+ """422: invalid parameters. See `fields` for per-field messages."""
46
+
47
+
48
+ class RateLimitError(AxioAPIError):
49
+ """429: request limit reached. `retry_after` is in seconds when the server sent it."""
50
+
51
+ def __init__(self, message: str, *, retry_after: Optional[float] = None, **kwargs: Any):
52
+ super().__init__(message, **kwargs)
53
+ self.retry_after = retry_after
54
+
55
+
56
+ class APIConnectionError(AxioAPIError):
57
+ """The request never produced an HTTP response (DNS, TLS, timeout)."""
axioapi/groups.py ADDED
@@ -0,0 +1,21 @@
1
+ from typing import TYPE_CHECKING, Any, Callable
2
+
3
+ if TYPE_CHECKING:
4
+ from .client import AxioAPI
5
+
6
+
7
+ class OperationGroup:
8
+ """`client.seo`: attribute access to the operations of one API group."""
9
+
10
+ def __init__(self, client: "AxioAPI", group: str):
11
+ self._client = client
12
+ self._group = group
13
+
14
+ def __getattr__(self, name: str) -> Callable[..., Any]:
15
+ key = self._client.registry.resolve(self._group, name)
16
+ if key is None:
17
+ raise AttributeError(f"AxioAPI has no operation '{self._group}.{name}'")
18
+ return lambda **params: self._client.call(key, **params)
19
+
20
+ def __dir__(self):
21
+ return self._client.registry.group_names(self._group)
axioapi/naming.py ADDED
@@ -0,0 +1,6 @@
1
+ import re
2
+
3
+
4
+ def normalize(name: str) -> str:
5
+ """Folds snake_case, camelCase and kebab-case to one comparable form."""
6
+ return re.sub(r"[^a-z0-9]", "", name.lower())