TikTokAnswer

TikTok API get user videos: any public account to CSV

TikTok's API lists videos only for users who log in to your app. Ours lists any public account by username and exported 1,538 of NatGeo's 1,539.

7 min read

Short answer

  • TikTok's Display API lists a user's public videos, 20 a page, but only with that user's own access token. The Research API is for approved researchers.
  • ToolzerHub's TikTok API lists any public account's videos by username at 2 credits a page. Geofenced videos are named, not listed, and fetched 25 a call for 38 credits.
  • NatGeo's 1,539 videos came back as 1,538: 307 listed and 1,231 fetched by ID. The NBA's list ends at about 2,750 to 2,950 of its 24,400.
On this page

TikTok's official API lists a user's videos only when that user logs in to your app. For any other public account, ToolzerHub's /v2/tiktok/app/user/posts lists the videos by username, with play, like, comment, share and save counts. The list skips videos TikTok marks person_geo_fencing, so the script below fetches those by ID. Very large accounts end early.

What TikTok's API is for

TikTok's Display API returns a user's public videos, 20 a page, but only with an access token from that user, so they must log in to your app first. The Research API can filter videos by username, up to 100 a request, but it is for approved researchers and works in 30-day windows. Use the Display API for users who log in to your app, and the Research API if you qualify; our Research API post covers who can apply.

Route Whose videos Who can use it
Display API Users who log in Any app a user authorizes
Research API Any public account Approved researchers
ToolzerHub Any public account Anyone with a key

TikTok videos with ToolzerHub

We make ToolzerHub. Our TikTok API lists a public account's videos by username, with one API key and no TikTok app. GET /v2/tiktok/app/user/posts takes unique_id and max_cursor (0, then the previous response's max_cursor) and costs 2 credits a call. A page holds up to 20 videos, often fewer.

Each page also carries lite_filter_reasons: the IDs of videos left out of that page, mostly geofenced ones. POST /v2/tiktok/app/video/multi takes up to 25 of those IDs and returns the videos, for 38 credits a call.

Export videos to CSV

The script writes each account's videos to CSV, with pinned videos first and marked. Pass yes as the third argument to fetch the geofenced ones; the listed column says which rows came from the list and which came by ID.

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

import requests

BASE = "https://api.toolzerhub.com/v2/tiktok/app"
HEADERS = {"x-api-key": os.environ.get("TOOLZERHUB_API_KEY", "")}
FIELDS = ["account", "video_id", "url", "listed", "posted_at", "pinned", "seconds",
          "plays", "likes", "comments", "shares", "saves", "caption"]
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", "\r"):
        return "'" + value
    return value


def call(path, params=None, ids=None, 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):
        if ids:
            r = requests.post(BASE + path, headers=HEADERS, json=ids, timeout=90)
        else:
            r = requests.get(BASE + path, headers=HEADERS, params=params, timeout=90)
        calls += 1
        if r.status_code == 400:  # malformed input: skip this account
            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, account, v, listed):
    author, stats = v.get("author") or {}, v.get("statistics") or {}
    writer.writerow({
        "account": account, "video_id": v["aweme_id"], "listed": listed,
        "url": f"https://www.tiktok.com/@{author.get('unique_id') or account}/video/{v['aweme_id']}",
        "posted_at": datetime.fromtimestamp(v["create_time"], timezone.utc).isoformat()
        if v.get("create_time") else "",
        "pinned": "yes" if v.get("is_top") else "",  # pinned videos come first, out of date order
        "seconds": round(((v.get("video") or {}).get("duration") or 0) / 1000) or "",
        "plays": stats.get("play_count"), "likes": stats.get("digg_count"),
        "comments": stats.get("comment_count"), "shares": stats.get("share_count"),
        "saves": stats.get("collect_count"),
        "caption": cell((v.get("desc") or "").replace("\r", " ").replace("\n", " ")),
    })


def export_account(writer, account, max_pages, fetch_hidden):
    params, seen, hidden, pages = {"unique_id": account, "max_cursor": 0}, set(), set(), 0
    status = "page cap reached, more available"
    while pages < max_pages:
        data = call("/user/posts", params)
        videos = (data or {}).get("aweme_list") or []
        if not videos and not (data or {}).get("has_more"):  # unknown users: 200 with no list
            status = "stopped early: failed or empty page" if pages else "nothing returned"
            break
        pages += 1
        for v in videos:  # a page can be empty when every video on it is geofenced
            if v.get("aweme_id") and v["aweme_id"] not in seen:  # pages can repeat a video
                seen.add(v["aweme_id"])
                write(writer, account, v, "yes")
        # Videos TikTok won't show in this region are left out, but their IDs are listed here.
        reasons = data.get("lite_filter_reasons") or {}
        hidden.update((json.loads(reasons) if isinstance(reasons, str) else reasons) or {})
        if not (data.get("has_more") and data.get("max_cursor")):
            status = "end"
            break
        params["max_cursor"] = data["max_cursor"]
        time.sleep(0.3)
    hidden -= seen
    got = 0
    if fetch_hidden:
        todo = sorted(hidden)
        for i in range(0, len(todo), 25):  # the batch route takes up to 25 IDs a call
            for v in call("/video/multi", ids=todo[i:i + 25]) or []:
                if v.get("aweme_id") and v["aweme_id"] not in seen:
                    seen.add(v["aweme_id"])
                    write(writer, account, v, "no, fetched by ID")
                    got += 1
    print(f"{account}: {len(seen) - got} listed, {len(hidden)} hidden, {got} fetched, {pages} pages ({status})")
    return len(seen)


def main(accounts, max_pages="50", fetch_hidden="no", out="tiktok_videos.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 account in [a.strip().lstrip("@") for a in accounts.split(",") if a.strip()]:
            total += export_account(writer, account, int(max_pages), fetch_hidden == "yes")
    print(f"wrote {total} videos 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_user_videos.py nasa,nba [max_pages] [yes|no fetch hidden] [file.csv]")
    if not HEADERS["x-api-key"]:
        sys.exit("set TOOLZERHUB_API_KEY first")
    main(*sys.argv[1:])
bash
export TOOLZERHUB_API_KEY=your_key
python tiktok_user_videos.py nasa,natgeo 70 yes tiktok_videos.csv

Output:

text
nasa: 57 listed, 0 hidden, 0 fetched, 3 pages (end)
natgeo: 307 listed, 1232 hidden, 1231 fetched, 34 pages (end)
wrote 1595 videos to tiktok_videos.csv in 87 calls

NatGeo's profile shows 1,539 videos: the list held 307 and named 1,232 more, and the batch route returned 1,231 of those. The fetched videos lean recent: 400 of them are from 2025, against 19 listed from that year.

What the accounts showed

We paged each account until has_more was 0. "Profile" is the video count from our /v1/tiktok/profile route; the NBA's is rounded.

Account Profile Listed Named, left out Pages
NASA 57 57 0 3
Duolingo 1,204 1,205 not counted 61
NatGeo 1,539 307 1,232 34
NBA 24,400 2,754 1 139

NatGeo's listed and named videos add up to its profile count exactly, and 1,229 of the 1,232 named IDs give person_geo_fencing as the reason. The NBA's list is not geofenced but ends at about 2,750 to 2,950 videos out of 24,400, and the cursor offers no way past that point.

What it costs

List calls are 2 credits a page: Duolingo's 1,205 videos took 61 calls, 122 credits, and NASA's 57 took 6. Fetching geofenced videos costs more: NatGeo's 34 list calls and 50 batch calls came to 1,968 credits for 1,538 videos. You get 100 free credits a month; $19 buys 10,000 credits that never expire, and plans for higher volume cover more accounts. Set your key and run the script on your first account.

To look up single videos from their links, see TikTok API get video, and to check whether a creator is live, the TikTok live API. For the same job on Instagram, see listing a public account's reels; for a creator's latest 11 videos with no key, how to scrape TikTok with Python runs a free script. For TikTok's Chinese sister app, see the Douyin API.

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.