Back to blog

TikTok API Python Tutorial: Get Video Stats Without Official API Restrictions

TikTok's official API requires business approval and weeks of review. This Python tutorial shows how to get video stats for any public TikTok URL — views, likes, comments, shares, and engagement — using a simple REST API with no OAuth required.

·3 min read·by ContentStats Team

TL;DR

The short answer — skip the full read

Use the ContentStats API with Python to fetch TikTok video views, likes, comments, shares, and engagement for any public URL—without TikTok’s official API, OAuth, or business approval.

  • Track any public TikTok, YouTube, or Instagram video via a simple REST API.
  • Fetch views, likes, comments, shares, and compute engagement rates in Python.
  • Scale analysis with pandas and automate viral spike detection over time.

1–2 hours

Time to build a working TikTok stats script in Python

No official API

Track any public TikTok video without business approval

~$0.01 / day

Approx. cost per tracked video on ContentStats

Getting TikTok video data in Python is harder than it should be. TikTok's official API requires:

  • A registered business account
  • Application review (takes days to weeks)
  • Specific use-case approval
  • Compliance with TikTok's developer policies

Most developers — especially those building analytics tools, competitor research tools, or content tracking systems — don't need the full TikTok API. They just need access to video statistics: views, likes, comments, shares, and engagement rates for public videos.

This tutorial covers how to get that data in Python.

The Problem with TikTok's Official API

TikTok offers two APIs:

TikTok for Developers (Display API / Login Kit): Requires users to authorize your app via OAuth. Only works for data about your own account or accounts that explicitly grant access. You cannot use this to track competitor content or monitor videos you don't own.

TikTok Research API: Academic/research use only. Requires institutional affiliation (universities, research organizations). Not available for commercial use.

Neither API lets you simply fetch public video statistics for arbitrary TikTok URLs — which is what most analytics use cases require.

Option 1: ContentStats API (Easiest, Production-Ready)

The ContentStats API lets you track any public TikTok video's performance via a simple REST API. No OAuth flows, no TikTok business account required.

Install and setup

python
pip install requests

Track a TikTok video

python
import requests

API_KEY = "your_contentstats_api_key"  # Get at contentstats.io
BASE_URL = "https://www.contentstats.io/api/v1"

def track_video(video_url: str) -> dict:
    """Start tracking a TikTok, YouTube, or Instagram video."""
    response = requests.post(
        f"{BASE_URL}/posts/track",
        headers={"x-api-key": API_KEY},
        json={"postLink": video_url}
    )
    response.raise_for_status()
    return response.json()

def get_video_stats(post_id: str) -> dict:
    """Get current stats for a tracked video."""
    response = requests.get(
        f"{BASE_URL}/posts/{post_id}",
        headers={"x-api-key": API_KEY}
    )
    response.raise_for_status()
    return response.json()

# Track a TikTok video
tiktok_url = "https://www.tiktok.com/@username/video/1234567890"
tracked = track_video(tiktok_url)
post_id = tracked["data"]["id"]

print(f"Video tracked. ID: {post_id}")

# Fetch current stats
stats = get_video_stats(post_id)
print(f"Views: {stats['data']['viewCount']}")
print(f"Likes: {stats['data']['likeCount']}")
print(f"Comments: {stats['data']['commentCount']}")
print(f"Shares: {stats['data']['shareCount']}")

Track multiple videos at once

python
import time
from typing import List

def track_multiple_videos(urls: List[str]) -> List[dict]:
    """Track multiple videos and return their IDs."""
    tracked = []
    for url in urls:
        result = track_video(url)
        tracked.append({
            "url": url,
            "post_id": result["data"]["id"]
        })
        time.sleep(0.5)  # Respect rate limits
    return tracked

def get_all_stats(tracked_videos: List[dict]) -> List[dict]:
    """Fetch stats for all tracked videos."""
    results = []
    for video in tracked_videos:
        stats = get_video_stats(video["post_id"])
        results.append({
            "url": video["url"],
            "views": stats["data"]["viewCount"],
            "likes": stats["data"]["likeCount"],
            "comments": stats["data"]["commentCount"],
            "engagement_rate": (
                (stats["data"]["likeCount"] + stats["data"]["commentCount"])
                / max(stats["data"]["viewCount"], 1)
            ) * 100
        })
    return results

# Example usage
urls = [
    "https://www.tiktok.com/@creator1/video/111",
    "https://www.tiktok.com/@creator2/video/222",
    "https://www.youtube.com/watch?v=abc123",  # Also works for YouTube!
]

tracked = track_multiple_videos(urls)
all_stats = get_all_stats(tracked)

for stat in all_stats:
    print(f"URL: {stat['url']}")
    print(f"  Views: {stat['views']:,}")
    print(f"  Engagement Rate: {stat['engagement_rate']:.2f}%")
    print()

Monitor a video for 24 hours (viral spike detection)

python
import time
from datetime import datetime

def monitor_video(post_id: str, hours: int = 24, interval_minutes: int = 60):
    """Monitor a video's view count over time to detect viral spikes."""
    readings = []
    intervals = (hours * 60) // interval_minutes
    
    for i in range(intervals):
        stats = get_video_stats(post_id)
        reading = {
            "timestamp": datetime.now().isoformat(),
            "views": stats["data"]["viewCount"],
            "likes": stats["data"]["likeCount"]
        }
        readings.append(reading)
        
        # Detect spike: views grew >10x vs previous hour
        if len(readings) >= 2:
            prev_views = readings[-2]["views"]
            curr_views = readings[-1]["views"]
            growth = curr_views - prev_views
            if prev_views > 0 and growth / prev_views > 10:
                print(f"VIRAL SPIKE DETECTED at {reading['timestamp']}")
                print(f"Views jumped from {prev_views:,} to {curr_views:,} in {interval_minutes} min")
        
        print(f"[{reading['timestamp']}] Views: {reading['views']:,}")
        
        if i < intervals - 1:  # Don't sleep after last check
            time.sleep(interval_minutes * 60)
    
    return readings

# Monitor a video for 24 hours, checking every hour
# monitor_video(post_id, hours=24, interval_minutes=60)

Option 2: Using pandas for TikTok Analytics

If you want to analyze your data at scale:

python
import pandas as pd
import requests

API_KEY = "your_contentstats_api_key"

def list_tracked_posts(limit: int = 50) -> pd.DataFrame:
    """Get all tracked videos as a pandas DataFrame."""
    response = requests.get(
        "https://www.contentstats.io/api/v1/posts",
        headers={"x-api-key": API_KEY},
        params={"limit": limit}
    )
    data = response.json()["data"]
    
    records = []
    for post in data:
        records.append({
            "id": post.get("id"),
            "url": post.get("postLink"),
            "platform": post.get("platform"),
            "views": post.get("viewCount", 0),
            "likes": post.get("likeCount", 0),
            "comments": post.get("commentCount", 0),
            "shares": post.get("shareCount", 0),
        })
    
    df = pd.DataFrame(records)
    df["engagement_rate"] = (
        (df["likes"] + df["comments"]) / df["views"].replace(0, 1) * 100
    ).round(2)
    return df

df = list_tracked_posts()
print(df.sort_values("views", ascending=False).head(10))
print(f"\nAverage engagement rate: {df['engagement_rate'].mean():.2f}%")

Getting Your API Key

  1. Sign up at contentstats.io

  2. Go to your dashboard → Settings → API Keys

  3. Create a new key

  4. The free tier includes $1 in credits (enough for ~100 tracked videos)

ContentStats API: What You Can Track

The API works for all major video platforms:

PlatformMetrics Available
TikTokViews, likes, comments, shares, engagement rate
YouTubeViews, likes, comments, duration, channel info
InstagramViews, likes, comments, engagement

Comparison: ContentStats API vs TikTok Official API

FeatureContentStats APITikTok Official API
Setup time< 5 minutesDays to weeks
Business account requiredNoYes
Application approvalNoYes
Track any public videoYesLimited
Cross-platformYes (TikTok + YouTube + Instagram)TikTok only
Rate limitsPer planVery strict
PricingPay-per-useFree (but limited)
Python SDKREST API (easy to use)Official SDK available

FAQ

Public video metrics (views, likes, comments) are publicly displayed on TikTok. Accessing public information is generally legal, though you should review TikTok's Terms of Service for your specific use case. ContentStats operates within platform terms by accessing publicly available data.

What's the rate limit for the ContentStats API?

Rate limits depend on your plan. The free tier ($1 in credits) is sufficient for small-scale projects. Paid plans support higher volume with $0.01 per tracked video per day.

Can I track private TikTok videos?

No. ContentStats (and all third-party tools) can only access publicly available data. Private videos are not accessible.

Does this work for TikTok Business accounts?

Yes. ContentStats tracks any public TikTok video, whether from a personal creator account or a business account.

Can I use this in a commercial product?

Yes. The ContentStats API is designed for commercial use. See the terms of service for details.


Share this post

ContentStats Team

Written by

ContentStats Team

Team

Related Posts

How to Check TikTok Analytics in 2026 (Step-by-Step)

To check TikTok analytics, go to your profile → tap the three-line menu → Creator Tools → Analytics. On desktop, go to TikTok Studio → Analytics. Step-by-step guide covering every metric, what it means, and how to use it to grow faster.

ContentStats Team