Skip to main content

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 urllib only), 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.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": ...}
client.live.playback("linh.live")  # needs the live:stream scope
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
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)

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 365, Enterprise unlimited).
  • A table reserved for a higher plan returns its first rows plus a teaser block {"rows", "total", "requiredTier"} (typed as toktokdata.Teaser); it is None when 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)
        ...
    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
details The whole error envelope (for example resetAt, historyWindowDays, requiredTier)
Helper True for
is_rate_limited 429 (per second, per minute, or daily_quota_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):

  • 429 rate limits, waiting Retry-After seconds (capped at 60 s). A 429 with code daily_quota_exceeded is not retried: the quota resets at midnight UTC.
  • 5xx answers whose envelope says retryable: true (or that have no envelope), GET only.
  • Network errors and timeouts, GET only.

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 through asyncio.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.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for toktokdata 0.2.0
File Size Uploaded Provenance Actions
toktokdata-0.2.0.tar.gz 37.9 kB With provenance Details for toktokdata-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for toktokdata 0.2.0
File Interpreter ABI Platform Actions
toktokdata-0.2.0-py3-none-any.whl Python 3 none any Details for toktokdata-0.2.0-py3-none-any.whl

Total release size: 70.6 kB

Release files / toktokdata-0.2.0.tar.gz

Download URL toktokdata-0.2.0.tar.gz
Size 37.9 kB
Tags Source
SHA-256 checksum
How to use checksums
781a03425826c59060b4fd14cd573ee77fd2eaee59c6cdfa001206edd88650b3
BLAKE2b-256 checksum
How to use checksums
c3bb0d0517bcb0e4b581f6dee949ec39e88f2ac1bfd31ab5e9212cac863beccb
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 29, 2026.

Transparency log

Release files / toktokdata-0.2.0-py3-none-any.whl

Download URL toktokdata-0.2.0-py3-none-any.whl
Size 32.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e7ab720edf62063263a74e6c245d1569bdc96a965d8d65a5f15d900d35c142b9
BLAKE2b-256 checksum
How to use checksums
537cfbe8607c988765b6f3f4ee2c841b0813662c8cd307b8cf03af88c47e7a40
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 29, 2026.

Transparency log

Security for toktokdata 0.2.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.

Select from 2 files

Attestation for toktokdata-0.2.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 29, 2026.

Transparency log

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page