Social Media Scraper
All tutorials
TikTokPython

Use TikTok Video Comments API with Python

Collect public comments on a TikTok video to study audience questions and reactions.

SocialScraper Engineering

Developer experience team

What you will build

Build a Python workflow for TikTok Video Comments API. Your first request identifies the target using url, then writes the returned comment data to disk with its request metadata.

Collect TikTok feedback for social listening, product questions or content analysis. Your application can classify the text and group repeated themes while retaining comment IDs for deduplication.

GET/v1/tiktok/commentsOpen endpoint reference

Before you begin

Use Python 3.10 or newer, a terminal and a customer API key. The script uses urllib, json and pathlib from the standard library. Save the Python file and its JSON input file in the same directory.

Python
python3 --version
Create an API key

Configure your API key

Replace YOUR_API_KEY privately with your customer key. Keep the variable in the environment used by the script; the source code reads it without storing the key in the file.

macOS / Linux
export SOCIALSCRAPER_API_KEY="YOUR_API_KEY"
Windows PowerShell
Windows PowerShell
$env:SOCIALSCRAPER_API_KEY="YOUR_API_KEY"

Prepare the endpoint inputs

For TikTok Video Comments API, send GET /v1/tiktok/comments. Start with the input object below, replace the target values and follow the identifier rules. Optional filters can be added using the parameter table.

tiktok.comments.input.json
{
  "url": "https://www.tiktok.com/example"
}
Download input JSON
ParameterTypeRequirementUsage
urlstringRequiredPublic tiktok content or profile URL to retrieve. Paste the complete URL, including https://.
trimbooleanOptionalRequest the supplier’s trimmed response representation.
cursornumberOptionalContinuation value from the preceding response. Keep the other search or target parameters unchanged when loading the next page.20

Complete implementation

This script calls only /v1/tiktok/comments. It reads the API key from your environment, sends the documented GET request, checks HTTP errors and writes each completed response to result.json. Start with one page while integrating.

tiktok.comments.py
#!/usr/bin/env python3
"""TikTok Video Comments API: GET /v1/tiktok/comments"""
import argparse
import json
import os
import uuid
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError

DEFAULT_INPUT = json.loads("{\"url\":\"https://www.tiktok.com/example\"}")
parser = argparse.ArgumentParser(description="TikTok Video Comments API")
parser.add_argument("--input", type=Path, help="JSON file containing endpoint inputs")
parser.add_argument("--request-key", help="Original key for one identical retry")
parser.add_argument("--output", type=Path, default=Path("result.json"))
parser.add_argument("--pages", type=int, default=1, help="Maximum number of pages, 1 to 20")
args = parser.parse_args()
if not 1 <= args.pages <= 20:
    parser.error("--pages must be between 1 and 20")
if args.request_key and args.pages != 1:
    parser.error("--request-key requires --pages 1")
key = os.environ["SOCIALSCRAPER_API_KEY"]
base = os.environ.get("SOCIALSCRAPER_BASE_URL", "https://socialmediascraper.org").rstrip("/")
inputs = json.loads(args.input.read_text(encoding="utf-8")) if args.input else DEFAULT_INPUT.copy()
if not isinstance(inputs, dict):
    parser.error("--input must contain a JSON object")
responses = []
for page in range(args.pages):
    request_key = args.request_key or str(uuid.uuid4())
    headers = {"x-api-key": key, "Idempotency-Key": request_key}
    query = {name: (str(value).lower() if isinstance(value, bool) else value)
             for name, value in inputs.items()}
    request = Request(base + "/v1/tiktok/comments" + "?" + urlencode(query), headers=headers)
    try:
        with urlopen(request, timeout=45) as response:
            result = json.load(response)
    except HTTPError as error:
        detail = error.read().decode("utf-8", errors="replace")
        retry_after = error.headers.get("Retry-After", "")
        raise RuntimeError(f"HTTP {error.code}; request key={request_key}; Retry-After={retry_after}; {detail}") from error
    except (URLError, TimeoutError) as error:
        raise RuntimeError(f"Uncertain request outcome; retain request key={request_key}; {error}") from error
    responses.append(result)
    args.output.write_text(json.dumps({"operation": "tiktok.comments", "requests": responses},
                                     ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"page": page + 1, "request_id": result["request_id"]}))
    cursor = result["data"].get("cursor")
    if cursor is None or cursor == "":
        break
    inputs = {**inputs, "cursor": cursor}
print(f"Saved {len(responses)} request response(s) to {args.output}")
Download source code

Run the script

Replace the example values in the input file with your target, then run the command from the directory containing both downloaded files. Use --output to choose a different result filename.

Python
python3 tiktok.comments.py --input tiktok.comments.input.json --output result.json --pages 1

Read and use the result

The saved file has an operation label and a requests array. Each requests entry contains the original request_id, data and meta envelope. The JSON below shows one response; use the field table to choose what your application stores.

Response JSON
{
  "request_id": "example-request-id",
  "data": {
    "platform": "tiktok",
    "resource": "comments",
    "items": [
      {
        "id": "123456789",
        "position": 0,
        "url": "https://example.com/public-content",
        "title": "Example public content",
        "text": "Example public content",
        "published_at": null,
        "author": {
          "id": "123456789",
          "handle": "example",
          "display_name": "Example creator"
        },
        "metrics": {
          "views": null,
          "likes": 12,
          "comments": null,
          "shares": null
        }
      }
    ],
    "cursor": null
  },
  "meta": {
    "platform": "tiktok",
    "fetched_at": "2026-11-28T00:00:00.000Z",
    "cached": false,
    "schema_version": "2026-11-23.2",
    "route_version": 1,
    "billing": {
      "capability": "tiktok.comments",
      "version": "2026-11-23.retail-1",
      "currency": "USD",
      "unit_scale": 1000000000,
      "amount_units": 2444000,
      "amount_usd": "0.002444000",
      "billing_basis": "request"
    }
  }
}

Fields used by this workflow

FieldHow it is used
data.platformSource platform identifier.
data.resourceOperation resource identifier.
data.itemsRecords in the returned page or bounded result set.
data.items[].idSource identity preserved as text.
data.items[].positionZero-based position within this returned set.
data.items[].urlPublic source URL for this record.
data.items[].titleTitle or display label associated with the record.
data.items[].textContent text, biography or transcript text associated with this record.
data.items[].published_atPublication value supplied by the source.
data.items[].authorIdentity fields for the author or account represented by the record.
data.items[].author.idSource identity preserved as text.
data.items[].author.handlePublic account username or handle.
data.items[].author.display_nameAccount or creator display name.
data.items[].metricsAvailable source metrics grouped by measurement.
data.items[].metrics.viewsSource-reported views measurement when present.
data.items[].metrics.likesSource-reported likes measurement when present.
data.items[].metrics.commentsSource-reported comments measurement when present.
data.items[].metrics.sharesSource-reported shares measurement when present.
data.cursorContinuation value for the next request; preserve its returned representation.

Keep comment IDs, author fields and source references when organizing a discussion. Use returned parent or reply context where present to preserve conversation relationships in your analysis.

Plan requests and pagination

This endpoint continues through cursor. Keep the target and filters from the first request, then pass data.cursor with the documented field name. The script uses the first continuation field shown here and stops when the cursor is empty.

Bounded multi-page collection
python3 tiktok.comments.py --input tiktok.comments.input.json --output result.json --pages 3
DecisionFirst requestNext page or new lookup
Target inputChoose one account or public content URL.Keep the target for pagination; change it for a new lookup.
Request identityGenerate one unique Idempotency-Key.Use a new key for a new page. Reuse the old key only for an identical retry.
Result handlingInspect data and keep request_id.Append records and preserve source IDs and links.

To retry one identical request, rerun with the original inputs and --request-key ORIGINAL_KEY, keeping --pages 1. For an uncertain result, check the saved request status first. A new page or independent lookup needs a new request identity.

Request costs

The standard request price for this operation is $0.002444 USD. Budget up to $0.007332 USD for a three-page run at this rate. Inspect response meta.billing for the applied price; optional configurations should be reviewed against the endpoint pricing.

Inspect meta.billing in the response for the price applied to your request, and preserve request_id for status checks.

Rate limits and concurrency

Troubleshooting

HTTP responseNext action
400Review the target URL, parameter types and identifier-combination rules.
401Check SOCIALSCRAPER_API_KEY and the x-api-key header.
402Check your USD balance and the selected operation’s price.
429Read Retry-After and your current limits before retrying the same request.

A new page is a new logical request. If the same request must be retried, keep its original Idempotency-Key and identical inputs. When the outcome is uncertain, query GET /v1/requests/:id before starting a replacement. The examples stop on an error rather than silently creating another request.

Handle errors and retries

Common questions

Which inputs does this TikTok Video Comments API example use?

The generated input file selects url. Review the table and combination rules before adding another identifier or optional filter. The Python script accepts a JSON object through --input.

How should I use the returned data?

Keep comment IDs, author fields and source references when organizing a discussion. Use returned parent or reply context where present to preserve conversation relationships in your analysis.

Can I rerun a failed request?

Read the reported HTTP status, request ID and request key. For a confirmed identical retry, provide that key through --request-key and keep the input unchanged. Follow Retry-After for 429 responses and check saved status for uncertain outcomes.

Can an AI coding agent use this tutorial?

Yes. Copy the tutorial or give the agent its Markdown URL. Ask it to configure the environment, inspect the endpoint contract and run the script with your selected input.