handlesapi 0.1.0__tar.gz

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,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,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
+ ![Handles API Python SDK: a request and its JSON response](assets/readme-handlesapi-python.png)
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
+ ![The Handles API reference page for an endpoint: request in curl, parameters and response](assets/screenshot-reference.png)
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,165 @@
1
+ ![Handles API Python SDK: a request and its JSON response](assets/readme-handlesapi-python.png)
2
+
3
+ # handlesapi-python
4
+
5
+ `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`).
6
+
7
+ ## Why
8
+
9
+ - Sync and async clients on `httpx`, with `py.typed` and `mypy --strict` clean types, so editors and type checkers know every field.
10
+ - 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.
11
+ - 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.
12
+
13
+ ## Quickstart
14
+
15
+ ### Install
16
+
17
+ ```bash
18
+ pip install handlesapi
19
+ ```
20
+
21
+ Requires Python 3.9 or newer. The only dependency is `httpx`.
22
+
23
+ ### First call
24
+
25
+ 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.
26
+
27
+ ```python
28
+ import os
29
+ from handlesapi import HandlesApi
30
+
31
+ with HandlesApi(os.environ["HANDLES_API_KEY"]) as api:
32
+ # Catalog check: 1 credit.
33
+ res = api.accounts_check("youtube", "mrbeast")
34
+ print(res.data["identity"]["name"], res.data["audience"]["count"], res.data["audience"]["metric"])
35
+ print("credits left:", res.credits.remaining)
36
+
37
+ # Live read of an X timeline: 2 credits.
38
+ tweets = api.x_users_tweets("nasa", limit=5)
39
+ for t in tweets.data["tweets"]:
40
+ print(t["likes"], t["text"])
41
+ ```
42
+
43
+ If you omit the key, the client reads `HANDLES_API_KEY` from the environment. An async twin, `AsyncHandlesApi`, has the same methods:
44
+
45
+ ```python
46
+ import asyncio
47
+ from handlesapi import AsyncHandlesApi
48
+
49
+ async def main() -> None:
50
+ async with AsyncHandlesApi() as api:
51
+ res = await api.directory_search(q="nasa", limit=3)
52
+ print(res.data["query"], res.request_id)
53
+
54
+ asyncio.run(main())
55
+ ```
56
+
57
+ ## Endpoints
58
+
59
+ ![The Handles API reference page for an endpoint: request in curl, parameters and response](assets/screenshot-reference.png)
60
+
61
+ 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`.
62
+
63
+ | Endpoint | Method |
64
+ | --- | --- |
65
+ | `GET /accounts/{platform}/{handle}` | `api.accounts_check(platform, handle)` |
66
+ | `POST /accounts/check` | `api.accounts_bulk(targets=[...])` |
67
+ | `GET /directory/search` | `api.directory_search(q=...)` |
68
+ | `GET /x/users/{handle}/tweets` | `api.x_users_tweets(handle, limit=...)` |
69
+ | `GET /insights/instagram/{handle}/top-posts` | `api.insights_instagram_top_posts(handle)` |
70
+ | `GET /trends/{platform}/movers` | `api.trends_movers(platform)` |
71
+ | `GET /leads/linkedin/companies` | `api.leads_linkedin_companies_list(country=...)` |
72
+
73
+ 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.
74
+
75
+ ## Pricing and credits
76
+
77
+ 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).
78
+
79
+ ### Credits and rate limits in code
80
+
81
+ Every `Response` carries the parsed headers:
82
+
83
+ ```python
84
+ res = api.accounts_platforms()
85
+ res.credits # Credits(cost=1, remaining=1199983, period_end="...") from X-Credits-*
86
+ res.rate_limit # RateLimit(limit, remaining, reset) from X-RateLimit-*
87
+ res.request_id # quote it to support
88
+ ```
89
+
90
+ 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).
91
+
92
+ ## Errors and retries
93
+
94
+ 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`.
95
+
96
+ ```python
97
+ from handlesapi import HandlesApi, HandlesApiError
98
+
99
+ try:
100
+ api.accounts_check("x", "nasa")
101
+ except HandlesApiError as err:
102
+ if err.code == "quota_exceeded":
103
+ print("Out of credits: upgrade or enable overage")
104
+ else:
105
+ print(err.code, err.status, err.request_id, err.details)
106
+ ```
107
+
108
+ 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`.
109
+
110
+ | Argument | Default | Meaning |
111
+ | --- | --- | --- |
112
+ | `api_key` | `HANDLES_API_KEY` | API key |
113
+ | `base_url` | `https://api.handlesapi.com/v1` | API base URL |
114
+ | `max_retries` | `2` | Retries per call (0 disables) |
115
+ | `timeout` | `60.0` | Per-attempt timeout in seconds; every method also takes `timeout=` |
116
+ | `max_retry_after` | `30.0` | Longest `Retry-After` it will sleep through |
117
+ | `http_client` | new `httpx.Client` | Bring your own client (proxies, transports) |
118
+
119
+ ## Pagination
120
+
121
+ List endpoints return `meta.page.next_cursor`. `paginate` follows it and yields one `Response` per page until the cursor is `None`:
122
+
123
+ ```python
124
+ for page in api.paginate(api.x_users_tweets, handle="nasa", limit=100, max_pages=3):
125
+ print(len(page.data["tweets"]), page.credits.remaining)
126
+ ```
127
+
128
+ Each page costs credits, so set `max_pages`. With `AsyncHandlesApi`, use `async for`. See [Pagination](https://handlesapi.com/docs/pagination).
129
+
130
+ ## Regenerating from the spec
131
+
132
+ 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:
133
+
134
+ ```bash
135
+ python scripts/generate.py # downloads the latest spec from handlesapi.com/openapi.json
136
+ python scripts/generate.py ./openapi.json # or use a local copy
137
+ ```
138
+
139
+ ## Development
140
+
141
+ ```bash
142
+ pip install -e ".[dev]"
143
+ mypy # strict type check
144
+ pytest # tests run against a mocked transport
145
+ ```
146
+
147
+ ## MCP
148
+
149
+ 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).
150
+
151
+ ## Links
152
+
153
+ - Website: [handlesapi.com](https://handlesapi.com)
154
+ - Documentation: [handlesapi.com/docs](https://handlesapi.com/docs)
155
+ - API reference: [handlesapi.com/docs/reference](https://handlesapi.com/docs/reference)
156
+ - Authentication: [handlesapi.com/docs/authentication](https://handlesapi.com/docs/authentication)
157
+ - MCP server for AI assistants: [handlesapi.com/docs/mcp](https://handlesapi.com/docs/mcp)
158
+ - Pricing: [handlesapi.com/pricing](https://handlesapi.com/pricing)
159
+ - Examples: [handlesapi/examples](https://github.com/handlesapi/examples)
160
+ - MCP server: [handlesapi/mcp](https://github.com/handlesapi/mcp)
161
+ - Changelog: [CHANGELOG.md](CHANGELOG.md), contributing: [CONTRIBUTING.md](CONTRIBUTING.md), security: [SECURITY.md](SECURITY.md)
162
+ - TypeScript client: [handlesapi-js](https://github.com/handlesapi/handlesapi-js)
163
+ - OpenAPI spec: [handlesapi.com/openapi.json](https://handlesapi.com/openapi.json), also in [handlesapi/openapi](https://github.com/handlesapi/openapi)
164
+
165
+ 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,42 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "handlesapi"
7
+ version = "0.1.0"
8
+ description = "Typed Python client for the Handles API: public social media data for X, Instagram, TikTok, YouTube, Telegram, Bluesky, Twitch, Kick and LinkedIn."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.9"
12
+ authors = [{ name = "Handles API", email = "support@handlesapi.com" }]
13
+ keywords = ["social-media-api", "twitter-api", "instagram-api", "tiktok-api", "youtube-api", "openapi", "mcp"]
14
+ classifiers = [
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3",
17
+ "Typing :: Typed",
18
+ ]
19
+ dependencies = ["httpx>=0.25,<1"]
20
+
21
+ [project.optional-dependencies]
22
+ dev = ["pytest>=7", "mypy>=1.8"]
23
+
24
+ [project.urls]
25
+ Homepage = "https://handlesapi.com"
26
+ Documentation = "https://handlesapi.com/docs"
27
+ Source = "https://github.com/handlesapi/handlesapi-python"
28
+ Issues = "https://github.com/handlesapi/handlesapi-python/issues"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
32
+
33
+ [tool.setuptools.package-data]
34
+ handlesapi = ["py.typed"]
35
+
36
+ [tool.mypy]
37
+ strict = true
38
+ files = ["src"]
39
+ warn_unused_ignores = false
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]
@@ -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
+ ]