Metadata-Version: 2.5
Name: toktokdata
Version: 0.3.0
Summary: Official Python SDK for the toktokdata.live API (TikTok LIVE rankings, creators, gifters, LIVE sessions, alerts, exports).
Project-URL: Documentation, https://toktokdata.live/docs
Project-URL: Homepage, https://toktokdata.live
Project-URL: Issues, https://github.com/MKK-Platform/toktokdata-sdks/issues
Project-URL: Source, https://github.com/MKK-Platform/toktokdata-sdks/tree/main/python
Author: toktokdata.live
License-Expression: MIT
License-File: LICENSE
Keywords: api,live,rankings,sdk,tiktok,toktokdata
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# toktokdata (Python)

Official Python client for the [toktokdata.live](https://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

```bash
pip install toktokdata
```

## Quickstart

Create a key at <https://toktokdata.live> (**Settings → API keys**) and keep it in the environment:

```bash
export TOKTOKDATA_API_KEY=ttk_live_...
```

```python
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

```python
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

```python
# 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 `date`s of the workspace time zone,
both included, or ISO 8601 instants / `datetime`s, `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.

```python
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 `teaser` block
  `{"rows", "total", "requiredTier"}` (typed as `toktokdata.Teaser`); it is `None` when the
  plan sees everything.

```python
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`:

```python
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):

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

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.

```python
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:

```python
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:

```python
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:

```python
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):

```python
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

```bash
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
