handlesapi 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.
- handlesapi/__init__.py +22 -0
- handlesapi/_core.py +194 -0
- handlesapi/_methods.py +4162 -0
- handlesapi/_operations.py +133 -0
- handlesapi/_types.py +5192 -0
- handlesapi/client.py +256 -0
- handlesapi/errors.py +63 -0
- handlesapi/py.typed +0 -0
- handlesapi-0.1.0.dist-info/METADATA +188 -0
- handlesapi-0.1.0.dist-info/RECORD +13 -0
- handlesapi-0.1.0.dist-info/WHEEL +5 -0
- handlesapi-0.1.0.dist-info/licenses/LICENSE +21 -0
- handlesapi-0.1.0.dist-info/top_level.txt +1 -0
handlesapi/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Python client for the Handles API: public social media data for X, Instagram, TikTok, YouTube,
|
|
2
|
+
Telegram, Bluesky, Twitch, Kick and LinkedIn companies. https://handlesapi.com/docs"""
|
|
3
|
+
from ._core import DEFAULT_BASE_URL, VERSION, Credits, RateLimit, Response
|
|
4
|
+
from ._operations import OPERATIONS, Operation
|
|
5
|
+
from .client import AsyncHandlesApi, HandlesApi
|
|
6
|
+
from .errors import HandlesApiConnectionError, HandlesApiError
|
|
7
|
+
|
|
8
|
+
__version__ = VERSION
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"AsyncHandlesApi",
|
|
12
|
+
"Credits",
|
|
13
|
+
"DEFAULT_BASE_URL",
|
|
14
|
+
"HandlesApi",
|
|
15
|
+
"HandlesApiConnectionError",
|
|
16
|
+
"HandlesApiError",
|
|
17
|
+
"OPERATIONS",
|
|
18
|
+
"Operation",
|
|
19
|
+
"RateLimit",
|
|
20
|
+
"Response",
|
|
21
|
+
"__version__",
|
|
22
|
+
]
|
handlesapi/_core.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Transport-independent pieces: response model, request building, parsing and retry policy."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import random
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from email.utils import parsedate_to_datetime
|
|
9
|
+
from typing import Any, Dict, Generic, List, Mapping, Optional, Tuple, TypeVar, Union
|
|
10
|
+
from urllib.parse import quote
|
|
11
|
+
|
|
12
|
+
from ._operations import OPERATIONS, Operation
|
|
13
|
+
from ._types import ApiMeta
|
|
14
|
+
from .errors import HandlesApiConnectionError, HandlesApiError
|
|
15
|
+
|
|
16
|
+
VERSION = "0.1.0"
|
|
17
|
+
DEFAULT_BASE_URL = "https://api.handlesapi.com/v1"
|
|
18
|
+
|
|
19
|
+
T = TypeVar("T")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Credits:
|
|
24
|
+
"""What the API reports in ``X-Credits-*``. Fields are None when a header is missing."""
|
|
25
|
+
|
|
26
|
+
cost: Optional[int]
|
|
27
|
+
"""Credits this call used."""
|
|
28
|
+
remaining: Optional[int]
|
|
29
|
+
"""Plan credits left in the current period."""
|
|
30
|
+
period_end: Optional[str]
|
|
31
|
+
"""When the current period ends, ISO 8601."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class RateLimit:
|
|
36
|
+
"""``X-RateLimit-*``: the per-minute window."""
|
|
37
|
+
|
|
38
|
+
limit: Optional[int]
|
|
39
|
+
remaining: Optional[int]
|
|
40
|
+
reset: Optional[int]
|
|
41
|
+
"""Unix seconds at which the window resets."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class Response(Generic[T]):
|
|
46
|
+
"""A successful ``{ data, meta }`` answer plus the credit and rate-limit headers."""
|
|
47
|
+
|
|
48
|
+
data: T
|
|
49
|
+
meta: ApiMeta
|
|
50
|
+
credits: Credits
|
|
51
|
+
rate_limit: RateLimit
|
|
52
|
+
request_id: Optional[str]
|
|
53
|
+
headers: Mapping[str, str]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _int(value: Optional[str]) -> Optional[int]:
|
|
57
|
+
if value is None or value == "":
|
|
58
|
+
return None
|
|
59
|
+
try:
|
|
60
|
+
return int(float(value))
|
|
61
|
+
except ValueError:
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_retry_after(value: Optional[str], now: Optional[datetime] = None) -> Optional[float]:
|
|
66
|
+
"""``Retry-After`` is delta-seconds or an HTTP date. Returns seconds."""
|
|
67
|
+
if not value:
|
|
68
|
+
return None
|
|
69
|
+
try:
|
|
70
|
+
return max(0.0, float(value))
|
|
71
|
+
except ValueError:
|
|
72
|
+
pass
|
|
73
|
+
try:
|
|
74
|
+
at = parsedate_to_datetime(value)
|
|
75
|
+
except (TypeError, ValueError):
|
|
76
|
+
return None
|
|
77
|
+
if at.tzinfo is None:
|
|
78
|
+
at = at.replace(tzinfo=timezone.utc)
|
|
79
|
+
return max(0.0, (at - (now or datetime.now(timezone.utc))).total_seconds())
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _stringify(value: Any) -> str:
|
|
83
|
+
if isinstance(value, bool):
|
|
84
|
+
return "true" if value else "false"
|
|
85
|
+
return str(value)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def build_request(
|
|
89
|
+
name: str, args: Mapping[str, Any]
|
|
90
|
+
) -> Tuple[Operation, str, Dict[str, str], Optional[Dict[str, Any]]]:
|
|
91
|
+
"""Maps one operation plus keyword arguments to (operation, path, query, body)."""
|
|
92
|
+
op = OPERATIONS[name]
|
|
93
|
+
path = op.path
|
|
94
|
+
for key in op.path_params:
|
|
95
|
+
value = args.get(key)
|
|
96
|
+
if value is None or value == "":
|
|
97
|
+
raise TypeError(f"{name}() missing path parameter {key!r}")
|
|
98
|
+
path = path.replace("{" + key + "}", quote(_stringify(value), safe=""))
|
|
99
|
+
query: Dict[str, str] = {}
|
|
100
|
+
for key in op.query_params:
|
|
101
|
+
value = args.get(key)
|
|
102
|
+
if value is None:
|
|
103
|
+
continue
|
|
104
|
+
query[key] = ",".join(_stringify(v) for v in value) if isinstance(value, (list, tuple)) else _stringify(value)
|
|
105
|
+
body: Optional[Dict[str, Any]] = None
|
|
106
|
+
if op.body_params:
|
|
107
|
+
body = {k: args[k] for k in op.body_params if args.get(k) is not None}
|
|
108
|
+
elif op.method == "POST":
|
|
109
|
+
body = {}
|
|
110
|
+
return op, path, query, body
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def parse_response(status: int, headers: Mapping[str, str], text: str) -> Union[Response[Any], HandlesApiError]:
|
|
114
|
+
"""Turns an HTTP answer into a Response, or the HandlesApiError to raise."""
|
|
115
|
+
low = {k.lower(): v for k, v in headers.items()}
|
|
116
|
+
payload: Any = None
|
|
117
|
+
if text:
|
|
118
|
+
try:
|
|
119
|
+
payload = json.loads(text)
|
|
120
|
+
except ValueError:
|
|
121
|
+
payload = None
|
|
122
|
+
if 200 <= status < 300 and isinstance(payload, dict) and "data" in payload:
|
|
123
|
+
meta: ApiMeta = payload.get("meta") or {} # type: ignore[assignment]
|
|
124
|
+
return Response(
|
|
125
|
+
data=payload["data"],
|
|
126
|
+
meta=meta,
|
|
127
|
+
credits=Credits(
|
|
128
|
+
cost=_int(low.get("x-credits-cost")),
|
|
129
|
+
remaining=_int(low.get("x-credits-remaining")),
|
|
130
|
+
period_end=low.get("x-credits-period-end"),
|
|
131
|
+
),
|
|
132
|
+
rate_limit=RateLimit(
|
|
133
|
+
limit=_int(low.get("x-ratelimit-limit")),
|
|
134
|
+
remaining=_int(low.get("x-ratelimit-remaining")),
|
|
135
|
+
reset=_int(low.get("x-ratelimit-reset")),
|
|
136
|
+
),
|
|
137
|
+
request_id=meta.get("request_id") or low.get("x-request-id"),
|
|
138
|
+
headers=low,
|
|
139
|
+
)
|
|
140
|
+
err = payload.get("error") if isinstance(payload, dict) else None
|
|
141
|
+
err = err if isinstance(err, dict) else {}
|
|
142
|
+
fallback = "Response was not a { data, meta } envelope" if 200 <= status < 300 else (text[:200] or f"HTTP {status}")
|
|
143
|
+
return HandlesApiError(
|
|
144
|
+
status=status,
|
|
145
|
+
code=str(err.get("code") or "unknown"),
|
|
146
|
+
message=str(err.get("message") or fallback),
|
|
147
|
+
request_id=err.get("request_id") or low.get("x-request-id"),
|
|
148
|
+
details=err.get("details"),
|
|
149
|
+
retry_after=parse_retry_after(low.get("retry-after")),
|
|
150
|
+
headers=low,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def next_cursor(page: "Response[Any]") -> Optional[str]:
|
|
155
|
+
"""``meta.page.next_cursor``, or None when the result set is exhausted."""
|
|
156
|
+
info = page.meta.get("page")
|
|
157
|
+
return info.get("next_cursor") if info else None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def is_retryable(err: Union[HandlesApiError, HandlesApiConnectionError]) -> bool:
|
|
161
|
+
return True if isinstance(err, HandlesApiConnectionError) else err.retryable
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def retry_delay(err: Union[HandlesApiError, HandlesApiConnectionError], attempt: int) -> float:
|
|
165
|
+
"""429 honours Retry-After; everything else backs off exponentially with jitter (0.5 s, 1 s, 2 s... capped at 8 s)."""
|
|
166
|
+
if isinstance(err, HandlesApiError) and err.retry_after is not None:
|
|
167
|
+
return err.retry_after
|
|
168
|
+
base = min(8.0, 0.5 * (2.0**attempt))
|
|
169
|
+
return base / 2 + random.random() * (base / 2)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def default_headers(api_key: str, extra: Optional[Mapping[str, str]]) -> Dict[str, str]:
|
|
173
|
+
headers = {
|
|
174
|
+
"Accept": "application/json",
|
|
175
|
+
"Authorization": f"Bearer {api_key}",
|
|
176
|
+
"User-Agent": f"handlesapi-python/{VERSION}",
|
|
177
|
+
}
|
|
178
|
+
if extra:
|
|
179
|
+
headers.update(extra)
|
|
180
|
+
return headers
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
__all__: List[str] = [
|
|
184
|
+
"Credits",
|
|
185
|
+
"DEFAULT_BASE_URL",
|
|
186
|
+
"RateLimit",
|
|
187
|
+
"Response",
|
|
188
|
+
"VERSION",
|
|
189
|
+
"build_request",
|
|
190
|
+
"next_cursor",
|
|
191
|
+
"parse_response",
|
|
192
|
+
"parse_retry_after",
|
|
193
|
+
"retry_delay",
|
|
194
|
+
]
|