Tutorial

How to Track Google Trends via a Search API

Monitor trending topics by tracking search result changes over time. Detect rising queries, seasonal patterns, and topic momentum with daily API queries.

Track Google search trends by querying the same keywords daily, measuring result freshness and content shifts, and detecting when new topics start appearing consistently across search results. Google Trends provides aggregate interest data, but it does not show you the actual content ranking for a topic. By tracking search results directly, you can see which pages are rising, which topics are generating new content, and how the SERP composition changes over time, giving you actionable content intelligence.

Prerequisites

  • Python 3.8+ installed
  • requests library installed
  • A Scavio API key from scavio.dev
  • A set of keywords to track

Walkthrough

Step 1: Define tracked keywords

Set up the keywords and categories you want to monitor for trending signals.

Python
import os, requests, json, datetime, hashlib

API_KEY = os.environ['SCAVIO_API_KEY']

TRACKED = [
    {'keyword': 'ai agent framework', 'category': 'tech'},
    {'keyword': 'remote work tools', 'category': 'productivity'},
    {'keyword': 'search api', 'category': 'tech'},
    {'keyword': 'cold email tools', 'category': 'sales'},
]

TRENDS_FILE = 'trends_history.json'

print(f'Tracking {len(TRACKED)} keywords for trends')

Step 2: Capture daily SERP snapshot

Search each keyword and store a snapshot of the results for comparison.

Python
def capture_snapshot(keyword: str) -> dict:
    resp = requests.post('https://api.scavio.dev/api/v1/search',
        headers={'x-api-key': API_KEY},
        json={'platform': 'google', 'query': keyword}, timeout=15)
    data = resp.json()
    results = data.get('organic_results', [])
    return {
        'keyword': keyword,
        'date': datetime.date.today().isoformat(),
        'result_count': len(results),
        'top_5_titles': [r.get('title', '') for r in results[:5]],
        'top_5_urls': [r.get('link', '') for r in results[:5]],
        'content_hash': hashlib.md5(json.dumps([r.get('title', '') for r in results[:5]]).encode()).hexdigest(),
        'has_featured_snippet': 'featured_snippet' in data or 'answer_box' in data,
        'paa_count': len(data.get('people_also_ask', [])),
    }

snap = capture_snapshot('ai agent framework')
print(f"{snap['keyword']}: {snap['result_count']} results, hash={snap['content_hash'][:8]}")

Step 3: Detect content velocity

Measure how fast the search results are changing to identify trending topics.

Python
def load_history() -> list:
    try:
        with open(TRENDS_FILE) as f:
            return json.load(f)
    except FileNotFoundError:
        return []

def save_history(history: list):
    with open(TRENDS_FILE, 'w') as f:
        json.dump(history, f, indent=2)

def content_velocity(keyword: str, history: list) -> dict:
    entries = [h for h in history if h['keyword'] == keyword]
    entries.sort(key=lambda x: x['date'])
    if len(entries) < 2:
        return {'velocity': 'unknown', 'changes': 0}
    recent = entries[-5:] if len(entries) >= 5 else entries
    changes = 0
    for i in range(1, len(recent)):
        if recent[i]['content_hash'] != recent[i-1]['content_hash']:
            changes += 1
    velocity = changes / (len(recent) - 1)
    return {
        'velocity': 'high' if velocity > 0.6 else 'medium' if velocity > 0.3 else 'low',
        'changes': changes,
        'days_tracked': len(recent),
    }

history = load_history()
vel = content_velocity('ai agent framework', history)
print(f"Velocity: {vel['velocity']} ({vel['changes']} changes)")

Step 4: Run daily tracking

Execute the daily tracking routine and store results.

Python
import time

def daily_track(tracked: list) -> list:
    history = load_history()
    snapshots = []
    for item in tracked:
        snap = capture_snapshot(item['keyword'])
        snap['category'] = item['category']
        snapshots.append(snap)
        history.append(snap)
        vel = content_velocity(item['keyword'], history)
        print(f"  {item['keyword']}: velocity={vel['velocity']}")
        time.sleep(0.3)
    save_history(history)
    return snapshots

snapshots = daily_track(TRACKED)

Step 5: Generate trends report

Produce a report showing which topics are trending up based on content velocity and SERP changes.

Python
def trends_report(tracked: list) -> str:
    history = load_history()
    lines = [f'Trends Report - {datetime.date.today().isoformat()}', '']
    trending = []
    for item in tracked:
        vel = content_velocity(item['keyword'], history)
        entries = [h for h in history if h['keyword'] == item['keyword']]
        latest = entries[-1] if entries else {}
        status = 'TRENDING' if vel['velocity'] == 'high' else 'STABLE' if vel['velocity'] == 'low' else 'WATCH'
        lines.append(f"[{status}] {item['keyword']} ({item['category']})")
        lines.append(f"  Velocity: {vel['velocity']}, Top: {latest.get('top_5_titles', [''])[0][:50]}")
        if vel['velocity'] == 'high':
            trending.append(item['keyword'])
    lines.append(f'\nTrending topics: {len(trending)}')
    report = '\n'.join(lines)
    print(report)
    return report

trends_report(TRACKED)

Python Example

Python
import requests, os, hashlib, json
H = {'x-api-key': os.environ['SCAVIO_API_KEY']}

def serp_hash(keyword):
    data = requests.post('https://api.scavio.dev/api/v1/search', headers=H,
        json={'platform': 'google', 'query': keyword}).json()
    titles = [r.get('title', '') for r in data.get('organic_results', [])[:5]]
    return hashlib.md5(json.dumps(titles).encode()).hexdigest()[:8]

print(serp_hash('ai agent framework'))

JavaScript Example

JavaScript
const H = {'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json'};
async function serpHash(keyword) {
  const r = await fetch('https://api.scavio.dev/api/v1/search', {
    method: 'POST', headers: H,
    body: JSON.stringify({platform: 'google', query: keyword})
  });
  const titles = ((await r.json()).organic_results || []).slice(0, 5).map(r => r.title);
  return titles.join('|').slice(0, 40);
}
serpHash('ai agent framework').then(console.log);

Expected Output

JSON
A daily trend tracking system that monitors SERP changes, measures content velocity, and identifies trending topics based on how fast search results are shifting.

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.8+ installed. requests library installed. A Scavio API key from scavio.dev. A set of keywords 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

Monitor trending topics by tracking search result changes over time. Detect rising queries, seasonal patterns, and topic momentum with daily API queries.