Back to use cases

    Use case / SOCIAL DATA / Python 3 / Published

    TikTok analytics to CSV with Python

    Build TikTok analytics in Python from public profiles and recent posts. Export engagement rates, median views and posting cadence to CSV with a stored sample.

    Public profiles flowing through profile and posts lookups into CSV summaries

    This TikTok analytics example gives analysts a spreadsheet snapshot of public profiles and recent posts. It exports per-post metrics and profile summaries with Python. This page shows a stored sample. There is no hosted demo.

    The problem

    Comparing public accounts means collecting follower counts and post metrics in one place. Raw views alone do not show engagement or posting cadence. A CSV makes those figures easier to sort and compare.

    What the app does

    • Fetches each public profile and its recent posts.
    • Computes engagement percentage, median views, likes, comments and shares.
    • Reports posts per week, views per follower and the weekday with the highest median views in the returned sample.
    • Writes a posts CSV, a profile summary CSV and a Markdown summary.

    How it works

    1. Read the key. The script reads a local key file, defaulting to ~/.desearch_api_key, and sends it in the Authorization header.
    2. Fetch profiles and posts. It calls GET /desearch/tiktok/profile/{username}, then GET /desearch/tiktok/profile/{username}/posts with a small count. It skips posts collection when the profile call does not succeed.
    3. Follow returned cursors. With additional pages requested, it passes the x-desearch-next-cursor header unchanged as cursor. It stops when the header is absent or a page has no posts. The dated sample returned 10 posts per profile. Treat this as a snapshot of returned posts, not a full history.
    4. Compute metrics. It deduplicates posts by id. Engagement percentage is 100 times (likes + comments + shares) / views. Zero views leave the engagement value empty.
    5. Estimate cadence. A heuristic flags up to three older posts at the front of the feed as likely pinned. Cadence excludes flagged posts when other posts remain, and uses a window of at least seven days. These flags are estimates. The best weekday describes this sample, not a recommended posting schedule.
    6. Export files. It saves raw responses for reuse and writes the CSVs and Markdown summary.

    The code

    These are verbatim excerpts from tiktok_profile_analytics.py. The first reads the local key file. The second is part of post_row; its helpers and imports are defined in the full script.

    PYTHON
    def read_key(path):
        p = os.path.expanduser(path)
        if not os.path.isfile(p):
            raise SystemExit(f"key file not found: {p} (put your Desearch API key in it, one line)")
        k = open(p).read().strip()
        if not k:
            raise SystemExit(f"key file is empty: {p}")
        return k
    
    PYTHON
        s = p.get("stats") or {}
        views, likes, com, sh, sv = (num(s.get(k)) for k in ("playCount", "digCount", "commentCount", "shareCount", "collectCount"))
        t = utc(p.get("createTime"))
        er = round(100 * (likes + com + sh) / views, 3) if views else None

    Endpoints

    • GET /desearch/tiktok/profile/{username}
    • GET /desearch/tiktok/profile/{username}/posts

    Example output

    This table is copied from samples/sample-summary.md, recorded on 2026-10-16. The sample uses anonymous profile labels. Engagement rates are percentages calculated from the returned posts.

    | profile | followers | posts | posts/week | median views | median ER % | best weekday |
    |---|---|---|---|---|---|---|
    | brand_a | 2100000 | 10 | 5.22 | 293205.5 | 7.489 | Tue (median views 916375, n=2) |
    | brand_b | 18300000 | 10 | 9.0 | 600720.5 | 15.636 | Thu (median views 5784513, n=1) |
    | brand_c | 27300000 | 10 | 7.0 | 80453.5 | 8.239 | Mon (median views 3917966, n=2) |

    Run it yourself

    Open the source folder and install its requirements with pip install -r requirements.txt. Replay the saved sample without an API key or API calls:

    BASH
    python tiktok_profile_analytics.py --from-raw samples/sample-raw.json --out output/sample

    For live requests, create a key at the console. Save it as one line in ~/.desearch_api_key, or pass a local path with --key-file. The script reads the key from a file only. Replace the profile placeholders in the source README command with the public profiles you want to analyze:

    BASH
    python tiktok_profile_analytics.py --profiles BRAND_ONE BRAND_TWO BRAND_THREE --count 10 --out output/brands

    What it costs

    The 2026-10-16 run recorded $0.06831 across six calls: three profile lookups and three posts requests returning 30 posts. Each profile lookup recorded $0.00207. Each 10-post request recorded $0.0207. These are historical measurements from X-Desearch-Cost-Usd, not a price guarantee.

    Profile calls took 1.41 to 1.66 seconds each. Posts calls took 3.38 to 11.58 seconds each in that run. Start with a small count, read the recorded cost headers and check pricing before increasing collection.

    Ideas to extend it

    • Save dated snapshots to compare the same profiles over time.
    • Review likely pinned flags before interpreting posting cadence.
    • Chart median views beside engagement percentage in a spreadsheet.

    Use with AI agents

    Point an MCP client at the hosted Desearch server. Replace the placeholder with a key from the console. Do not commit the key.

    JSON
    {
      "mcpServers": {
        "desearch": {
          "url": "https://mcp.desearch.ai/mcp",
          "headers": {
            "Authorization": "Bearer <key>"
          }
        }
      }
    }

    Prompt you can paste for this example:

    Build TikTok analytics with Desearch in Python. Read the API key from a local key file. Fetch GET /desearch/tiktok/profile/{username} and GET /desearch/tiktok/profile/{username}/posts with count 10. Follow only the x-desearch-next-cursor header when present, passing it unchanged as cursor. Deduplicate posts by id. Compute engagement percentage as 100 times likes plus comments plus shares divided by views, leaving it empty for zero views. Export per-post and per-profile CSVs with medians and posting cadence. Flag likely pinned posts using the source heuristic and explain its limits. Show recorded response costs and label results as a snapshot of returned posts, never a full history.

    Build your own example.

    Give your agents access to web and social search. Get an API key to start building, or talk to us about your integration.

    Read docs