toktokdata 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.
Files changed (38) hide show
  1. toktokdata-0.1.0/.gitignore +12 -0
  2. toktokdata-0.1.0/LICENSE +21 -0
  3. toktokdata-0.1.0/PKG-INFO +355 -0
  4. toktokdata-0.1.0/README.md +324 -0
  5. toktokdata-0.1.0/pyproject.toml +63 -0
  6. toktokdata-0.1.0/src/toktokdata/__init__.py +37 -0
  7. toktokdata-0.1.0/src/toktokdata/_client.py +298 -0
  8. toktokdata-0.1.0/src/toktokdata/_errors.py +172 -0
  9. toktokdata-0.1.0/src/toktokdata/_transport.py +111 -0
  10. toktokdata-0.1.0/src/toktokdata/_types.py +118 -0
  11. toktokdata-0.1.0/src/toktokdata/_util.py +46 -0
  12. toktokdata-0.1.0/src/toktokdata/_version.py +1 -0
  13. toktokdata-0.1.0/src/toktokdata/_webhooks.py +109 -0
  14. toktokdata-0.1.0/src/toktokdata/py.typed +0 -0
  15. toktokdata-0.1.0/src/toktokdata/resources/__init__.py +29 -0
  16. toktokdata-0.1.0/src/toktokdata/resources/_base.py +16 -0
  17. toktokdata-0.1.0/src/toktokdata/resources/account.py +16 -0
  18. toktokdata-0.1.0/src/toktokdata/resources/agencies.py +35 -0
  19. toktokdata-0.1.0/src/toktokdata/resources/alerts.py +68 -0
  20. toktokdata-0.1.0/src/toktokdata/resources/creators.py +95 -0
  21. toktokdata-0.1.0/src/toktokdata/resources/exports.py +87 -0
  22. toktokdata-0.1.0/src/toktokdata/resources/gifters.py +22 -0
  23. toktokdata-0.1.0/src/toktokdata/resources/gifts.py +31 -0
  24. toktokdata-0.1.0/src/toktokdata/resources/insights.py +16 -0
  25. toktokdata-0.1.0/src/toktokdata/resources/live.py +101 -0
  26. toktokdata-0.1.0/src/toktokdata/resources/rankings.py +98 -0
  27. toktokdata-0.1.0/src/toktokdata/resources/trends.py +12 -0
  28. toktokdata-0.1.0/src/toktokdata/resources/videos.py +48 -0
  29. toktokdata-0.1.0/tests/conftest.py +139 -0
  30. toktokdata-0.1.0/tests/test_client.py +232 -0
  31. toktokdata-0.1.0/tests/test_errors.py +109 -0
  32. toktokdata-0.1.0/tests/test_exports.py +77 -0
  33. toktokdata-0.1.0/tests/test_pagination.py +87 -0
  34. toktokdata-0.1.0/tests/test_pending.py +137 -0
  35. toktokdata-0.1.0/tests/test_retries.py +175 -0
  36. toktokdata-0.1.0/tests/test_routes.py +447 -0
  37. toktokdata-0.1.0/tests/test_transport.py +112 -0
  38. toktokdata-0.1.0/tests/test_webhooks.py +102 -0
@@ -0,0 +1,12 @@
1
+ .venv/
2
+ venv/
3
+ __pycache__/
4
+ *.py[cod]
5
+ *.egg-info/
6
+ build/
7
+ dist/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ htmlcov/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 toktokdata.live
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,355 @@
1
+ Metadata-Version: 2.5
2
+ Name: toktokdata
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the toktokdata.live API (TikTok LIVE rankings, creators, gifters, LIVE sessions, alerts, exports).
5
+ Project-URL: Documentation, https://toktokdata.live/docs
6
+ Project-URL: Homepage, https://toktokdata.live
7
+ Project-URL: Issues, https://github.com/MKK-Platform/toktokdata-sdks/issues
8
+ Project-URL: Source, https://github.com/MKK-Platform/toktokdata-sdks/tree/main/python
9
+ Author: toktokdata.live
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: api,live,rankings,sdk,tiktok,toktokdata
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Internet :: WWW/HTTP
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Provides-Extra: dev
27
+ Requires-Dist: mypy>=1.11; extra == 'dev'
28
+ Requires-Dist: pytest>=8; extra == 'dev'
29
+ Requires-Dist: ruff>=0.6; extra == 'dev'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # toktokdata (Python)
33
+
34
+ Official Python client for the [toktokdata.live](https://toktokdata.live) API: TikTok LIVE
35
+ rankings, creators, gifters, agencies, LIVE sessions, trends, alerts and exports.
36
+
37
+ - Python 3.10+, **no runtime dependencies** (standard library `urllib` only), fully typed (`py.typed`).
38
+ - Auth, retries with `Retry-After`, waiting for data that is still being collected (`202`),
39
+ cursor pagination, typed errors, rate-limit info and a webhook signature helper.
40
+
41
+ API docs: <https://toktokdata.live/docs> · Reference: <https://toktokdata.live/docs/reference>
42
+
43
+ ## Install
44
+
45
+ ```bash
46
+ pip install toktokdata
47
+ ```
48
+
49
+ ## Quickstart
50
+
51
+ Create a key at <https://toktokdata.live> (**Settings → API keys**) and keep it in the environment:
52
+
53
+ ```bash
54
+ export TOKTOKDATA_API_KEY=ttk_live_...
55
+ ```
56
+
57
+ ```python
58
+ from toktokdata import TokTokData
59
+
60
+ with TokTokData() as client: # reads TOKTOKDATA_API_KEY
61
+ board = client.rankings.official("hourly", region="VN", limit=10)
62
+ for entry in board["data"]["board"]["entries"]:
63
+ print(entry["rank"], entry["uniqueId"], entry["score"])
64
+ ```
65
+
66
+ Every method returns the parsed JSON body unchanged, as a plain `dict`. Reads look like
67
+ `{"data": ..., "provenance": {...}}`; exports and alert rules are flat objects. Field names are
68
+ the API's (camelCase); method and argument names are snake_case.
69
+
70
+ ## Configuration
71
+
72
+ ```python
73
+ client = TokTokData(
74
+ api_key="ttk_live_...", # default: TOKTOKDATA_API_KEY (required, checked here)
75
+ base_url="https://api.toktokdata.live", # default: TOKTOKDATA_BASE_URL or this URL
76
+ timeout=30.0, # seconds per HTTP request
77
+ max_retries=2, # retries after the first attempt
78
+ pending_timeout=180.0, # how long 202-aware methods wait (keyword-only)
79
+ )
80
+ ```
81
+
82
+ The client never logs or prints the key (`repr(client)` masks it). Call `client.close()` or
83
+ use it as a context manager.
84
+
85
+ ## One example per namespace
86
+
87
+ ```python
88
+ # rankings: official boards (daily, hourly, popular_live, gaming_*, shopping_*, league_a1..d5)
89
+ client.rankings.official("daily", region="VN", period="current", live_only=True)
90
+ client.rankings.regions()
91
+ client.rankings.history("daily", region="VN", limit=24)
92
+ client.rankings.day_bars(region="VN", board="daily", days=30)
93
+ client.rankings.masked("<maskedRef from a board entry>")
94
+
95
+ # creators: uid is a handle (a leading "@" is stripped) or a numeric TikTok user id
96
+ client.creators.search(q="linh", limit=20)
97
+ client.creators.get("linh.live") # waits on 202 while TikTok is read
98
+ client.creators.analysis("linh.live")
99
+ client.creators.changes("linh.live", limit=50)
100
+ client.creators.followers("linh.live", limit=100)
101
+ client.creators.following("linh.live")
102
+ client.creators.gifters("linh.live", window="30d")
103
+ client.creators.insights("linh.live")
104
+ client.creators.videos("linh.live")
105
+
106
+ # agencies
107
+ client.agencies.list(region="VN", public_only=True, sort="revenue", limit=50, offset=0)
108
+ client.agencies.get("<agency id>")
109
+
110
+ # insights
111
+ client.insights.best_time(region="VN")
112
+ client.insights.presence(region="VN", hours=48)
113
+
114
+ # videos
115
+ client.videos.get("7300000000000000000")
116
+ client.videos.comments("7300000000000000000", limit=50)
117
+
118
+ # trends, gifts, gifters
119
+ client.trends.list(region="US", type="hashtag")
120
+ client.gifts.list(q="rose", min_coins=1, max_coins=100, sort="coins")
121
+ client.gifters.list(window="7d", segment="whale", region="VN")
122
+
123
+ # live
124
+ client.live.sessions(creator_unique_id="linh.live", limit=50)
125
+ client.live.session("<session id>")
126
+ client.live.timeline("<session id>")
127
+ client.live.compare(["<session id>", "<session id>"]) # 2 to 4 ids
128
+ client.live.performance("linh.live")
129
+ client.live.refresh("linh.live") # 202 {"queued": true, "jobId": ...}
130
+ client.live.playback("linh.live") # needs the live:stream scope
131
+ chat = client.live.comments("linh.live")
132
+ newer = client.live.comments("linh.live", after=chat["cursor"])
133
+
134
+ # alerts
135
+ created = client.alerts.create_rule(
136
+ {
137
+ "name": "Whale gifts",
138
+ "scope": "watchlist",
139
+ "eventTypes": ["gift", "envelope"],
140
+ "minDiamondCount": 1000,
141
+ "channels": [{"channelType": "webhook", "target": "https://example.com/hooks/toktokdata"}],
142
+ }
143
+ )
144
+ rule_id = created["rule"]["id"] # created["webhookSecrets"]: signing secrets
145
+ client.alerts.update_rule(rule_id, {"enabled": False})
146
+ client.alerts.test_rule(rule_id)
147
+ client.alerts.list_rules()
148
+ client.alerts.fires(rule_id=rule_id, limit=20)
149
+ client.alerts.deliveries(status="failed", since="2026-11-01T00:00:00Z")
150
+ client.alerts.stats()
151
+ client.alerts.delete_rule(rule_id) # returns None (204)
152
+
153
+ # exports
154
+ job = client.exports.create(dataset="rankings", format="csv", board="daily", region="VN")
155
+ job = client.exports.wait_until_ready(job["id"]) # no-op when it is already ready
156
+ if job["status"] == "ready":
157
+ open(job["filename"], "wb").write(client.exports.download(job["id"]))
158
+ client.exports.list()
159
+
160
+ # account
161
+ client.account.entitlements()
162
+ client.account.usage(limit=50)
163
+ ```
164
+
165
+ Type hints list the accepted enum values (for example `period: "current" | "history"`), and
166
+ `toktokdata.AlertRuleInput` describes the alert rule body. Any route can also be called
167
+ directly with `client.request("GET", "/v1/...", query={...})`.
168
+
169
+ ## Errors
170
+
171
+ Every failed call raises `toktokdata.TokTokDataError`:
172
+
173
+ ```python
174
+ from toktokdata import TokTokDataError
175
+
176
+ try:
177
+ client.creators.get("linh.live")
178
+ except TokTokDataError as err:
179
+ print(err.status, err.code, err.message, err.request_id)
180
+ if err.is_payment_required: # 402 credit_cap_exceeded
181
+ print("credits reset at", err.details.get("resetAt"))
182
+ elif err.is_rate_limited: # 429 (incl. daily_quota_exceeded)
183
+ print("retry in", err.retry_after, "s")
184
+ elif err.is_forbidden: # 403 insufficient_scope / module_not_entitled
185
+ ...
186
+ elif err.is_unauthorized: # 401
187
+ ...
188
+ elif err.is_not_found: # 404
189
+ ...
190
+ ```
191
+
192
+ | Field | Meaning |
193
+ |---|---|
194
+ | `status` | HTTP status (`0` when no response arrived: `code` is `network_error` or `timeout`) |
195
+ | `code` | Machine-readable code from the envelope; `http_error` when the body was not JSON |
196
+ | `message` | Human-readable message |
197
+ | `request_id` | Quote it to support |
198
+ | `retryable` | The API's hint whether a retry may succeed |
199
+ | `retry_after` | Seconds from the `Retry-After` header, or `None` |
200
+ | `details` | The whole error envelope (for example `resetAt`) |
201
+
202
+ `PendingTimeoutError` (a subclass) is raised when a 202 read or an export is still not ready
203
+ after the wait; `WebhookVerificationError` (a subclass) by `verify_webhook`.
204
+
205
+ ## Retries
206
+
207
+ The client retries up to `max_retries` times (default 2):
208
+
209
+ - `429` rate limits, waiting `Retry-After` seconds (capped at 60 s). A `429` with code
210
+ `daily_quota_exceeded` is not retried: the quota resets at midnight UTC.
211
+ - `5xx` answers whose envelope says `retryable: true` (or that have no envelope), GET only.
212
+ - Network errors and timeouts, GET only.
213
+
214
+ Without `Retry-After` it backs off 0.5 s, 1 s, 2 s ... with jitter. `402` and other `4xx`
215
+ are never retried, and a POST/PATCH/DELETE is not retried once it may have reached the server.
216
+
217
+ ## Waiting for fresh data (202)
218
+
219
+ `creators.get`, `creators.followers`, `creators.following`, `videos.comments` and
220
+ `live.playback` may answer `202` (`{"status": "resolving" | "saturated", "jobId",
221
+ "retryAfterSeconds"}`) while toktokdata.live reads TikTok. These methods wait
222
+ `retryAfterSeconds` (clamped to 1-120 s) and ask again until the data is there, for up to
223
+ `pending_timeout` seconds (180 by default), then raise `PendingTimeoutError`. A 202 is never
224
+ billed beyond a cached read.
225
+
226
+ ```python
227
+ from toktokdata import PendingTimeoutError
228
+
229
+ try:
230
+ profile = client.creators.get("new.creator")
231
+ except PendingTimeoutError as err:
232
+ print("still resolving, job", err.job_id)
233
+
234
+ # Or handle it yourself:
235
+ body = client.creators.get("new.creator", wait=False)
236
+ if body.get("status") in ("resolving", "saturated"):
237
+ ... # ask again after body["retryAfterSeconds"]
238
+ ```
239
+
240
+ `live.refresh` (202 queued) and `exports.create` (201 ready or 202 pending) return their body
241
+ as is; use `exports.wait_until_ready(job_id, timeout=300, poll_interval=2)` for exports.
242
+
243
+ ## Pagination
244
+
245
+ Cursor lists return `data.nextCursor` (null at the end) and take `cursor` + `limit`. Each has an
246
+ `iter_*` generator that yields whole pages and follows the cursor for you:
247
+
248
+ ```python
249
+ for page in client.live.iter_sessions(creator_unique_id="linh.live", limit=100):
250
+ for session in page["data"]["items"]:
251
+ print(session["startedAt"], session["totalGiftDiamonds"])
252
+ ```
253
+
254
+ | Generator | Items under |
255
+ |---|---|
256
+ | `rankings.iter_history(board, ...)` | `data.periods` |
257
+ | `creators.iter_followers(uid, ...)` / `creators.iter_following(uid, ...)` | `data.entries` |
258
+ | `videos.iter_comments(video_id, ...)` | `data.comments` |
259
+ | `live.iter_sessions(...)` | `data.items` |
260
+ | `live.iter_performance(uid, ...)` | `data.items` |
261
+
262
+ Pages are fetched lazily, one request per page; pass `cursor=` to resume.
263
+
264
+ ## Webhooks
265
+
266
+ Alert webhooks carry `x-toktokdata-timestamp` and
267
+ `x-toktokdata-signature: sha256=<hex HMAC-SHA256(secret, "<timestamp>.<raw body>")>`.
268
+ `verify_webhook` checks the signature in constant time, rejects timestamps more than
269
+ `tolerance_seconds` (300) away from now, and returns the parsed payload. Always pass the
270
+ **raw** request body, never re-serialised JSON.
271
+
272
+ Flask:
273
+
274
+ ```python
275
+ import os
276
+ from flask import Flask, abort, request
277
+ from toktokdata import WebhookVerificationError, verify_webhook
278
+
279
+ app = Flask(__name__)
280
+ SECRET = os.environ["TOKTOKDATA_WEBHOOK_SECRET"]
281
+
282
+
283
+ @app.post("/hooks/toktokdata")
284
+ def toktokdata_hook():
285
+ try:
286
+ payload = verify_webhook(request.get_data(), request.headers, SECRET)
287
+ except WebhookVerificationError:
288
+ abort(400)
289
+ print(payload["rule"]["name"], payload["event"])
290
+ return "", 204
291
+ ```
292
+
293
+ FastAPI:
294
+
295
+ ```python
296
+ import os
297
+ from fastapi import FastAPI, HTTPException, Request, Response
298
+ from toktokdata import WebhookVerificationError, verify_webhook
299
+
300
+ app = FastAPI()
301
+ SECRET = os.environ["TOKTOKDATA_WEBHOOK_SECRET"]
302
+
303
+
304
+ @app.post("/hooks/toktokdata")
305
+ async def toktokdata_hook(request: Request) -> Response:
306
+ raw = await request.body()
307
+ try:
308
+ payload = verify_webhook(raw, request.headers, SECRET)
309
+ except WebhookVerificationError as err:
310
+ raise HTTPException(status_code=400, detail=err.code)
311
+ print(payload["rule"]["name"], payload["event"])
312
+ return Response(status_code=204)
313
+ ```
314
+
315
+ `sign_webhook(secret, timestamp, raw_body)` builds the header value, handy for testing your
316
+ handler.
317
+
318
+ ## Rate-limit info
319
+
320
+ `client.last_rate_limit` holds the `X-RateLimit-*` headers of the last response that carried
321
+ them (or `None` before the first call):
322
+
323
+ ```python
324
+ client.rankings.regions()
325
+ rl = client.last_rate_limit
326
+ if rl is not None:
327
+ print(rl.limit, rl.remaining) # per second
328
+ print(rl.minute_limit, rl.minute_remaining) # per minute
329
+ print(rl.daily_limit, rl.daily_remaining) # per day (None when the plan has no cap)
330
+ ```
331
+
332
+ ## Custom transport and testing
333
+
334
+ The HTTP layer sits behind a small `toktokdata.Transport` protocol (`request(method, url, *,
335
+ headers, body, timeout) -> TransportResponse` and `close()`). Pass your own with
336
+ `TokTokData(transport=...)` to add a proxy, logging or a fake for your tests; the default is
337
+ `toktokdata.UrllibTransport`.
338
+
339
+ ## Roadmap
340
+
341
+ - An async client (`AsyncTokTokData`) is planned; v0.1 is synchronous only. In async code, call
342
+ the client through `asyncio.to_thread(...)` for now.
343
+
344
+ ## Development
345
+
346
+ ```bash
347
+ pip install -e ".[dev]"
348
+ ruff check . && mypy --strict src && pytest
349
+ ```
350
+
351
+ The tests run offline against a fake transport and never call the real API.
352
+
353
+ ## License
354
+
355
+ MIT