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/registry.py ADDED
@@ -0,0 +1,65 @@
1
+ import json
2
+ from dataclasses import dataclass, fields
3
+ from importlib import resources
4
+ from typing import Dict, List, Optional
5
+
6
+ from .naming import normalize
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Operation:
11
+ key: str
12
+ method: str
13
+ path: str
14
+ summary: str
15
+ cost: Optional[float]
16
+ path_params: List[str]
17
+ query: List[str]
18
+ body: List[str]
19
+ binary: bool
20
+ auth: bool = True
21
+
22
+ @property
23
+ def has_body(self) -> bool:
24
+ return self.method not in ("GET", "DELETE", "HEAD")
25
+
26
+
27
+ class Registry:
28
+ """Every API operation, loaded from operations.json."""
29
+
30
+ def __init__(self, operations: Dict[str, Operation]):
31
+ self._operations = operations
32
+ self._index = {self._index_key(*key.partition(".")[::2]): key for key in operations}
33
+ self._groups = {normalize(key.partition(".")[0]) for key in operations}
34
+
35
+ @classmethod
36
+ def load(cls) -> "Registry":
37
+ text = resources.files("axioapi").joinpath("operations.json").read_text(encoding="utf-8")
38
+ raw = json.loads(text)["operations"]
39
+ known = {f.name for f in fields(Operation)}
40
+ return cls({key: Operation(key=key, **{k: v for k, v in entry.items() if k in known}) for key, entry in raw.items()})
41
+
42
+ @staticmethod
43
+ def _index_key(group: str, name: str) -> str:
44
+ return f"{normalize(group)}.{normalize(name)}"
45
+
46
+ def all(self) -> Dict[str, Operation]:
47
+ return dict(self._operations)
48
+
49
+ def resolve(self, group: str, name: str) -> Optional[str]:
50
+ return self._index.get(self._index_key(group, name))
51
+
52
+ def find(self, operation: str) -> Optional[Operation]:
53
+ """Looks an operation up by exact key or by any spelling of group.name."""
54
+ if operation in self._operations:
55
+ return self._operations[operation]
56
+ group, _, name = operation.partition(".")
57
+ key = self.resolve(group, name)
58
+ return self._operations[key] if key else None
59
+
60
+ def has_group(self, group: str) -> bool:
61
+ return normalize(group) in self._groups
62
+
63
+ def group_names(self, group: str) -> List[str]:
64
+ prefix = normalize(group) + "."
65
+ return sorted(key[len(prefix):] for key in self._index if key.startswith(prefix))
@@ -0,0 +1,56 @@
1
+ import urllib.parse
2
+ from dataclasses import dataclass
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ from .registry import Operation
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class PreparedRequest:
10
+ method: str
11
+ path: str
12
+ query: Dict[str, Any]
13
+ body: Optional[Dict[str, Any]]
14
+
15
+
16
+ def build_request(operation: Operation, params: Dict[str, Any]) -> PreparedRequest:
17
+ """Splits flat params into path, query and body according to the operation."""
18
+ remaining = dict(params)
19
+ path = _fill_path(operation, remaining)
20
+ query: Dict[str, Any] = {}
21
+ body: Dict[str, Any] = {}
22
+ for name, value in remaining.items():
23
+ if value is None:
24
+ continue
25
+ target = body if _belongs_in_body(operation, name) else query
26
+ target[name] = value
27
+ return PreparedRequest(operation.method, path, query, body or None if operation.has_body else None)
28
+
29
+
30
+ def _fill_path(operation: Operation, params: Dict[str, Any]) -> str:
31
+ path = operation.path
32
+ for name in operation.path_params:
33
+ if params.get(name) is None:
34
+ raise ValueError(f"Missing path parameter '{name}' for {operation.key}")
35
+ path = path.replace("{" + name + "}", urllib.parse.quote(str(params.pop(name)), safe=""))
36
+ return path
37
+
38
+
39
+ def _belongs_in_body(operation: Operation, name: str) -> bool:
40
+ return operation.has_body and (name in operation.body or name not in operation.query)
41
+
42
+
43
+ def encode_query(params: Dict[str, Any]) -> str:
44
+ return urllib.parse.urlencode(_query_pairs(params))
45
+
46
+
47
+ def _query_pairs(params: Dict[str, Any]) -> List[Tuple[str, str]]:
48
+ pairs: List[Tuple[str, str]] = []
49
+ for key, value in params.items():
50
+ if isinstance(value, (list, tuple)):
51
+ pairs.extend((f"{key}[]", str(item)) for item in value)
52
+ elif isinstance(value, bool):
53
+ pairs.append((key, "true" if value else "false"))
54
+ elif value is not None:
55
+ pairs.append((key, str(value)))
56
+ return pairs
axioapi/responses.py ADDED
@@ -0,0 +1,56 @@
1
+ import json
2
+ from typing import Any, Dict, Optional
3
+
4
+ from .errors import (AuthenticationError, AxioAPIError, InsufficientCreditsError, NotFoundError,
5
+ RateLimitError, ValidationError)
6
+ from .transport import HttpResponse
7
+
8
+
9
+ def parse_success(response: HttpResponse, raw: bool) -> Any:
10
+ """Returns `data`, the whole envelope when raw, or bytes for non-JSON bodies (files)."""
11
+ if "json" not in (response.header("Content-Type") or ""):
12
+ return response.body
13
+ if not response.body:
14
+ return None
15
+ envelope = json.loads(response.body.decode("utf-8"))
16
+ if raw or not isinstance(envelope, dict):
17
+ return envelope
18
+ return envelope.get("data")
19
+
20
+
21
+ def build_error(response: HttpResponse) -> AxioAPIError:
22
+ body = _json_or_empty(response.body)
23
+ detail = body.get("error") if isinstance(body.get("error"), dict) else {}
24
+ fields = dict(
25
+ message=detail.get("message") or body.get("message") or f"HTTP {response.status}",
26
+ status=response.status,
27
+ code=detail.get("code"),
28
+ request_id=detail.get("request_id") or response.header("X-Request-Id"),
29
+ fields=detail.get("fields"),
30
+ body=body or None,
31
+ )
32
+ if response.status == 429:
33
+ return RateLimitError(retry_after=_retry_after_seconds(response), **fields)
34
+ error_class = _ERROR_BY_STATUS.get(response.status, AxioAPIError)
35
+ return error_class(**fields)
36
+
37
+
38
+ _ERROR_BY_STATUS = {
39
+ 401: AuthenticationError,
40
+ 402: InsufficientCreditsError,
41
+ 404: NotFoundError,
42
+ 422: ValidationError,
43
+ }
44
+
45
+
46
+ def _json_or_empty(content: bytes) -> Dict[str, Any]:
47
+ try:
48
+ parsed = json.loads(content.decode("utf-8"))
49
+ except ValueError:
50
+ return {}
51
+ return parsed if isinstance(parsed, dict) else {}
52
+
53
+
54
+ def _retry_after_seconds(response: HttpResponse) -> Optional[float]:
55
+ value = response.header("Retry-After")
56
+ return float(value) if value and value.isdigit() else None
axioapi/retry.py ADDED
@@ -0,0 +1,31 @@
1
+ from typing import Callable, Optional
2
+
3
+ RETRYABLE_STATUS = {502, 503, 504}
4
+ IDEMPOTENT_METHODS = {"GET", "HEAD", "DELETE"}
5
+ MAX_DELAY_SECONDS = 8.0
6
+ MAX_RETRY_AFTER_SECONDS = 30.0
7
+
8
+
9
+ class RetryPolicy:
10
+ """429 is retried for every method; 5xx and network errors only for idempotent ones."""
11
+
12
+ def __init__(self, max_retries: int, sleep: Callable[[float], None]):
13
+ self.max_retries = max(0, max_retries)
14
+ self._sleep = sleep
15
+
16
+ def should_retry_status(self, status: int, method: str, attempt: int) -> bool:
17
+ if attempt >= self.max_retries:
18
+ return False
19
+ return status == 429 or (method in IDEMPOTENT_METHODS and status in RETRYABLE_STATUS)
20
+
21
+ def should_retry_connection(self, method: str, attempt: int) -> bool:
22
+ return attempt < self.max_retries and method in IDEMPOTENT_METHODS
23
+
24
+ def wait(self, attempt: int, retry_after: Optional[str] = None) -> None:
25
+ self._sleep(self._delay(attempt, retry_after))
26
+
27
+ @staticmethod
28
+ def _delay(attempt: int, retry_after: Optional[str]) -> float:
29
+ if retry_after and retry_after.replace(".", "", 1).isdigit():
30
+ return min(float(retry_after), MAX_RETRY_AFTER_SECONDS)
31
+ return min(0.5 * (2 ** attempt), MAX_DELAY_SECONDS)
axioapi/transport.py ADDED
@@ -0,0 +1,39 @@
1
+ import urllib.error
2
+ import urllib.request
3
+ from dataclasses import dataclass
4
+ from typing import Dict, Mapping, Optional
5
+
6
+
7
+ class ConnectionFailure(Exception):
8
+ """The request produced no HTTP response."""
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class HttpResponse:
13
+ status: int
14
+ headers: Mapping[str, str]
15
+ body: bytes
16
+
17
+ def header(self, name: str) -> Optional[str]:
18
+ return self.headers.get(name)
19
+
20
+ @property
21
+ def ok(self) -> bool:
22
+ return 200 <= self.status < 300
23
+
24
+
25
+ class UrllibTransport:
26
+ """One HTTP round trip with the standard library; HTTP error statuses are returned, not raised."""
27
+
28
+ def __init__(self, timeout: float):
29
+ self._timeout = timeout
30
+
31
+ def send(self, method: str, url: str, headers: Dict[str, str], payload: Optional[bytes]) -> HttpResponse:
32
+ request = urllib.request.Request(url, data=payload, headers=headers, method=method)
33
+ try:
34
+ with urllib.request.urlopen(request, timeout=self._timeout) as response:
35
+ return HttpResponse(response.status, response.headers, response.read())
36
+ except urllib.error.HTTPError as error:
37
+ return HttpResponse(error.code, error.headers, error.read())
38
+ except (urllib.error.URLError, TimeoutError, ConnectionError) as error:
39
+ raise ConnectionFailure(str(getattr(error, "reason", error))) from None
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.4
2
+ Name: axioapi
3
+ Version: 1.0.0
4
+ Summary: Official Python SDK for the AxioAPI REST API: temp mail API, receive SMS and OTP API, email validation API, proxy API, SEO API (keyword data and backlink API), search API and social scraper APIs. One API key.
5
+ License: MIT
6
+ Project-URL: Homepage, https://axioapi.com
7
+ Project-URL: Documentation, https://axioapi.com/docs
8
+ Keywords: api,sdk,seo api,backlink api,keyword api,temp mail api,sms verification api,otp api,email validation api,proxy api,scraper api,search api,serp api,scholar api,translation api,python,axioapi
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ # AxioAPI Python SDK: temp mail, SMS OTP, email validation, proxy, SEO and backlink API
15
+
16
+ Python client for the [AxioAPI](https://axioapi.com) REST API: temp mail API, receive SMS and OTP API, email validation API, proxy API, SEO API (keyword data and backlink API) and social scraper APIs. One API key, pay per request. No dependencies.
17
+
18
+ <!-- start:begin -->
19
+ ## Get started in 3 steps
20
+
21
+ ### 1. Get an API key
22
+
23
+ [Create a free account](https://axioapi.com/portal/register), then open [API keys](https://axioapi.com/account/tokens), create a key and copy it. New accounts receive free credits after verification, enough to try every endpoint.
24
+
25
+ Set it as an environment variable (the SDK reads `AXIOAPI_KEY`):
26
+
27
+ ```bash
28
+ export AXIOAPI_KEY=ak_your_key # macOS / Linux
29
+ ```
30
+
31
+ ```powershell
32
+ $env:AXIOAPI_KEY = "ak_your_key" # Windows PowerShell
33
+ ```
34
+
35
+ ### 2. Install
36
+
37
+ ```bash
38
+ pip install git+https://github.com/axioapi/axioapi-python.git
39
+ ```
40
+
41
+ Requires Python 3.9+. No dependencies. Once released on PyPI: `pip install axioapi`.
42
+
43
+ ### 3. Make your first call
44
+
45
+ ```python
46
+ from axioapi import AxioAPI
47
+
48
+ client = AxioAPI() # reads AXIOAPI_KEY
49
+ print(client.account.limits()) # your plan and rate limits
50
+ print(client.seo.keyword_metrics(keywords=["api gateway"], country="us"))
51
+ ```
52
+
53
+ Every endpoint works the same way: `client.<group>.<operation>(params)`. See the examples below and the [full reference](https://axioapi.com/docs).
54
+ <!-- start:end -->
55
+
56
+ ## More examples
57
+
58
+ ```python
59
+ from axioapi import AxioAPI, RateLimitError, InsufficientCreditsError
60
+
61
+ client = AxioAPI() # or AxioAPI("ak_...")
62
+
63
+ # Keyword data API: volume, CPC and competition for up to 10 keywords per request
64
+ rows = client.seo.keyword_metrics(keywords=["api gateway", "proxy scraper"], country="us")
65
+
66
+ # Backlink API: summary with every data source that answered
67
+ backlinks = client.seo.backlinks_summary(domain="example.com")
68
+ print(backlinks["partial"], backlinks["missing"], list(backlinks["sources"]))
69
+
70
+ # Temp mail API: one inbox per test
71
+ inbox = client.temporary_email.create_inbox(ttl_minutes=10)
72
+ messages = client.temporary_email.list_messages(inbox=inbox["id"])
73
+
74
+ try:
75
+ client.verify.wait(number="+12025550192")
76
+ except RateLimitError as e:
77
+ print("retry in", e.retry_after, "request", e.request_id)
78
+ except InsufficientCreditsError:
79
+ print("top up credits")
80
+ ```
81
+
82
+ - `client.<group>.<operation>(**params)` for every endpoint; `client.call("seo.keyword-metrics", ...)` works by capability key. `client.operations()` lists all of them with method, path and credit cost.
83
+ - Returns the `data` field. `client.request("GET", "/api/v1/account/limits", raw=True)` returns the whole envelope.
84
+ - Image and audio endpoints return `bytes`.
85
+ - Options: `AxioAPI(api_key, base_url=..., timeout=30, max_retries=2)`. 429 is retried for all methods; 502/503/504 and network errors only for GET and DELETE.
86
+
87
+ Docs: https://axioapi.com/docs · Guides: https://axioapi.com/guides · License: MIT
88
+
89
+ <!-- seo:start -->
90
+ ## What you can build with the Python SDK
91
+
92
+ | Use case | API page | Typical call |
93
+ |---|---|---|
94
+ | [Temp mail API](https://axioapi.com/apis/temporary-email): disposable inboxes for signup and password-reset tests | `temporary-email` | create inbox, list messages, read message |
95
+ | [Receive SMS API](https://axioapi.com/apis/sms) and [OTP API](https://axioapi.com/apis/verify): public numbers and "wait for the code" | `sms`, `verify` | list numbers, wait for OTP |
96
+ | [Email validation API](https://axioapi.com/apis/email-validation): syntax, MX and disposable-address checks, plus transactional and outreach email sending | `email` | validate, batch validate, send |
97
+ | [Proxy API](https://axioapi.com/apis/proxy-vpn): sticky and rotating proxy sessions by country | `proxy` | create session, rotate, close |
98
+ | [SEO API](https://axioapi.com/apis/seo): keyword data API (volume, CPC), backlink API, domain overview, on-page audit | `seo` | keyword metrics, backlinks summary |
99
+ | [Search API](https://axioapi.com/apis/search): web, image, news, video, maps and shopping results, AI Overview and autocomplete | `search` | web search, news search |
100
+ | Scholar API: Google Scholar paper search, author profiles and citation formats | `scholar` | search papers, author profile |
101
+ | Text AI: neural translation, text generation and grammar check | `text`, `grammar` | translate, generate, check grammar |
102
+ | Audio and video AI: speech-to-text, text-to-speech, AI image generation, video transcripts and tags | `audio`, `tts`, `ai-image`, `video` | transcribe, text to speech, generate image |
103
+ | YouTube AI summarizer and webpage content extraction | `youtube`, `webpage` | summarize video, extract page |
104
+ | [Coupon API](https://axioapi.com/apis/coupons) and product price history: store promo codes and historical prices | `coupons`, `products`, `ecommerce` | search coupons, price history |
105
+ | DNS, BIN, technology and local lead APIs: DNS records, card BIN lookup, website tech stack, Google Maps business leads | `dns`, `bin`, `tech`, `local` | resolve DNS, BIN lookup, tech profile |
106
+ | [TikTok](https://axioapi.com/apis/social-tiktok), [Facebook](https://axioapi.com/apis/social-facebook), [Instagram](https://axioapi.com/apis/social-instagram), [YouTube](https://axioapi.com/apis/social-youtube), [X (Twitter)](https://axioapi.com/apis/social-twitter), [LinkedIn](https://axioapi.com/apis/social-linkedin) and [Reddit](https://axioapi.com/apis/social-reddit) scraper APIs | `social` | profiles, posts, comments, transcripts |
107
+
108
+ ## Guides with working code
109
+
110
+ - [Backlink API: check a domain's backlinks in Python](https://axioapi.com/guides/backlink-api-check-domain-python)
111
+ - [Keyword data API: get search volume and CPC in code](https://axioapi.com/guides/keyword-data-api-volume-cpc)
112
+ - [SEO report API: build a domain ranking report](https://axioapi.com/guides/seo-report-api-domain-ranking)
113
+ - [Test signup emails with Playwright and a temp mail API](https://axioapi.com/guides/playwright-temp-mail-signup-test)
114
+ - [Test OTP flows with a receive SMS API](https://axioapi.com/guides/otp-testing-with-sms-api)
115
+ - [Sticky vs rotating proxy: which one to use](https://axioapi.com/guides/sticky-vs-rotating-proxy)
116
+
117
+ Free tools that need no account: [backlink checker](https://axioapi.com/tools/backlink-checker), [email validator](https://axioapi.com/tools/email-validator), [DNS lookup](https://axioapi.com/tools/dns-lookup), [BIN checker](https://axioapi.com/tools/bin-checker).
118
+
119
+ ## FAQ
120
+
121
+ **Is there a Python client for the AxioAPI backlink API and keyword data API?** Yes, this package. `seo.backlinks_summary` returns the backlink summary of a domain with the figures of every data source, and `seo.keyword_metrics` returns search volume, CPC and competition for up to 10 keywords per request.
122
+
123
+ **How do I test signup emails and OTP codes from Python?** Create a disposable inbox with the temp mail API, submit its address in your form and read the message. For SMS codes, call the verify endpoint, which waits for the OTP on a public number and returns it.
124
+
125
+ **How much does it cost?** You pay per request with credits, and each endpoint lists its price on its [API page](https://axioapi.com/apis) and in the OpenAPI spec (`x-credit-cost`). New accounts receive free credits after verification. See [pricing](https://axioapi.com/pricing).
126
+
127
+ **Where is the full reference?** [axioapi.com/docs](https://axioapi.com/docs), the [OpenAPI 3.1 spec](https://axioapi.com/api/v1/openapi.json) and [llms.txt](https://axioapi.com/llms.txt) for AI agents.
128
+
129
+ Vietnamese: [AxioAPI tiếng Việt](https://axioapi.com/vi), [API SEO và API backlink](https://axioapi.com/vi/apis/seo).
130
+ <!-- seo:end -->
@@ -0,0 +1,16 @@
1
+ axioapi/__init__.py,sha256=ZiYy4IZfU8xVTNWH6TrlsLlcUWHeNNG1z24gt7OvEQU,415
2
+ axioapi/client.py,sha256=0lNIA6s9tsWR0Fpoucm50xBkv_AKmoyrfcbsLlf5lI4,3922
3
+ axioapi/errors.py,sha256=nt96fCN-aZZoFkE2mqMpyP2UO-oAGdMl_S4Q9qpM9qQ,1821
4
+ axioapi/groups.py,sha256=MXOBjoyNvLgTltPDTRHWG1LE5R9FmJsW4wQII3rSHCA,698
5
+ axioapi/naming.py,sha256=4nXs9dJuDnZ-emE7Lh4onLHUbzsco9ndkJAu8wc5beA,172
6
+ axioapi/operations.json,sha256=aNDylq8ICNBX6LeAIfEtkFzYfcr88xIlKPZkIv9Ehuc,55399
7
+ axioapi/registry.py,sha256=1aPb5Zzrww_SuUL6alG5hW8EkiRnyrhgoo3X9YKMrcA,2204
8
+ axioapi/request_builder.py,sha256=xIl8pyMqGeg-Gi5oyZ1whcJEpN1rKJ11vO9Lbf-pX0U,1959
9
+ axioapi/responses.py,sha256=iJSkgZ2GBQ1KhPtIQEbPg0ex42M9Qg_r81IONGuYL_o,1942
10
+ axioapi/retry.py,sha256=R85bFcJmUVpoAU2u2FTfOCPljt3CezCq4LV5bm_AY1s,1249
11
+ axioapi/transport.py,sha256=fmR4s8Y7oeWu7IbtKGIi_lbD1u80qLNr2R5odVFkWZU,1360
12
+ axioapi-1.0.0.dist-info/licenses/LICENSE,sha256=HtfShPGBNJdimtUwZpzpxCd3Kjd0n8Th11OgRjJLITk,1064
13
+ axioapi-1.0.0.dist-info/METADATA,sha256=dBVETLLhThB1RFFbDwrM7pw7Rg2T_88JZGyj_pby4co,8478
14
+ axioapi-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
15
+ axioapi-1.0.0.dist-info/top_level.txt,sha256=30V9MNYyJQo8fj34p4X-x-aAbOzGxqIiZHN2uak0sxU,8
16
+ axioapi-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AxioAPI
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.
@@ -0,0 +1 @@
1
+ axioapi