TikTokAnswer

TikTok API get comments: every comment and reply to CSV

TikTok's comments API is for approved researchers only. Ours returns a public video's comments and replies at 2 credits a call: 2,513 rows from one video.

7 min read

Short answer

  • TikTok's only comment list is in the Research API, up to 100 comments a request, for approved researchers. Its FAQ says commercial users are not eligible.
  • ToolzerHub returns up to 50 comments a page at 2 credits, plus a replies route. has_more ends early: a NASA video showing 2,490 comments stopped at 283 top-level comments.
  • Stepping the cursor yourself got 1,556 comments and 957 replies from that video, and 116 rows against 112 shown on a smaller one.
On this page

TikTok's Research API has the only comment list, and it is for approved researchers. Our /v2/tiktok/app/video/comments returns a public video's comments by video ID, but its has_more flag turns false long before the end, so you step the cursor yourself. Done that way, a NASA video gave 2,513 rows against the 2,490 TikTok showed.

Does TikTok have a comments API?

Only for researchers. The Research API's Query Video Comments endpoint returns comment text, likes, reply counts and the parent comment ID, up to 100 per request, and can return fewer than you ask for. Its FAQ says creators, advertisers and commercial users are not eligible, and the scopes reference for ordinary apps lists no comment scope. Our Research API post covers who can apply. If you qualify, use it: it is TikTok's own route.

Get a video's comments with ToolzerHub

We make ToolzerHub. Our TikTok API returns comments for a public video by its ID, with one API key and no TikTok app. GET /v2/tiktok/app/video/comments takes aweme_id, cursor and count, returns 20 comments a page by default and up to 50 with count=50, with likes, reply counts and timestamps, and costs 2 credits a call either way. GET /v2/tiktok/app/video/comments/replies takes item_id (the video) and comment_id and pages a comment's replies.

The catch is the end of the list. On a NASA video showing 2,490 comments, following has_more and the returned cursor stopped after 17 pages and 283 top-level comments, while asking for later cursors still returned full pages. So the script asks for 50 a page, ignores has_more, adds 50 to the cursor each time, and stops after three empty pages in a row. It takes video IDs or full video URLs, not vm.tiktok.com short links, and keeps one row per comment ID because pages overlap.

python
import csv
import os
import sys
import time
from datetime import datetime, timezone

import requests

BASE = "https://api.toolzerhub.com/v2/tiktok/app/video"
HEADERS = {"x-api-key": os.environ.get("TOOLZERHUB_API_KEY", "")}
FIELDS = ["video_id", "comment_id", "reply_to", "posted_at", "likes", "replies", "text"]
PAGE = 50  # count=50 returns up to 50 comments for the same 2 credits
calls = 0


def cell(value):
    # Spreadsheets run text starting with = + - or @ as a formula; an apostrophe keeps it text.
    if isinstance(value, str) and value[:1] in ("=", "+", "-", "@", "\t"):
        return "'" + value
    return value


def get(path, params, tries=4):
    # 429 and 503 are retried; the wait comes from the error body or the Retry-After header.
    global calls
    for attempt in range(tries):
        r = requests.get(BASE + path, headers=HEADERS, params=params, timeout=90)
        calls += 1
        if r.status_code == 400:  # missing or empty ID: skip this video
            print("bad request:", str(r.json()["error"].get("message")).split("\n")[0])
            return None
        if r.status_code not in (429, 503) or attempt == tries - 1:
            if r.status_code >= 500:  # any 5xx, or a 503 past the retries: skip
                print(f"HTTP {r.status_code}, skipping:", r.text[:120].replace("\n", " "))
                return None
            r.raise_for_status()
            return r.json().get("data")
        try:
            wait = r.json()["error"]["details"]["retryAfter"]
        except (ValueError, KeyError, TypeError):
            wait = None
        try:
            wait = int(wait or r.headers.get("Retry-After") or 5 * (attempt + 1))
        except ValueError:
            wait = 5 * (attempt + 1)
        time.sleep(min(wait, 60))


def write(writer, video_id, c, seen, reply_to=""):
    if not c.get("cid") or c["cid"] in seen:  # pages overlap: keep one row per comment
        return False
    seen.add(c["cid"])
    writer.writerow({
        "video_id": video_id, "comment_id": c["cid"], "reply_to": reply_to,
        "posted_at": datetime.fromtimestamp(c["create_time"], timezone.utc).isoformat()
        if c.get("create_time") else "",
        "likes": c.get("digg_count"), "replies": c.get("reply_comment_total"),
        "text": cell((c.get("text") or "").replace("\r", " ").replace("\n", " ")),
    })
    return True


def export_video(writer, video_id, max_pages, with_replies):
    seen, cursor, pages, empty, total, parents = set(), 0, 0, 0, None, []
    status = "page cap reached"
    while pages < max_pages:
        data = get("/comments", {"aweme_id": video_id, "cursor": cursor, "count": PAGE})
        if data is None:
            status = "stopped early: failed page" if pages else "nothing returned"
            break
        pages += 1
        total = total or data.get("total")
        rows = data.get("comments") or []
        if not rows and not seen and not total:  # unknown or comment-free video
            status = "nothing returned"
            break
        for c in rows:
            if write(writer, video_id, c, seen) and int(c.get("reply_comment_total") or 0):
                parents.append(c["cid"])
        empty = 0 if rows else empty + 1
        if empty >= 3:
            status = "end"
            break
        # has_more can turn 0 long before the end, so step the cursor ourselves.
        cursor += PAGE
        time.sleep(0.3)
    top = len(seen)
    for parent in parents if with_replies else []:
        params = {"item_id": video_id, "comment_id": parent, "cursor": 0}
        while True:
            data = get("/comments/replies", params)
            rows = (data or {}).get("comments") or []
            new = [write(writer, video_id, c, seen, parent) for c in rows]
            nxt = (data or {}).get("cursor")
            done = not (data and data.get("has_more") and nxt)
            if done or nxt == params["cursor"] or not any(new):
                break  # also stops on a cursor that does not move or a page with nothing new
            params["cursor"] = nxt
            time.sleep(0.3)
    shown = f"; TikTok shows {total}" if total else ""
    print(f"{video_id}: {top} comments, {len(seen) - top} replies, {pages} pages "
          f"({status}{shown})")
    return len(seen)


def main(videos, max_pages="150", replies="no", out="tiktok_comments.csv"):
    total = 0
    with open(out, "w", newline="", encoding="utf-8-sig") as f:  # BOM: Excel reads emoji
        writer = csv.DictWriter(f, fieldnames=FIELDS)
        writer.writeheader()
        for v in [v.strip() for v in videos.split(",") if v.strip()]:
            video = v.split("?")[0].split("#")[0].rstrip("/").split("/")[-1]  # ID or full video URL
            total += export_video(writer, video, int(max_pages), replies == "yes")
    print(f"wrote {total} rows to {out} in {calls} calls")


if __name__ == "__main__":
    if len(sys.argv) < 2 or (len(sys.argv) > 3 and sys.argv[3] not in ("yes", "no")):
        sys.exit("usage: python tiktok_comments.py VIDEO_ID_OR_URL[,...] [max_pages] "
                 "[yes|no replies] [file.csv]")
    if not HEADERS["x-api-key"]:
        sys.exit("set TOOLZERHUB_API_KEY first")
    main(*sys.argv[1:])

Run the script

Pass video IDs or video URLs, a page cap and yes for replies:

bash
export TOOLZERHUB_API_KEY=your_key
python tiktok_comments.py "7691827402988686606, https://www.tiktok.com/@nasa/video/7679483952507276558?lang=en" 150 yes tiktok_comments.csv

It printed:

text
7691827402988686606: 68 comments, 48 replies, 5 pages (end; TikTok shows 112)
7679483952507276558: 1556 comments, 957 replies, 37 pages (end; TikTok shows 2490)
wrote 2629 rows to tiktok_comments.csv in 261 calls

It took 182 seconds: 42 comment-page calls and 219 replies calls.

What the cursor recovered

The table compares the comment count TikTok showed with what each method returned. The first results column follows has_more at 20 a page; the second steps the cursor at 50 a page.

Video Shown Following has_more Stepping, 50 a page
NatGeo, small 112 55 + 42 replies 68 + 48 replies
NASA 384 238 + 70 replies 276 + 70 replies
NatGeo 706 240 + 124 replies 421 + 134 replies
NASA, large 2,490 283 + 735 replies 1,556 + 957 replies

Following has_more ended after 16 or 17 pages on the three longer videos. Stepping the cursor recovered the rest on the large video and most of it on the others. Replies in the table are the counts the comments report, except for the small and large videos in the right column, which count replies actually fetched.

What it costs

A call costs 2 credits. The run above made 261 calls, 522 credits, for 2,629 rows, and replies are most of the calls. Without replies, the large video took 37 calls, 74 credits. The 100 free credits a month cover 50 calls; $19 buys 10,000 credits that never expire, and plans for higher volume cover more videos. Set your key and the first video is a CSV in under a minute.

For a few hundred comments from one video, a free Python script pages TikTok's own comment endpoint; see scraping TikTok with Python. For comments on Instagram, see getting Instagram comments. For a video's own stats and file link, see TikTok API get video. For comments on Douyin, TikTok's Chinese sister app, see the Douyin comments scraper.

We are not affiliated with TikTok or ByteDance.

Get this data from your own code

The TikTok API returns it as JSON with one x-api-key header. 100 free credits monthly.