toktokdata (Python)
Official Python client for the toktokdata.live API: TikTok LIVE rankings, creators, gifters, agencies, LIVE sessions, trends, alerts and exports.
- Python 3.10+, no runtime dependencies (standard library
urllibonly), fully typed (py.typed). - Auth, retries with
Retry-After, waiting for data that is still being collected (202), cursor pagination, typed errors, rate-limit info and a webhook signature helper.
API docs: https://toktokdata.live/docs · Reference: https://toktokdata.live/docs/reference
Install
pip install toktokdata
Quickstart
Create a key at https://toktokdata.live (Settings → API keys) and keep it in the environment:
export TOKTOKDATA_API_KEY=ttk_live_...
from toktokdata import TokTokData
with TokTokData() as client: # reads TOKTOKDATA_API_KEY
board = client.rankings.official("hourly", region="VN", limit=10)
for entry in board["data"]["board"]["entries"]:
print(entry["rank"], entry["uniqueId"], entry["score"])
Every method returns the parsed JSON body unchanged, as a plain dict. Reads look like
{"data": ..., "provenance": {...}}; exports and alert rules are flat objects. Field names are
the API's (camelCase); method and argument names are snake_case.
Configuration
client = TokTokData(
api_key="ttk_live_...", # default: TOKTOKDATA_API_KEY (required, checked here)
base_url="https://api.toktokdata.live", # default: TOKTOKDATA_BASE_URL or this URL
timeout=30.0, # seconds per HTTP request
max_retries=2, # retries after the first attempt
pending_timeout=180.0, # how long 202-aware methods wait (keyword-only)
)
The client never logs or prints the key (repr(client) masks it). Call client.close() or
use it as a context manager.
One example per namespace
# rankings: official boards (daily, hourly, popular_live, gaming_*, shopping_*, league_a1..d5)
client.rankings.official("daily", region="VN", period="current", live_only=True)
client.rankings.regions()
client.rankings.history("daily", region="VN", limit=24)
client.rankings.day_bars(region="VN", board="daily", days=30)
client.rankings.masked("<maskedRef from a board entry>")
# creators: uid is a handle (a leading "@" is stripped) or a numeric TikTok user id
client.creators.search(q="linh", limit=20)
client.creators.get("linh.live") # waits on 202 while TikTok is read
client.creators.analysis("linh.live")
client.creators.changes("linh.live", limit=50)
client.creators.followers("linh.live", limit=100)
client.creators.following("linh.live")
client.creators.gifters("linh.live", window="30d")
client.creators.insights("linh.live")
client.creators.videos("linh.live")
# agencies
client.agencies.list(region="VN", public_only=True, sort="revenue", limit=50, offset=0)
client.agencies.get("<agency id>")
client.agencies.stats(region="VN") # size and revenue bands over the directory
# insights
client.insights.best_time(region="VN")
client.insights.presence(region="VN", hours=48)
# videos
client.videos.get("7300000000000000000")
client.videos.comments("7300000000000000000", limit=50)
# trends, gifts, gifters
client.trends.list(region="US", type="hashtag")
client.trends.get("hashtag", "SEAGames31", region="VN") # 90-day history, sample videos
client.gifts.list(q="rose", min_coins=1, max_coins=100, sort="coins")
client.gifters.list(window="7d", segment="whale", region="VN")
client.gifters.get("6987001122334455667", window="30d") # user id or handle
# live
client.live.sessions(creator_unique_id="linh.live", limit=50)
client.live.sessions(scope="7d", status="ended", min_diamonds=1000, sort="diamonds", order="desc")
client.live.sessions(scope="range", from_="2026-11-01", to="2026-11-07", q="linh") # local days
by_creator = client.live.creators(scope="30d", sort="sessions") # LIVE history by creator
for row in by_creator["data"]["items"]:
print(row["handle"], row["isLive"], row["sessions"], row["liveSeconds"], row["diamonds"])
client.live.session("<session id>")
client.live.timeline("<session id>")
client.live.compare(["<session id>", "<session id>"]) # 2 to 4 ids
client.live.performance("linh.live")
client.live.refresh("linh.live") # 202 {"queued": true, "jobId": ...}; free, 10 a minute
client.live.playback("linh.live") # live:stream; 1,250 credits per new lookup
chat = client.live.comments("linh.live")
newer = client.live.comments("linh.live", after=chat["cursor"])
# live: the watchlist board and a followed creator's LIVE page
client.live.board(scope="today", roster_status="active")
client.live.creator("linh.live", scope="today") # GET /v1/creators/{uid}/live
client.live.battles("linh.live", scope="7d") # PK battles: current, list, record
client.live.battle("linh.live", "<battle id>") # score timeline, lead changes, donors
client.live.rivals("linh.live") # PK opponents (API default scope 30d)
client.live.gifter_gifts("linh.live", "<gifter user id>", scope="30d") # paged
client.live.gift_senders("linh.live", "<gift id>", from_="2026-11-01", to="2026-11-02")
# alerts
created = client.alerts.create_rule(
{
"name": "Whale gifts",
"scope": "watchlist",
"eventTypes": ["gift", "envelope"],
"minDiamondCount": 1000,
"channels": [{"channelType": "webhook", "target": "https://example.com/hooks/toktokdata"}],
}
)
rule_id = created["rule"]["id"] # created["webhookSecrets"]: signing secrets
client.alerts.update_rule(rule_id, {"enabled": False})
client.alerts.test_rule(rule_id)
client.alerts.list_rules()
client.alerts.fires(rule_id=rule_id, limit=20)
client.alerts.deliveries(status="failed", since="2026-11-01T00:00:00Z")
client.alerts.stats()
client.alerts.delete_rule(rule_id) # returns None (204)
# exports: `export` plus the dataset's read scope (rank:read here; trends needs trend:read)
job = client.exports.create(dataset="rankings", format="csv", board="daily", region="VN")
job = client.exports.wait_until_ready(job["id"]) # no-op when it is already ready
if job["status"] == "ready":
open(job["filename"], "wb").write(client.exports.download(job["id"]))
client.exports.list()
# account
client.account.entitlements()
client.account.usage(limit=50)
live.sessions and live.creators share the history filters: scope (1h, today, 7d, 30d,
all, or range with from_ + to: local days YYYY-MM-DD or dates of the workspace time zone,
both included, or ISO 8601 instants / datetimes, to excluded; no scope: the whole history
window), creator_unique_id, q (part of a handle), status (live or ended), min_duration
(seconds), min_diamonds, sort and order. Sessions sort by started (default), duration,
diamonds, peak or gifts; creators by diamonds (default), duration, sessions, peak,
gifts or started (the last session).
Exports need export plus the scope that reads the same data: live:read for live_sessions,
rank:read for rankings (plus shop:read for a shopping board), gifter:read for gifters (Pro
plan), trend:read for trends. Without it the call raises 403 insufficient_scope and
err.required_scope names the missing scope.
live.playback (live:stream) returns a signed, expiring HLS/FLV URL your player loads straight from
TikTok's CDN. A lookup that makes TikTok resolve the room costs live-playback (1,250 credits),
whatever it finds; an answer from a recent lookup of the same room (cached: true, the poll after a
202) is a cached read. A workspace starts at most 2 / 5 / 10 / 20 new lookups a minute (Free /
Starter / Pro / Agency), API keys and dashboard together; past that it answers
429 live_playback_limit_exceeded with Retry-After. Check whether the creator is live first
(live.creator). live.refresh is free and limited to 10 requests a minute per user.
Type hints list the accepted enum values (for example period: "current" | "history"), and
toktokdata.AlertRuleInput describes the alert rule body (event types include
diamond_spike and trend_new). Any route can also be called
directly with client.request("GET", "/v1/...", query={...}).
Time ranges (scope, from_, to)
live.creator, live.battles, live.rivals, live.gifter_gifts and live.gift_senders
take a scope ("live", "1h", "today", "7d", "30d", "all") or a custom range.
from is a Python keyword, so the start of the range is the argument from_; it is sent
as the query parameter from. to keeps its name. Both take an ISO 8601 string or a
datetime (sent with isoformat()), and the API needs both together.
import datetime as dt
utc = dt.timezone.utc
client.live.creator(
"linh.live",
from_=dt.datetime(2026, 11, 1, 12, tzinfo=utc),
to=dt.datetime(2026, 11, 1, 18, tzinfo=utc),
)
Plan limits
Plans differ in how far back they see and which tables they show in full. Both come back as data, not errors, so there is nothing to retry:
- Lists are clamped to the plan's history window (Free 7 days, Starter 90, Pro 180, Agency unlimited).
- A table reserved for a higher plan returns its first rows plus a
teaserblock{"rows", "total", "requiredTier"}(typed astoktokdata.Teaser); it isNonewhen the plan sees everything.
page = client.live.gift_senders("linh.live", "5655")
teaser = page["data"].get("teaser")
if teaser:
print(f"showing {teaser['rows']} of {teaser['total']}; {teaser['requiredTier']} shows all")
Reading one record by id that is older than the window (for example live.session) raises a
403 with code history_window_exceeded; see is_plan_limit below.
Errors
Every failed call raises toktokdata.TokTokDataError:
from toktokdata import TokTokDataError
try:
client.creators.get("linh.live")
except TokTokDataError as err:
print(err.status, err.code, err.message, err.request_id)
if err.is_payment_required: # 402 credit_cap_exceeded
print("credits reset at", err.details.get("resetAt"))
elif err.is_rate_limited: # 429 (incl. daily_quota_exceeded)
print("retry in", err.retry_after, "s")
elif err.is_plan_limit: # 403 module_not_entitled / history_window_exceeded
print("needs plan", err.details.get("requiredTier"))
elif err.is_forbidden: # any other 403, e.g. insufficient_scope (key lacks a scope)
print("missing scope", err.required_scope)
elif err.is_unauthorized: # 401, incl. account_suspended / account_deleted
...
elif err.is_not_found: # 404
...
| Field | Meaning |
|---|---|
status |
HTTP status (0 when no response arrived: code is network_error or timeout) |
code |
Machine-readable code from the envelope; http_error when the body was not JSON |
message |
Human-readable message |
request_id |
Quote it to support |
retryable |
The API's hint whether a retry may succeed |
retry_after |
Seconds from the Retry-After header, or None |
required_scope |
On insufficient_scope: the scope the key needs (rank:read, ...), else None |
details |
The whole error envelope (for example resetAt, historyWindowDays, requiredTier, requiredScope) |
| Helper | True for |
|---|---|
is_rate_limited |
429 (request_interval_exceeded, per second, per minute, daily_quota_exceeded or live_playback_limit_exceeded) |
is_payment_required |
402 credit_cap_exceeded |
is_forbidden |
every 403: insufficient_scope, module_not_entitled, history_window_exceeded |
is_plan_limit |
403 with module_not_entitled or history_window_exceeded: upgrade the plan, a retry does not help. history_window_exceeded carries historyWindowDays and requiredTier |
is_unauthorized |
every 401: missing, unknown or revoked key, account_suspended, account_deleted |
is_not_found |
404 |
PendingTimeoutError (a subclass) is raised when a 202 read or an export is still not ready
after the wait; WebhookVerificationError (a subclass) by verify_webhook.
Retries
The client retries up to max_retries times (default 2):
429rate limits, waitingRetry-Afterseconds (capped at 60 s). A429with codedaily_quota_exceededis not retried: the quota resets at midnight UTC.5xxanswers whose envelope saysretryable: true(or that have no envelope), GET only.- Network errors and timeouts, GET only.
Free, Starter and Pro also allow only one request every 30, 15 or 7 seconds per workspace (all its keys together; Agency has no gap): a request sooner answers 429 request_interval_exceeded with Retry-After (the seconds left) and X-RateLimit-Interval. With the default
max_retries a second call inside the gap waits up to 30 s and then succeeds.
Without Retry-After it backs off 0.5 s, 1 s, 2 s ... with jitter. 402 and other 4xx
are never retried, and a POST/PATCH/DELETE is not retried once it may have reached the server.
Waiting for fresh data (202)
creators.get, creators.followers, creators.following, videos.comments and
live.playback may answer 202 ({"status": "resolving" | "saturated", "jobId", "retryAfterSeconds"}) while toktokdata.live reads TikTok. These methods wait
retryAfterSeconds (clamped to 1-120 s) and ask again until the data is there, for up to
pending_timeout seconds (180 by default), then raise PendingTimeoutError. A 202 is never
billed beyond a cached read.
from toktokdata import PendingTimeoutError
try:
profile = client.creators.get("new.creator")
except PendingTimeoutError as err:
print("still resolving, job", err.job_id)
# Or handle it yourself:
body = client.creators.get("new.creator", wait=False)
if body.get("status") in ("resolving", "saturated"):
... # ask again after body["retryAfterSeconds"]
live.refresh (202 queued) and exports.create (201 ready or 202 pending) return their body
as is; use exports.wait_until_ready(job_id, timeout=300, poll_interval=2) for exports.
Pagination
Cursor lists return data.nextCursor (null at the end) and take cursor + limit. Each has an
iter_* generator that yields whole pages and follows the cursor for you:
for page in client.live.iter_sessions(creator_unique_id="linh.live", limit=100):
for session in page["data"]["items"]:
print(session["startedAt"], session["totalGiftDiamonds"])
| Generator | Items under |
|---|---|
rankings.iter_history(board, ...) |
data.periods |
creators.iter_followers(uid, ...) / creators.iter_following(uid, ...) |
data.entries |
videos.iter_comments(video_id, ...) |
data.comments |
live.iter_sessions(...) |
data.items |
live.iter_performance(uid, ...) |
data.items |
live.iter_gifter_gifts(uid, gifter_id, ...) |
data.items |
live.iter_gift_senders(uid, gift_id, ...) |
data.items |
Pages are fetched lazily, one request per page; pass cursor= to resume.
Webhooks
Alert webhooks carry x-toktokdata-timestamp and
x-toktokdata-signature: sha256=<hex HMAC-SHA256(secret, "<timestamp>.<raw body>")>.
verify_webhook checks the signature in constant time, rejects timestamps more than
tolerance_seconds (300) away from now, and returns the parsed payload. Always pass the
raw request body, never re-serialised JSON.
Flask:
import os
from flask import Flask, abort, request
from toktokdata import WebhookVerificationError, verify_webhook
app = Flask(__name__)
SECRET = os.environ["TOKTOKDATA_WEBHOOK_SECRET"]
@app.post("/hooks/toktokdata")
def toktokdata_hook():
try:
payload = verify_webhook(request.get_data(), request.headers, SECRET)
except WebhookVerificationError:
abort(400)
print(payload["rule"]["name"], payload["event"])
return "", 204
FastAPI:
import os
from fastapi import FastAPI, HTTPException, Request, Response
from toktokdata import WebhookVerificationError, verify_webhook
app = FastAPI()
SECRET = os.environ["TOKTOKDATA_WEBHOOK_SECRET"]
@app.post("/hooks/toktokdata")
async def toktokdata_hook(request: Request) -> Response:
raw = await request.body()
try:
payload = verify_webhook(raw, request.headers, SECRET)
except WebhookVerificationError as err:
raise HTTPException(status_code=400, detail=err.code)
print(payload["rule"]["name"], payload["event"])
return Response(status_code=204)
sign_webhook(secret, timestamp, raw_body) builds the header value, handy for testing your
handler.
Rate-limit info
client.last_rate_limit holds the X-RateLimit-* headers of the last response that carried
them (or None before the first call):
client.rankings.regions()
rl = client.last_rate_limit
if rl is not None:
print(rl.limit, rl.remaining) # per second
print(rl.minute_limit, rl.minute_remaining) # per minute
print(rl.daily_limit, rl.daily_remaining) # per day (None when the plan has no cap)
Custom transport and testing
The HTTP layer sits behind a small toktokdata.Transport protocol (request(method, url, *, headers, body, timeout) -> TransportResponse and close()). Pass your own with
TokTokData(transport=...) to add a proxy, logging or a fake for your tests; the default is
toktokdata.UrllibTransport.
Roadmap
- An async client (
AsyncTokTokData) is planned; v0.2 is synchronous only. In async code, call the client throughasyncio.to_thread(...)for now.
Development
pip install -e ".[dev]"
ruff check . && mypy --strict src && pytest
The tests run offline against a fake transport and never call the real API.
License
MIT
Metadata
Release files for toktokdata 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| toktokdata-0.3.0.tar.gz | 42.4 kB | With provenance | Details for toktokdata-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| toktokdata-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for toktokdata-0.3.0-py3-none-any.whl |
Total release size: 78.3 kB
Release files / toktokdata-0.3.0.tar.gz
| Download URL | toktokdata-0.3.0.tar.gz |
|---|---|
| Size | 42.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
54603cc72e0e702c567e36bf54deef84562ea507e68c2cab1da97229adeb8b08
|
|
BLAKE2b-256 checksum How to use checksums |
237bd6a9dc67777b9b6bfa74d763fdfcd2003a30f33c06719935b76625a0bc3d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logRelease files / toktokdata-0.3.0-py3-none-any.whl
| Download URL | toktokdata-0.3.0-py3-none-any.whl |
|---|---|
| Size | 35.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5c1d400de09b3c1aa230934624c3e8a16b65cd7be1b4d8be6425d66b6a60b477
|
|
BLAKE2b-256 checksum How to use checksums |
afe0c6299b7be8f64a187fc09a742b9ab1be56f6ef125a95db0a23e56229b54a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logSecurity for toktokdata 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for toktokdata-0.3.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.