ScavioScavio
ProductPricingDocs
Sign InGet Started
  1. Home
  2. Tutorials
  3. How to Build a YouTube Trend Detector
Tutorial

How to Build a YouTube Trend Detector

Detect rising YouTube topics by tracking view counts for niche keywords over time using the Scavio search API. Daily cron with SQLite storage and trend scoring.

Get Free API KeyAPI Docs

A YouTube trend detector searches niche keywords via the Scavio API with platform set to youtube, stores view counts daily in SQLite, and identifies rising topics by calculating week-over-week view count growth.

Prerequisites

  • Python 3.9+
  • Scavio API key
  • SQLite (stdlib)

Walkthrough

Step 1: Search YouTube for a keyword

Use platform:youtube to get video listings with view counts for any query.

Python
import requests

API_KEY = "your-scavio-api-key"

def search_youtube(query: str, n: int = 10) -> list:
    r = requests.post(
        "https://api.scavio.dev/api/v1/search",
        json={"query": query, "platform": "youtube", "num_results": n},
        headers={"x-api-key": API_KEY},
        timeout=15
    )
    r.raise_for_status()
    return r.json().get("organic_results", [])

Step 2: Parse view counts from results

Extract total view count across top videos for the keyword.

Python
import re

def parse_views(views_str: str) -> int:
    if not views_str:
        return 0
    s = views_str.upper().replace(",","")
    m = re.search(r"([\d.]+)([KMB])?", s)
    if not m:
        return 0
    num = float(m.group(1))
    mult = {"K": 1_000, "M": 1_000_000, "B": 1_000_000_000}.get(m.group(2), 1)
    return int(num * mult)

def total_views_for_keyword(query: str) -> int:
    videos = search_youtube(query, n=5)
    return sum(parse_views(v.get("views","")) for v in videos)

Step 3: Track and detect trends

Store daily view sums and alert when a keyword's views jump by 50%+ week-over-week.

Python
import sqlite3
from datetime import date, timedelta

NICHE_KEYWORDS = ["vibe coding", "ai agent tools", "local llm setup", "cursor vs copilot", "claude code tutorial"]

def init_db(path="youtube_trends.db"):
    conn = sqlite3.connect(path)
    conn.execute("CREATE TABLE IF NOT EXISTS trends (date TEXT, keyword TEXT, total_views INTEGER, PRIMARY KEY (date, keyword))")
    conn.commit()
    return conn

def run_trend_detector():
    conn = init_db()
    today = str(date.today())
    week_ago = str(date.today() - timedelta(days=7))
    results = []
    for kw in NICHE_KEYWORDS:
        views = total_views_for_keyword(kw)
        conn.execute("INSERT OR REPLACE INTO trends VALUES (?,?,?)", (today, kw, views))
        conn.commit()
        prev = conn.execute("SELECT total_views FROM trends WHERE keyword=? AND date=?", (kw, week_ago)).fetchone()
        growth = ((views - prev[0]) / prev[0] * 100) if prev and prev[0] > 0 else None
        results.append({"keyword": kw, "views": views, "growth_pct": growth})
    results.sort(key=lambda x: x.get("growth_pct") or 0, reverse=True)
    for r in results:
        g = f"+{r['growth_pct']:.0f}%" if r["growth_pct"] else "no prior data"
        print(f"{r['keyword']:<35} {r['views']:>10,} views | WoW: {g}")

run_trend_detector()

Python Example

Python
import requests
import sqlite3
import re
from datetime import date, timedelta

API_KEY = "your-scavio-api-key"
KEYWORDS = ["vibe coding", "ai agent tools", "local llm setup", "cursor vs copilot", "claude code tutorial"]

def search_youtube(query, n=5):
    r = requests.post("https://api.scavio.dev/api/v1/search",
                      json={"query": query, "platform": "youtube", "num_results": n},
                      headers={"x-api-key": API_KEY}, timeout=15)
    r.raise_for_status()
    return r.json().get("organic_results", [])

def parse_views(s):
    if not s: return 0
    m = re.search(r"([\d.]+)([KMB])?", s.upper().replace(",",""))
    if not m: return 0
    return int(float(m.group(1)) * {"K":1000,"M":1_000_000,"B":1_000_000_000}.get(m.group(2),1))

def total_views(query):
    return sum(parse_views(v.get("views","")) for v in search_youtube(query))

def init_db():
    conn = sqlite3.connect("youtube_trends.db")
    conn.execute("CREATE TABLE IF NOT EXISTS trends (date TEXT, keyword TEXT, views INTEGER, PRIMARY KEY (date, keyword))")
    conn.commit()
    return conn

def run():
    conn = init_db()
    today = str(date.today())
    week_ago = str(date.today() - timedelta(days=7))
    rows = []
    for kw in KEYWORDS:
        views = total_views(kw)
        conn.execute("INSERT OR REPLACE INTO trends VALUES (?,?,?)", (today, kw, views))
        conn.commit()
        prev = conn.execute("SELECT views FROM trends WHERE keyword=? AND date=?", (kw, week_ago)).fetchone()
        growth = ((views - prev[0]) / prev[0] * 100) if prev and prev[0] else None
        rows.append((kw, views, growth))
    rows.sort(key=lambda x: x[2] or 0, reverse=True)
    print(f"YouTube Trend Report — {today}")
    for kw, views, g in rows:
        g_str = f"+{g:.0f}%" if g else "no prior"
        print(f"  {kw:<35} {views:>10,} | {g_str}")

if __name__ == "__main__":
    run()

JavaScript Example

JavaScript
const API_KEY = 'your-scavio-api-key';
const KEYWORDS = ['vibe coding', 'ai agent tools', 'local llm setup'];

async function searchYoutube(query, n = 5) {
  const res = await fetch('https://api.scavio.dev/api/v1/search', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'x-api-key': API_KEY },
    body: JSON.stringify({ query, platform: 'youtube', num_results: n })
  });
  const data = await res.json();
  return data.organic_results ?? [];
}

function parseViews(s) {
  if (!s) return 0;
  const m = s.toUpperCase().replace(/,/g,'').match(/([\d.]+)([KMB])?/);
  if (!m) return 0;
  return Math.round(parseFloat(m[1]) * ({K:1e3,M:1e6,B:1e9}[m[2]] ?? 1));
}

for (const kw of KEYWORDS) {
  const videos = await searchYoutube(kw);
  const total = videos.reduce((s, v) => s + parseViews(v.views), 0);
  console.log(`${kw}: ${total.toLocaleString()} total views`);
}

Expected Output

JSON
YouTube Trend Report - 2026-05-22
  vibe coding                         24,892,441 | +187%
  ai agent tools                      18,441,209 | +94%
  cursor vs copilot                   12,209,882 | +71%
  local llm setup                      8,891,022 | +43%
  claude code tutorial                 4,102,441 | +28%

Related Tutorials

  • How to Build a YouTube Channel Stats Dashboard
  • How to Build a TikTok Hashtag Tracker
  • How to Build a Multi-Source Research Agent

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+. Scavio API key. SQLite (stdlib). A Scavio API key gives you 50 free credits on signup.

Yes. The free tier includes 50 credits on signup, 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.

Related Resources

Best Of

Best Real Time Search API in 2026

Read more
Best Of

Best Low-Latency Search APIs for AI Agents (2026)

Read more
Glossary

Exa Semantic Search

Read more
Solution

Find YouTube Influencers via API Instead of Scraping

Read more
Use Case

n8n Search Enrichment Workflow

Read more
Solution

Migrate from Brave Search API to Scavio for Better Coverage

Read more

Start Building

Detect rising YouTube topics by tracking view counts for niche keywords over time using the Scavio search API. Daily cron with SQLite storage and trend scoring.

Get Free API KeyRead the Docs
ScavioScavio

Real-time search API for AI agents. Search every platform, not just Google.

Product

  • Features
  • Pricing
  • Dashboard
  • Affiliates

Developers

  • Documentation
  • API Reference
  • Quickstart
  • MCP Integration
  • Python SDK

Alternatives

  • Tavily Alternative
  • SerpAPI Alternative
  • Firecrawl Alternative
  • Exa Alternative

Tools

  • JSON Formatter
  • cURL to Code
  • Token Counter
  • All Tools

© 2026 Scavio. All rights reserved.

Featured on TAAFT
Terms of ServicePrivacy Policy