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/client.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Synchronous and asynchronous clients."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from types import TracebackType
|
|
8
|
+
from typing import Any, AsyncIterator, Callable, Dict, Iterator, Mapping, Optional, Type, TypeVar
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from ._core import (
|
|
13
|
+
DEFAULT_BASE_URL,
|
|
14
|
+
Response,
|
|
15
|
+
build_request,
|
|
16
|
+
default_headers,
|
|
17
|
+
next_cursor,
|
|
18
|
+
is_retryable,
|
|
19
|
+
parse_response,
|
|
20
|
+
retry_delay,
|
|
21
|
+
)
|
|
22
|
+
from ._methods import AsyncOperations, SyncOperations
|
|
23
|
+
from .errors import HandlesApiConnectionError, HandlesApiError
|
|
24
|
+
|
|
25
|
+
T = TypeVar("T")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _resolve_key(api_key: Optional[str]) -> str:
|
|
29
|
+
key = api_key or os.environ.get("HANDLES_API_KEY")
|
|
30
|
+
if not key:
|
|
31
|
+
raise ValueError("Handles API key missing: pass api_key=... or set the HANDLES_API_KEY environment variable.")
|
|
32
|
+
return key
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _Config:
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
api_key: Optional[str],
|
|
39
|
+
base_url: str,
|
|
40
|
+
max_retries: int,
|
|
41
|
+
timeout: float,
|
|
42
|
+
max_retry_after: float,
|
|
43
|
+
headers: Optional[Mapping[str, str]],
|
|
44
|
+
) -> None:
|
|
45
|
+
self.api_key = _resolve_key(api_key)
|
|
46
|
+
self.base_url = base_url.rstrip("/")
|
|
47
|
+
self.max_retries = max_retries
|
|
48
|
+
self.timeout = timeout
|
|
49
|
+
self.max_retry_after = max_retry_after
|
|
50
|
+
self.headers = default_headers(self.api_key, headers)
|
|
51
|
+
|
|
52
|
+
def should_retry(self, err: "HandlesApiError | HandlesApiConnectionError", attempt: int) -> bool:
|
|
53
|
+
if attempt >= self.max_retries or not is_retryable(err):
|
|
54
|
+
return False
|
|
55
|
+
if isinstance(err, HandlesApiError) and err.retry_after is not None and err.retry_after > self.max_retry_after:
|
|
56
|
+
return False
|
|
57
|
+
return True
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _connection_error(exc: Exception, timeout: float) -> HandlesApiConnectionError:
|
|
61
|
+
if isinstance(exc, httpx.TimeoutException):
|
|
62
|
+
return HandlesApiConnectionError(f"Request timed out after {timeout} s", timed_out=True)
|
|
63
|
+
return HandlesApiConnectionError(f"Network error: {exc}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class HandlesApi(SyncOperations):
|
|
67
|
+
"""Client for the Handles API (https://handlesapi.com/docs).
|
|
68
|
+
|
|
69
|
+
There is one method per endpoint, named after its ``operationId`` in snake_case:
|
|
70
|
+
``GET /accounts/{platform}/{handle}`` is ``api.accounts_check("youtube", "mrbeast")``.
|
|
71
|
+
Path, query and body parameters are all plain arguments. Every method returns a
|
|
72
|
+
:class:`Response` with ``data``, ``meta``, ``credits``, ``rate_limit`` and ``request_id``.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
api_key: Your key (``hk_live_...``). Defaults to the ``HANDLES_API_KEY`` environment variable.
|
|
76
|
+
base_url: Defaults to ``https://api.handlesapi.com/v1``.
|
|
77
|
+
max_retries: Retries after a 429, a 5xx or a network failure. Default 2; 0 disables.
|
|
78
|
+
timeout: Per-attempt timeout in seconds. Default 60: live reads can take ten seconds or more.
|
|
79
|
+
max_retry_after: Longest ``Retry-After`` the client sleeps through; a longer wait raises. Default 30.
|
|
80
|
+
headers: Extra headers for every request.
|
|
81
|
+
http_client: Your own ``httpx.Client`` (proxies, transport, mounts).
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
api_key: Optional[str] = None,
|
|
87
|
+
*,
|
|
88
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
89
|
+
max_retries: int = 2,
|
|
90
|
+
timeout: float = 60.0,
|
|
91
|
+
max_retry_after: float = 30.0,
|
|
92
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
93
|
+
http_client: Optional[httpx.Client] = None,
|
|
94
|
+
) -> None:
|
|
95
|
+
self._cfg = _Config(api_key, base_url, max_retries, timeout, max_retry_after, headers)
|
|
96
|
+
self._owns_client = http_client is None
|
|
97
|
+
self._http = http_client or httpx.Client()
|
|
98
|
+
|
|
99
|
+
def __enter__(self) -> "HandlesApi":
|
|
100
|
+
return self
|
|
101
|
+
|
|
102
|
+
def __exit__(
|
|
103
|
+
self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]
|
|
104
|
+
) -> None:
|
|
105
|
+
self.close()
|
|
106
|
+
|
|
107
|
+
def close(self) -> None:
|
|
108
|
+
if self._owns_client:
|
|
109
|
+
self._http.close()
|
|
110
|
+
|
|
111
|
+
def request(
|
|
112
|
+
self,
|
|
113
|
+
method: str,
|
|
114
|
+
path: str,
|
|
115
|
+
*,
|
|
116
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
117
|
+
body: Optional[Any] = None,
|
|
118
|
+
timeout: Optional[float] = None,
|
|
119
|
+
) -> Response[Any]:
|
|
120
|
+
"""Calls any path below the base URL, for example ``api.request("GET", "/accounts/platforms")``."""
|
|
121
|
+
q = {k: str(v) for k, v in (query or {}).items() if v is not None}
|
|
122
|
+
return self._send(method, path, q, body, timeout)
|
|
123
|
+
|
|
124
|
+
def _op(self, name: str, args: Mapping[str, Any], timeout: Optional[float] = None) -> Any:
|
|
125
|
+
op, path, query, body = build_request(name, args)
|
|
126
|
+
return self._send(op.method, path, query, body, timeout)
|
|
127
|
+
|
|
128
|
+
def _send(
|
|
129
|
+
self, method: str, path: str, query: Dict[str, str], body: Optional[Any], timeout: Optional[float]
|
|
130
|
+
) -> Response[Any]:
|
|
131
|
+
cfg = self._cfg
|
|
132
|
+
wait = timeout if timeout is not None else cfg.timeout
|
|
133
|
+
attempt = 0
|
|
134
|
+
while True:
|
|
135
|
+
err: "HandlesApiError | HandlesApiConnectionError"
|
|
136
|
+
try:
|
|
137
|
+
res = self._http.request(
|
|
138
|
+
method, cfg.base_url + path, params=query or None, json=body, headers=cfg.headers, timeout=wait
|
|
139
|
+
)
|
|
140
|
+
except httpx.HTTPError as exc:
|
|
141
|
+
err = _connection_error(exc, wait)
|
|
142
|
+
else:
|
|
143
|
+
parsed = parse_response(res.status_code, res.headers, res.text)
|
|
144
|
+
if isinstance(parsed, Response):
|
|
145
|
+
return parsed
|
|
146
|
+
err = parsed
|
|
147
|
+
if not cfg.should_retry(err, attempt):
|
|
148
|
+
raise err
|
|
149
|
+
time.sleep(retry_delay(err, attempt))
|
|
150
|
+
attempt += 1
|
|
151
|
+
|
|
152
|
+
def paginate(
|
|
153
|
+
self, method: Callable[..., Response[Any]], *, max_pages: Optional[int] = None, **kwargs: Any
|
|
154
|
+
) -> Iterator[Response[Any]]:
|
|
155
|
+
"""Follows ``meta.page.next_cursor``, yielding one :class:`Response` per page.
|
|
156
|
+
|
|
157
|
+
Stops when the cursor is ``None``, the only reliable end of a result set, or after ``max_pages``::
|
|
158
|
+
|
|
159
|
+
for page in api.paginate(api.x_users_tweets, handle="nasa", limit=100, max_pages=3):
|
|
160
|
+
print(len(page.data.get("tweets") or []), page.credits.remaining)
|
|
161
|
+
"""
|
|
162
|
+
cursor = kwargs.pop("cursor", None)
|
|
163
|
+
pages = 0
|
|
164
|
+
while max_pages is None or pages < max_pages:
|
|
165
|
+
page = method(cursor=cursor, **kwargs)
|
|
166
|
+
yield page
|
|
167
|
+
pages += 1
|
|
168
|
+
cursor = next_cursor(page)
|
|
169
|
+
if not cursor:
|
|
170
|
+
return
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class AsyncHandlesApi(AsyncOperations):
|
|
174
|
+
"""Asynchronous twin of :class:`HandlesApi`: the same methods, awaited, on ``httpx.AsyncClient``."""
|
|
175
|
+
|
|
176
|
+
def __init__(
|
|
177
|
+
self,
|
|
178
|
+
api_key: Optional[str] = None,
|
|
179
|
+
*,
|
|
180
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
181
|
+
max_retries: int = 2,
|
|
182
|
+
timeout: float = 60.0,
|
|
183
|
+
max_retry_after: float = 30.0,
|
|
184
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
185
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
186
|
+
) -> None:
|
|
187
|
+
self._cfg = _Config(api_key, base_url, max_retries, timeout, max_retry_after, headers)
|
|
188
|
+
self._owns_client = http_client is None
|
|
189
|
+
self._http = http_client or httpx.AsyncClient()
|
|
190
|
+
|
|
191
|
+
async def __aenter__(self) -> "AsyncHandlesApi":
|
|
192
|
+
return self
|
|
193
|
+
|
|
194
|
+
async def __aexit__(
|
|
195
|
+
self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]
|
|
196
|
+
) -> None:
|
|
197
|
+
await self.aclose()
|
|
198
|
+
|
|
199
|
+
async def aclose(self) -> None:
|
|
200
|
+
if self._owns_client:
|
|
201
|
+
await self._http.aclose()
|
|
202
|
+
|
|
203
|
+
async def request(
|
|
204
|
+
self,
|
|
205
|
+
method: str,
|
|
206
|
+
path: str,
|
|
207
|
+
*,
|
|
208
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
209
|
+
body: Optional[Any] = None,
|
|
210
|
+
timeout: Optional[float] = None,
|
|
211
|
+
) -> Response[Any]:
|
|
212
|
+
"""Calls any path below the base URL."""
|
|
213
|
+
q = {k: str(v) for k, v in (query or {}).items() if v is not None}
|
|
214
|
+
return await self._send(method, path, q, body, timeout)
|
|
215
|
+
|
|
216
|
+
async def _op(self, name: str, args: Mapping[str, Any], timeout: Optional[float] = None) -> Any:
|
|
217
|
+
op, path, query, body = build_request(name, args)
|
|
218
|
+
return await self._send(op.method, path, query, body, timeout)
|
|
219
|
+
|
|
220
|
+
async def _send(
|
|
221
|
+
self, method: str, path: str, query: Dict[str, str], body: Optional[Any], timeout: Optional[float]
|
|
222
|
+
) -> Response[Any]:
|
|
223
|
+
cfg = self._cfg
|
|
224
|
+
wait = timeout if timeout is not None else cfg.timeout
|
|
225
|
+
attempt = 0
|
|
226
|
+
while True:
|
|
227
|
+
err: "HandlesApiError | HandlesApiConnectionError"
|
|
228
|
+
try:
|
|
229
|
+
res = await self._http.request(
|
|
230
|
+
method, cfg.base_url + path, params=query or None, json=body, headers=cfg.headers, timeout=wait
|
|
231
|
+
)
|
|
232
|
+
except httpx.HTTPError as exc:
|
|
233
|
+
err = _connection_error(exc, wait)
|
|
234
|
+
else:
|
|
235
|
+
parsed = parse_response(res.status_code, res.headers, res.text)
|
|
236
|
+
if isinstance(parsed, Response):
|
|
237
|
+
return parsed
|
|
238
|
+
err = parsed
|
|
239
|
+
if not cfg.should_retry(err, attempt):
|
|
240
|
+
raise err
|
|
241
|
+
await asyncio.sleep(retry_delay(err, attempt))
|
|
242
|
+
attempt += 1
|
|
243
|
+
|
|
244
|
+
async def paginate(
|
|
245
|
+
self, method: Callable[..., Any], *, max_pages: Optional[int] = None, **kwargs: Any
|
|
246
|
+
) -> AsyncIterator[Response[Any]]:
|
|
247
|
+
"""Async version of :meth:`HandlesApi.paginate`: ``async for page in api.paginate(api.x_users_tweets, ...)``."""
|
|
248
|
+
cursor = kwargs.pop("cursor", None)
|
|
249
|
+
pages = 0
|
|
250
|
+
while max_pages is None or pages < max_pages:
|
|
251
|
+
page: Response[Any] = await method(cursor=cursor, **kwargs)
|
|
252
|
+
yield page
|
|
253
|
+
pages += 1
|
|
254
|
+
cursor = next_cursor(page)
|
|
255
|
+
if not cursor:
|
|
256
|
+
return
|
handlesapi/errors.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Exceptions raised by the Handles API client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Dict, Mapping, Optional
|
|
5
|
+
|
|
6
|
+
RETRYABLE_CODES = frozenset(
|
|
7
|
+
{
|
|
8
|
+
"rate_limited",
|
|
9
|
+
"live_limit_reached",
|
|
10
|
+
"platform_unavailable",
|
|
11
|
+
"upstream_timeout",
|
|
12
|
+
"upstream_error",
|
|
13
|
+
"service_unavailable",
|
|
14
|
+
"internal_error",
|
|
15
|
+
}
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class HandlesApiError(Exception):
|
|
20
|
+
"""A non-2xx answer from the API. Branch on ``code``, never on the message.
|
|
21
|
+
|
|
22
|
+
Attributes:
|
|
23
|
+
status: HTTP status code.
|
|
24
|
+
code: Stable machine-readable code from ``error.code`` (``"unknown"`` when the body was not JSON).
|
|
25
|
+
message: Human-readable explanation. Prose, not a contract.
|
|
26
|
+
request_id: Quote this to support: it identifies your exact call.
|
|
27
|
+
details: Field-level detail on ``invalid_request``, parameter name to reason.
|
|
28
|
+
retry_after: Seconds to wait, from the ``Retry-After`` header, when the API sent one.
|
|
29
|
+
headers: Response headers.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
*,
|
|
35
|
+
status: int,
|
|
36
|
+
code: str,
|
|
37
|
+
message: str,
|
|
38
|
+
request_id: Optional[str] = None,
|
|
39
|
+
details: Optional[Dict[str, str]] = None,
|
|
40
|
+
retry_after: Optional[float] = None,
|
|
41
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
42
|
+
) -> None:
|
|
43
|
+
super().__init__(f"{code} (HTTP {status}): {message}")
|
|
44
|
+
self.status = status
|
|
45
|
+
self.code = code
|
|
46
|
+
self.message = message
|
|
47
|
+
self.request_id = request_id
|
|
48
|
+
self.details = details
|
|
49
|
+
self.retry_after = retry_after
|
|
50
|
+
self.headers: Mapping[str, str] = headers or {}
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def retryable(self) -> bool:
|
|
54
|
+
"""True for codes where waiting and retrying can succeed. ``quota_exceeded`` is not one of them."""
|
|
55
|
+
return self.code in RETRYABLE_CODES or (self.code == "unknown" and self.status >= 500)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class HandlesApiConnectionError(Exception):
|
|
59
|
+
"""The request never produced an HTTP answer: DNS, TLS, a reset, or the client's own timeout."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, message: str, *, timed_out: bool = False) -> None:
|
|
62
|
+
super().__init__(message)
|
|
63
|
+
self.timed_out = timed_out
|
handlesapi/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: handlesapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed Python client for the Handles API: public social media data for X, Instagram, TikTok, YouTube, Telegram, Bluesky, Twitch, Kick and LinkedIn.
|
|
5
|
+
Author-email: Handles API <support@handlesapi.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://handlesapi.com
|
|
8
|
+
Project-URL: Documentation, https://handlesapi.com/docs
|
|
9
|
+
Project-URL: Source, https://github.com/handlesapi/handlesapi-python
|
|
10
|
+
Project-URL: Issues, https://github.com/handlesapi/handlesapi-python/issues
|
|
11
|
+
Keywords: social-media-api,twitter-api,instagram-api,tiktok-api,youtube-api,openapi,mcp
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: httpx<1,>=0.25
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
21
|
+
Requires-Dist: mypy>=1.8; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+

|
|
25
|
+
|
|
26
|
+
# handlesapi-python
|
|
27
|
+
|
|
28
|
+
`handlesapi-python` is the Python client for [Handles API](https://handlesapi.com), a REST and MCP API that returns public data from X (Twitter), Instagram, TikTok, YouTube, Telegram, Bluesky, Twitch, Kick and LinkedIn companies in one consistent JSON shape. It wraps all 113 endpoints from the [OpenAPI spec](https://github.com/handlesapi/openapi) in typed methods, with a sync client and an async client, both built on `httpx`. Responses are typed with `TypedDict`, and the package ships `py.typed` (checked with `mypy --strict`).
|
|
29
|
+
|
|
30
|
+
## Why
|
|
31
|
+
|
|
32
|
+
- Sync and async clients on `httpx`, with `py.typed` and `mypy --strict` clean types, so editors and type checkers know every field.
|
|
33
|
+
- Every one of the 113 endpoints is a method, generated from the OpenAPI spec by the generator in this repo, so the client and the API cannot drift silently.
|
|
34
|
+
- The things you would otherwise write yourself are built in: `X-Credits-*` parsing, `Retry-After` handling, backoff for transient failures, cursor pagination and typed errors.
|
|
35
|
+
|
|
36
|
+
## Quickstart
|
|
37
|
+
|
|
38
|
+
### Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install handlesapi
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Requires Python 3.9 or newer. The only dependency is `httpx`.
|
|
45
|
+
|
|
46
|
+
### First call
|
|
47
|
+
|
|
48
|
+
Get an API key at [handlesapi.com/signup](https://handlesapi.com/signup). The Free plan gives you 100 credits to try every endpoint, once, with no card. Keep the key on the server: it spends your credits.
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import os
|
|
52
|
+
from handlesapi import HandlesApi
|
|
53
|
+
|
|
54
|
+
with HandlesApi(os.environ["HANDLES_API_KEY"]) as api:
|
|
55
|
+
# Catalog check: 1 credit.
|
|
56
|
+
res = api.accounts_check("youtube", "mrbeast")
|
|
57
|
+
print(res.data["identity"]["name"], res.data["audience"]["count"], res.data["audience"]["metric"])
|
|
58
|
+
print("credits left:", res.credits.remaining)
|
|
59
|
+
|
|
60
|
+
# Live read of an X timeline: 2 credits.
|
|
61
|
+
tweets = api.x_users_tweets("nasa", limit=5)
|
|
62
|
+
for t in tweets.data["tweets"]:
|
|
63
|
+
print(t["likes"], t["text"])
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
If you omit the key, the client reads `HANDLES_API_KEY` from the environment. An async twin, `AsyncHandlesApi`, has the same methods:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
import asyncio
|
|
70
|
+
from handlesapi import AsyncHandlesApi
|
|
71
|
+
|
|
72
|
+
async def main() -> None:
|
|
73
|
+
async with AsyncHandlesApi() as api:
|
|
74
|
+
res = await api.directory_search(q="nasa", limit=3)
|
|
75
|
+
print(res.data["query"], res.request_id)
|
|
76
|
+
|
|
77
|
+
asyncio.run(main())
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Endpoints
|
|
81
|
+
|
|
82
|
+

|
|
83
|
+
|
|
84
|
+
Every endpoint has a method named after its `operationId` in snake_case. Path, query and body parameters are plain arguments (required ones first, the rest keyword-only), and `data` is a `TypedDict`.
|
|
85
|
+
|
|
86
|
+
| Endpoint | Method |
|
|
87
|
+
| --- | --- |
|
|
88
|
+
| `GET /accounts/{platform}/{handle}` | `api.accounts_check(platform, handle)` |
|
|
89
|
+
| `POST /accounts/check` | `api.accounts_bulk(targets=[...])` |
|
|
90
|
+
| `GET /directory/search` | `api.directory_search(q=...)` |
|
|
91
|
+
| `GET /x/users/{handle}/tweets` | `api.x_users_tweets(handle, limit=...)` |
|
|
92
|
+
| `GET /insights/instagram/{handle}/top-posts` | `api.insights_instagram_top_posts(handle)` |
|
|
93
|
+
| `GET /trends/{platform}/movers` | `api.trends_movers(platform)` |
|
|
94
|
+
| `GET /leads/linkedin/companies` | `api.leads_linkedin_companies_list(country=...)` |
|
|
95
|
+
|
|
96
|
+
The full list, with credit costs, is `handlesapi.OPERATIONS` and the [API reference](https://handlesapi.com/docs/reference). `api.request("GET", "/accounts/platforms")` reaches any path directly.
|
|
97
|
+
|
|
98
|
+
## Pricing and credits
|
|
99
|
+
|
|
100
|
+
Catalog, insights, identity and lead reads cost 1 credit; live reads cost 2. Plans: Free (100 credits, once, no card), Starter ($29 a month, 15,000 credits), Pro ($99, 75,000), Business ($299, 300,000), Scale ($799, 1,200,000). See [Credits and limits](https://handlesapi.com/docs/credits-and-limits) and [pricing](https://handlesapi.com/pricing).
|
|
101
|
+
|
|
102
|
+
### Credits and rate limits in code
|
|
103
|
+
|
|
104
|
+
Every `Response` carries the parsed headers:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
res = api.accounts_platforms()
|
|
108
|
+
res.credits # Credits(cost=1, remaining=1199983, period_end="...") from X-Credits-*
|
|
109
|
+
res.rate_limit # RateLimit(limit, remaining, reset) from X-RateLimit-*
|
|
110
|
+
res.request_id # quote it to support
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Catalog, insights, identity and lead reads cost 1 credit; live reads cost 2. See [Credits and limits](https://handlesapi.com/docs/credits-and-limits) and [pricing](https://handlesapi.com/pricing).
|
|
114
|
+
|
|
115
|
+
## Errors and retries
|
|
116
|
+
|
|
117
|
+
Every failure raises `HandlesApiError` with the stable `code`, the HTTP `status`, `request_id` and, for `invalid_request`, per-field `details`. Branch on `code`, never on the message. Failures that never reach the API raise `HandlesApiConnectionError`.
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from handlesapi import HandlesApi, HandlesApiError
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
api.accounts_check("x", "nasa")
|
|
124
|
+
except HandlesApiError as err:
|
|
125
|
+
if err.code == "quota_exceeded":
|
|
126
|
+
print("Out of credits: upgrade or enable overage")
|
|
127
|
+
else:
|
|
128
|
+
print(err.code, err.status, err.request_id, err.details)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
The client retries what the [error table](https://handlesapi.com/docs/errors) marks as retryable: `rate_limited` and `live_limit_reached` (it waits for `Retry-After`, up to 30 seconds, otherwise it raises), and `platform_unavailable`, `upstream_timeout`, `upstream_error`, `service_unavailable`, `internal_error` plus network failures (exponential backoff with jitter, 0.5 s to 8 s). It never retries `quota_exceeded`, `invalid_request`, `unauthorized` or `not_found`.
|
|
132
|
+
|
|
133
|
+
| Argument | Default | Meaning |
|
|
134
|
+
| --- | --- | --- |
|
|
135
|
+
| `api_key` | `HANDLES_API_KEY` | API key |
|
|
136
|
+
| `base_url` | `https://api.handlesapi.com/v1` | API base URL |
|
|
137
|
+
| `max_retries` | `2` | Retries per call (0 disables) |
|
|
138
|
+
| `timeout` | `60.0` | Per-attempt timeout in seconds; every method also takes `timeout=` |
|
|
139
|
+
| `max_retry_after` | `30.0` | Longest `Retry-After` it will sleep through |
|
|
140
|
+
| `http_client` | new `httpx.Client` | Bring your own client (proxies, transports) |
|
|
141
|
+
|
|
142
|
+
## Pagination
|
|
143
|
+
|
|
144
|
+
List endpoints return `meta.page.next_cursor`. `paginate` follows it and yields one `Response` per page until the cursor is `None`:
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
for page in api.paginate(api.x_users_tweets, handle="nasa", limit=100, max_pages=3):
|
|
148
|
+
print(len(page.data["tweets"]), page.credits.remaining)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Each page costs credits, so set `max_pages`. With `AsyncHandlesApi`, use `async for`. See [Pagination](https://handlesapi.com/docs/pagination).
|
|
152
|
+
|
|
153
|
+
## Regenerating from the spec
|
|
154
|
+
|
|
155
|
+
The types and method list under `src/handlesapi/` (`_types.py`, `_operations.py`, `_methods.py`) are generated from [`openapi.json`](https://github.com/handlesapi/openapi). The generator is part of this repo and uses only the standard library:
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
python scripts/generate.py # downloads the latest spec from handlesapi.com/openapi.json
|
|
159
|
+
python scripts/generate.py ./openapi.json # or use a local copy
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## Development
|
|
163
|
+
|
|
164
|
+
```bash
|
|
165
|
+
pip install -e ".[dev]"
|
|
166
|
+
mypy # strict type check
|
|
167
|
+
pytest # tests run against a mocked transport
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## MCP
|
|
171
|
+
|
|
172
|
+
The same API is available to AI assistants as a remote [Model Context Protocol](https://modelcontextprotocol.io) server at `https://api.handlesapi.com/mcp`, with 23 tools that spend the same credits. Setup for Claude, Cursor, VS Code and Claude Code is in [handlesapi/mcp](https://github.com/handlesapi/mcp); the tool list is in the [MCP docs](https://handlesapi.com/docs/mcp).
|
|
173
|
+
|
|
174
|
+
## Links
|
|
175
|
+
|
|
176
|
+
- Website: [handlesapi.com](https://handlesapi.com)
|
|
177
|
+
- Documentation: [handlesapi.com/docs](https://handlesapi.com/docs)
|
|
178
|
+
- API reference: [handlesapi.com/docs/reference](https://handlesapi.com/docs/reference)
|
|
179
|
+
- Authentication: [handlesapi.com/docs/authentication](https://handlesapi.com/docs/authentication)
|
|
180
|
+
- MCP server for AI assistants: [handlesapi.com/docs/mcp](https://handlesapi.com/docs/mcp)
|
|
181
|
+
- Pricing: [handlesapi.com/pricing](https://handlesapi.com/pricing)
|
|
182
|
+
- Examples: [handlesapi/examples](https://github.com/handlesapi/examples)
|
|
183
|
+
- MCP server: [handlesapi/mcp](https://github.com/handlesapi/mcp)
|
|
184
|
+
- Changelog: [CHANGELOG.md](CHANGELOG.md), contributing: [CONTRIBUTING.md](CONTRIBUTING.md), security: [SECURITY.md](SECURITY.md)
|
|
185
|
+
- TypeScript client: [handlesapi-js](https://github.com/handlesapi/handlesapi-js)
|
|
186
|
+
- OpenAPI spec: [handlesapi.com/openapi.json](https://handlesapi.com/openapi.json), also in [handlesapi/openapi](https://github.com/handlesapi/openapi)
|
|
187
|
+
|
|
188
|
+
Handles API is an independent service and is not affiliated with any of the platforms it covers. It returns public data only. MIT licensed.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
handlesapi/__init__.py,sha256=hEDa3R565fWgMMmuA5eanP4t6X-0NN0WT9FE5MV8EGg,679
|
|
2
|
+
handlesapi/_core.py,sha256=mf1JVZIPCjOSieg2etasplW-XPhNVgBz-MQxJDC0RfM,6485
|
|
3
|
+
handlesapi/_methods.py,sha256=91EkQZHtFfjOZvbfDL8hVNl3X4_Env0YJKwJaUSiHMA,180182
|
|
4
|
+
handlesapi/_operations.py,sha256=nLTqwwV7xn4xZzGj3qJQFclSixexIUxcF2XUG_s2Qzs,22411
|
|
5
|
+
handlesapi/_types.py,sha256=9O1iP9U6DFxqY46390tPVmWn9qgO54ORziKAxLBcYC8,161488
|
|
6
|
+
handlesapi/client.py,sha256=qk081ZMAuGbzb8ihN2_HV1o_2J1GErokOoOZYJh1xzo,9776
|
|
7
|
+
handlesapi/errors.py,sha256=Obl24yed2mVn-hGmt1BuzFdOnBeP4yRdfSvrCg-mubo,2174
|
|
8
|
+
handlesapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
handlesapi-0.1.0.dist-info/licenses/LICENSE,sha256=r1LIxaYhULQCp_q3nlQ2_j0ZJN2JcbFceiKuMhAJY9A,1073
|
|
10
|
+
handlesapi-0.1.0.dist-info/METADATA,sha256=NJKe21s0TD26vy6dZS6zr1LSgM8SyHQtujYjzhdhK2A,9493
|
|
11
|
+
handlesapi-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
handlesapi-0.1.0.dist-info/top_level.txt,sha256=IyNNe3DLbKAO6HQ_4Sq0jYut29AtP81R6Vioo6IVlVY,11
|
|
13
|
+
handlesapi-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DUCK DIGITAL LTD
|
|
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
|
+
handlesapi
|