Tutorial

How to Build a TikTok Content Performance Tracker

Track TikTok video engagement over time using the API. Monitor views, likes, comments, and shares to identify your best-performing content patterns.

Posting TikTok content without tracking performance means you cannot identify what works. This tutorial builds a content performance tracker that pulls your video stats via the Scavio TikTok API, stores snapshots over time, and calculates engagement velocity (how fast a video gains views and likes after posting). Use this data to identify your top content patterns and double down on what resonates. Each API call costs $0.005 using Bearer token authentication.

Prerequisites

  • Python 3.9+ installed
  • requests library installed
  • A Scavio API key from scavio.dev
  • A TikTok account username to track

Walkthrough

Step 1: Pull your TikTok video history

Fetch your recent posts using the user posts endpoint. This returns video metadata and current engagement stats.

Python
import os, requests, json, time
from datetime import datetime

SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
TT_URL = 'https://api.scavio.dev/api/v1/tiktok'
TT_H = {'Authorization': f'Bearer {SCAVIO_KEY}', 'Content-Type': 'application/json'}

def get_user_videos(username: str) -> list:
    # Get profile first to get sec_user_id
    resp = requests.post(f'{TT_URL}/profile', headers=TT_H,
        json={'username': username})
    sec_uid = resp.json().get('data', {}).get('user', {}).get('secUid', '')
    time.sleep(0.3)
    # Get posts
    resp = requests.post(f'{TT_URL}/user/posts', headers=TT_H,
        json={'sec_user_id': sec_uid, 'count': 30})
    videos = resp.json().get('data', {}).get('videos', [])
    return [{
        'id': v.get('id'),
        'desc': v.get('desc', '')[:80],
        'created': v.get('createTime', 0),
        'views': v.get('stats', {}).get('playCount', 0),
        'likes': v.get('stats', {}).get('diggCount', 0),
        'comments': v.get('stats', {}).get('commentCount', 0),
        'shares': v.get('stats', {}).get('shareCount', 0),
        'timestamp': datetime.now().isoformat(),
    } for v in videos]

videos = get_user_videos('scikitnews')
print(f'Fetched {len(videos)} videos')
for v in videos[:5]:
    print(f'  {v["views"]:>10,} views | {v["likes"]:>8,} likes | {v["desc"][:40]}')

Step 2: Store snapshots for time-series tracking

Save video stats to a JSON file with timestamps. Each run appends a new snapshot so you can track changes over time.

Python
TRACKING_FILE = 'tiktok_performance.json'

def load_history() -> dict:
    if os.path.exists(TRACKING_FILE):
        with open(TRACKING_FILE) as f:
            return json.load(f)
    return {'snapshots': []}

def save_snapshot(videos: list):
    history = load_history()
    history['snapshots'].append({
        'timestamp': datetime.now().isoformat(),
        'videos': videos,
    })
    with open(TRACKING_FILE, 'w') as f:
        json.dump(history, f, indent=2)
    print(f'Snapshot saved: {len(videos)} videos, {len(history["snapshots"])} total snapshots')

save_snapshot(videos)

Step 3: Calculate engagement velocity

Compare the latest snapshot with the previous one to calculate how fast each video is gaining views and likes.

Python
def calculate_velocity(history: dict) -> list:
    snapshots = history.get('snapshots', [])
    if len(snapshots) < 2:
        print('Need at least 2 snapshots to calculate velocity')
        return []
    current = {v['id']: v for v in snapshots[-1]['videos']}
    previous = {v['id']: v for v in snapshots[-2]['videos']}
    velocities = []
    for vid_id, curr in current.items():
        prev = previous.get(vid_id)
        if not prev:
            continue
        view_delta = curr['views'] - prev['views']
        like_delta = curr['likes'] - prev['likes']
        velocities.append({
            'id': vid_id,
            'desc': curr['desc'],
            'view_velocity': view_delta,
            'like_velocity': like_delta,
            'total_views': curr['views'],
            'engagement_rate': curr['likes'] / curr['views'] if curr['views'] > 0 else 0,
        })
    velocities.sort(key=lambda x: x['view_velocity'], reverse=True)
    print('Content Velocity Report')
    print('-' * 60)
    for v in velocities[:10]:
        print(f'  +{v["view_velocity"]:>8,} views | +{v["like_velocity"]:>6,} likes | {v["desc"][:35]}')
    return velocities

history = load_history()
calculate_velocity(history)

Python Example

Python
import os, requests, json, time
from datetime import datetime

SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
TT_H = {'Authorization': f'Bearer {SCAVIO_KEY}', 'Content-Type': 'application/json'}

def track_content(username):
    resp = requests.post('https://api.scavio.dev/api/v1/tiktok/profile', headers=TT_H,
        json={'username': username})
    uid = resp.json().get('data', {}).get('user', {}).get('secUid', '')
    time.sleep(0.3)
    resp2 = requests.post('https://api.scavio.dev/api/v1/tiktok/user/posts', headers=TT_H,
        json={'sec_user_id': uid, 'count': 20})
    videos = resp2.json().get('data', {}).get('videos', [])
    print(f'Tracking {len(videos)} videos for @{username}')
    for v in videos[:5]:
        s = v.get('stats', {})
        eng = (s.get('diggCount', 0) + s.get('commentCount', 0)) / max(s.get('playCount', 1), 1)
        print(f'  {s.get("playCount", 0):>10,} views | {eng:.1%} eng | {v.get("desc", "")[:35]}')

track_content('scikitnews')

JavaScript Example

JavaScript
const SCAVIO_KEY = process.env.SCAVIO_API_KEY;
const TT_H = { Authorization: `Bearer ${SCAVIO_KEY}`, 'Content-Type': 'application/json' };

async function trackContent(username) {
  const profile = await fetch('https://api.scavio.dev/api/v1/tiktok/profile', {
    method: 'POST', headers: TT_H, body: JSON.stringify({ username })
  }).then(r => r.json());
  const uid = profile.data?.user?.secUid || '';
  const posts = await fetch('https://api.scavio.dev/api/v1/tiktok/user/posts', {
    method: 'POST', headers: TT_H, body: JSON.stringify({ sec_user_id: uid, count: 20 })
  }).then(r => r.json());
  const videos = posts.data?.videos || [];
  console.log(`Tracking ${videos.length} videos for @${username}`);
  videos.slice(0, 5).forEach(v => {
    const s = v.stats || {};
    const eng = ((s.diggCount || 0) + (s.commentCount || 0)) / Math.max(s.playCount || 1, 1);
    console.log(`  ${(s.playCount || 0).toLocaleString()} views | ${(eng * 100).toFixed(1)}% eng`);
  });
}

trackContent('scikitnews');

Expected Output

JSON
Fetched 30 videos
    1,234,567 views |  145,200 likes | How to use search APIs in your app
      892,345 views |   98,400 likes | Building an AI agent with web search
      654,321 views |   72,100 likes | TikTok API tutorial for developers

Snapshot saved: 30 videos, 2 total snapshots

Content Velocity Report
------------------------------------------------------------
  + 125,000 views | + 14,200 likes | How to use search APIs in your
  +  89,000 views | +  9,800 likes | Building an AI agent with web
  +  45,000 views | +  5,100 likes | TikTok API tutorial for develop

Related Tutorials

Frequently Asked Questions

Most developers complete this tutorial in 15 to 30 minutes. You will need a Scavio API key (free tier works) and a working Python or JavaScript environment.

Python 3.9+ installed. requests library installed. A Scavio API key from scavio.dev. A TikTok account username to track. A Scavio API key gives you 250 free credits per month.

Yes. The free tier includes 250 credits per month, which is more than enough to complete this tutorial and prototype a working solution.

Scavio has a native LangChain package (langchain-scavio), an MCP server, and a plain REST API that works with any HTTP client. This tutorial uses the raw REST API, but you can adapt to your framework of choice.

Start Building

Track TikTok video engagement over time using the API. Monitor views, likes, comments, and shares to identify your best-performing content patterns.