# How to scrape TikTok using Python

https://jsonscraper.com/blog/how-to-scrape-tiktok-api

Author: Michael Johnson

Published: 2026-03-05T00:00:00+00:00

Updated: 2026-11-22T22:38:44+00:00

A practical implementation guide with no-watermark endpoint examples and high-volume workflow patterns.

Build a small TikTok data collector in Python using the paid jsonscraper API. You will fetch a public profile, search for videos, collect a creator feed or video comments, and save records as JSON and CSV. This uses API requests rather than browser automation.

 

The TikTok API map includes user, video, hashtag, location, music, trending, effect, and search classes. This allows one backend to support analytics, moderation, and enrichment workflows at the same time.

 

What you will build

 

- Python requests with query-based license_key auth.
- Reusable helper for TikTok route classes (video, search, user).
- Stable pagination strategy using cursor fields from API responses.

 

## TikTok API Demo

 

Choose one endpoint, pass parameters, run the request, inspect snippets, then review response + visual rendering side by side.

 

[Open Playground](https://jsonscraper.com/playground)

 

[Live demo](https://jsonscraper.com/playground)

 

## Fast start in Postman

 

Open the official TikTok collection, set license_key, and validate the first routes before coding.

 

Step 1

 

### Fork

 

Use IG or TikTok Postman collection as your workspace baseline.

   

Step 2

 

### Set key

 

Configure `license_key` once in an environment variable.

   

Step 3

 

### Automate

 

Export snippets or run AI-agent workflows on top of ready requests.

 

[Open Postman collection](https://www.postman.com/evelode/workspace/evelode/collection/24862082-d886cc87-4267-4e0c-b57a-2d083add50ad?action=share&creator=24862082) [Get Access](https://jsonscraper.com/services/tiktok-scraper-api/)

 

## All API requests

 

Full endpoint map from the collection. Expand each class and click any route to inspect parameters and sample responses.

 

Video Search User Hashtag Location Music Trending Effects Stories Playlists Live

 

Video (8 endpoints) 



   Search (9 endpoints) 



   User (15 endpoints) 



   Hashtag (3 endpoints) 



   Location (2 endpoints) 



   Music (3 endpoints) 



   Trending (2 endpoints) 



   Effects (3 endpoints) 



   Stories (2 endpoints) 



   Playlists (3 endpoints) 



   Live (4 endpoints)

 [View full endpoint list in Postman](https://www.postman.com/evelode/workspace/evelode/collection/24862082-d886cc87-4267-4e0c-b57a-2d083add50ad?action=share&creator=24862082)

 

## 1. Install Python dependencies and set your license key



Use Python 3.10 or later and install requests in a virtual environment. Get a license through the TikTok API product page; the free trial currently includes 2,000 requests. Keep the key in an environment variable and never commit it to your repository.

 

```
python3 -m venv .venv
# macOS / Linux
source .venv/bin/activate
# Windows PowerShell
# .venv\Scripts\Activate.ps1
python -m pip install requests
# macOS / Linux
export TIKTOK_LICENSE_KEY='YOUR_LICENSE_KEY'
# Windows PowerShell
# $env:TIKTOK_LICENSE_KEY = 'YOUR_LICENSE_KEY'
```

 [Download the complete Python example](https://jsonscraper.com/assets/docs/tiktok_scraper.py)

 

## 2. Run a bounded collection



Save the downloadable script as tiktok_scraper.py. Choose profile, search, feed or comments. Replace the example nickname, keyword or video ID with your target. The examples below limit each list to two pages; check your quota before increasing the limit.

 

### Public profile



```
python tiktok_scraper.py --mode profile --query therock --output profile
```

 

### Video keyword search



```
python tiktok_scraper.py --mode search --query coffee --pages 2 --output search
```

 

### Creator video feed



```
python tiktok_scraper.py --mode feed --query therock --pages 2 --output feed
```

 

### Video comments



```
python tiktok_scraper.py --mode comments --query 7141505394869898538 --pages 2 --output comments
```

 

## 3. Inspect the request and pagination logic



The complete script below uses the routes and cursor fields documented in the Postman collection. It validates both HTTP and API status, stops on missing or repeated cursors, deduplicates record IDs and writes JSON and CSV only after collection succeeds.



```
"""Bounded public-data collection with the jsonscraper TikTok API (Python 3.10+)."""

import argparse
import csv
import json
import os
from pathlib import Path

import requests

BASE_URL = "https://tiktok.evelode.com/tiktok-api"
ROUTES = {
    "profile": ("getUserInfo", "query", "user", None),
    "search": ("searchVideo", "keyword", "aweme_list", "cursor"),
    "feed": ("getUserFeed", "query", "aweme_list", "max_cursor"),
    "comments": ("getCommentsByID", "video_id", "comments", "cursor"),
}


class ApiError(RuntimeError):
    pass


def call(session, endpoint, key, params):
    try:
        response = session.get(
            f"{BASE_URL}/{endpoint}",
            params={**params, "license_key": key},
            timeout=(10, 45),
            allow_redirects=False,
        )
    except requests.RequestException:
        raise ApiError("Network request failed; check connectivity before retrying.") from None
    if response.status_code != 200:
        raise ApiError(f"HTTP {response.status_code}; check access, quota and Retry-After.")
    try:
        envelope = response.json()
    except ValueError:
        raise ApiError("The API did not return valid JSON.") from None
    if not isinstance(envelope, dict) or envelope.get("status") != "ok" or envelope.get("rate_limit_reached") is True:
        raise ApiError("API request failed; check the license and endpoint parameters.")
    payload = envelope.get("tiktok")
    if not isinstance(payload, dict) or payload.get("status_code", 0) != 0:
        raise ApiError("TikTok payload is unavailable or reports an error.")
    return payload


def collect(session, mode, query, key, pages=2, count=10):
    if mode not in ROUTES or not 1 <= pages <= 100 or not 1 <= count <= 30:
        raise ValueError("Use a supported mode, 1–100 pages and a count of 1–30.")
    endpoint, query_field, list_field, cursor_field = ROUTES[mode]
    params = {query_field: query}
    if cursor_field:
        params["count"] = count
    records, ids, cursors = [], set(), set()
    for _ in range(pages):
        payload = call(session, endpoint, key, params)
        items = payload.get(list_field)
        if mode == "profile":
            if not isinstance(items, dict):
                raise ApiError("Expected a public user object.")
            return [items]
        if not isinstance(items, list) or any(not isinstance(item, dict) for item in items):
            raise ApiError("Unexpected list payload; inspect the endpoint documentation.")
        for item in items:
            item_id = item.get("cid" if mode == "comments" else "aweme_id")
            if item_id is not None:
                item_id = str(item_id)
                if item_id in ids:
                    continue
                ids.add(item_id)
            records.append(item)
        if payload.get("has_more") not in (1, True, "1"):
            break
        cursor = payload.get(cursor_field)
        if cursor is None or cursor == "" or str(cursor) in cursors:
            raise ApiError("Pagination stopped: the next cursor is missing or repeated.")
        cursors.add(str(cursor))
        params[cursor_field] = cursor
    return records


def export(records, output):
    path = Path(output)
    path.with_suffix(".json").write_text(
        json.dumps(records, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    fields = sorted({field for record in records for field in record})
    with path.with_suffix(".csv").open("w", encoding="utf-8", newline="") as stream:
        writer = csv.DictWriter(stream, fieldnames=fields)
        if fields:
            writer.writeheader()
        for record in records:
            row = {}
            for field, value in record.items():
                cell = json.dumps(value, ensure_ascii=False) if isinstance(value, (dict, list)) else str(value) if value is not None else ""
                # Public captions/comments may be interpreted as spreadsheet formulas.
                row[field] = "'" + cell if cell.lstrip().startswith(("=", "+", "-", "@")) else cell
            writer.writerow(row)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--mode", choices=ROUTES, required=True)
    parser.add_argument("--query", required=True)
    parser.add_argument("--pages", type=int, default=2)
    parser.add_argument("--count", type=int, default=10)
    parser.add_argument("--output", default="tiktok")
    args = parser.parse_args()
    key = os.environ.get("TIKTOK_LICENSE_KEY", "").strip()
    if not key:
        parser.exit(1, "Set TIKTOK_LICENSE_KEY in your environment.\n")
    try:
        with requests.Session() as session:
            records = collect(session, args.mode, args.query, key, args.pages, args.count)
        export(records, args.output)
    except (ApiError, ValueError, OSError) as error:
        # Never print request exceptions: their URL can include the license key.
        message = str(error) if isinstance(error, (ApiError, ValueError)) else "Could not write output files."
        parser.exit(1, message + "\n")
    print(f"Saved {len(records)} records as JSON and CSV.")


if __name__ == "__main__":
    main()
```

 

## 4. Understand the exported files



The JSON file keeps complete returned records. The CSV file stores one record per row; nested objects and lists remain JSON strings inside their cells. IDs stay strings. These exports contain only the pages you requested, not a complete TikTok archive.



## 5. Handle errors without leaking your key



A timeout, invalid JSON, non-success HTTP response or API error stops the script with a short message that excludes the request URL and license key. It deliberately does not retry automatically: retries may consume additional quota. Check access and quota first; respect Retry-After when adding a retry policy for HTTP 429.



## Use the correct cursor for each endpoint



searchVideo reads aweme_list and sends cursor; getUserFeed reads aweme_list and sends max_cursor; getCommentsByID reads comments and sends cursor. Pass the returned value unchanged. Do not assume that a cursor is a page number or that count guarantees a full page.

 

## Choose the next step for your project

 

Use the endpoint map below for hashtag, music, replies and other workflows. Compare plans and alternatives before increasing collection volume. Store only the data you need and review applicable platform terms and privacy requirements.

[TikTok Scraper API →](https://jsonscraper.com/services/tiktok-scraper-api) 

Compare billing models, request allowances and migration requirements using the providers' published sources.

[Compare TikTok scraper API providers →](https://jsonscraper.com/services/tiktok-scraper-api/alternatives)

 

## Implementation notes

 

- Always include license_key in every request.
- Use cache_timeout intentionally for recurring checks.
- Persist cursor fields with query context.
- Scale route coverage class-by-class after baseline validation.

 

## Ready to launch your API workflow?

 

Pick an API, test endpoints in Postman, and launch your workflow in minutes.

 

[Open TikTok Scraper API](https://jsonscraper.com/services/tiktok-scraper-api) [Open Postman collection](https://www.postman.com/evelode/workspace/evelode/collection/24862082-d886cc87-4267-4e0c-b57a-2d083add50ad?action=share&creator=24862082) [Get Access](https://evelode.com/downloads/tiktok-rest-api/)
