Blog

Cache Trends API Responses in Python

Cache Trends API responses in Python with sqlite3: cache keys, TTLs matched to each response type, and a freshness check, tested on live data from November 18, 2026.

Trends API team Published Data as of 2026-11-18

Line chart of weekly Google Search interest for air fryer, November 2021 to November 2026

Cache Trends API responses on the client, and set the TTL from how often the data changes. A weekly get_time_series response stays valid until 7 days after its latest point date, because a new weekly point lands once a week: the series for "air fryer" on Google Search pulled November 18, 2026 held 261 weekly points from 2021-11-20 to 2026-11-14, with the latest value at 54. Daily resolution series change each day, so they get a 1 day TTL. Live boards such as Google Trends refresh through the day, so they get minutes at most, or no cache at all. Each get_time_series and get_growth call costs 1 request, so a cache that serves a week of dashboard reads from one call pays for itself fast. The working example below stores responses in sqlite3, keys them by the exact request, and checks freshness before it trusts a hit.

Weekly series data stays valid for a week

The latest weekly point in the series pulled November 18, 2026 is dated 2026-11-14, four days before the pull, and no newer point exists yet. That gap is the whole case for caching: the data has no scheduled change until the next weekly point lands, though upstream revisions to past points remain possible. The series ran 261 points from 2021-11-20, when the value was 39 with volume 3,115,430, to 2026-11-14, when the value was 54 with volume 4,313,672. The week before, 2026-11-07, sat at 51 with volume 4,074,023. Growth over the same call came back at 10.0% down over 3 months, from 60 on 2026-08-15 to 54, and 8.47% down over 12 months, from 59 on 2025-11-15 to 54.

A TTL of 7 days from the fetch time still has a weak spot. A fetch made six days after the latest point lands would serve stale data for most of the week after the next point arrives. Anchor the TTL to the latest point date instead: expire the entry 7 days after the latest point, so expiry lands close to when the next point is due. The code below stores that date with each entry for exactly this check.

How long each response type can sit in the cache

The API sent no Cache-Control, ETag, or Last-Modified header on the get_growth response checked November 18, 2026, so the client sets its own TTLs instead of reading them from headers. The update rhythm for each board comes from the Trends API data catalog. TTLs for live boards are recommendations, not API facts.

Response Update rhythm TTL
get_time_series, weekly resolution New point once a week 7 days after the latest point date
get_time_series, daily resolution New point each day, about the last 90 days 1 day
get_growth Reads the same weekly points 7 days after the latest point date
get_top_trends, live boards (Google Trends, Google News Top News, Reddit Hot Posts, Steam Most Played, Polymarket, Pinterest Trending, X) Live through the day 5 minutes at most (recommended)
get_top_trends, daily boards (GitHub, YouTube Trending, TikTok Trending Hashtags, Amazon Best Sellers, and others) Daily 24 hours (recommended)
get_top_trends, Top Websites Monthly 30 days (recommended)
get_context Posts and stories, fetched live 1 hour at most (recommended)
get_top_posts Fetched live on every call Never cache

Two details in that table deserve a note. Daily resolution on Google sources covers about the last 90 days (92 days in this run), so a daily series cache holds about 90 points and turns over fast. The daily call run for this piece pulled 92 points from 2026-08-18 to 2026-11-17, with the latest value at 57. And get_growth needs no shorter TTL than the series it reads from: its windows move only when a new weekly point lands, so the same 7 day rule holds. The Python quickstart shows the first call in each mode, and the API reference lists every parameter the cache key must cover.

A working Python cache with sqlite3

The script anchors expiry to the latest point date, not the fetch time, and the run below proves it. It fetches through the REST endpoint, stores the raw response, and serves later reads from sqlite3. The sqlite3 docs cover the storage layer used here. The envelope returns body as a JSON string, so the code runs json.loads on it a second time before it stores or reads the data.

import hashlib
import json
import os
import sqlite3
import sys
import time
from datetime import datetime, timezone

import requests

API_URL = "https://api.trendsmcp.ai/api"
CACHE_VERSION = 1
DB_PATH = "trends_cache.db"

TTL_SECONDS = {
    "get_time_series": 7 * 24 * 3600,
    "get_growth": 7 * 24 * 3600,
    "get_top_trends": 5 * 60,
}


def ttl_for(body):
    if body.get("mode") == "get_time_series" and body.get("resolution") == "daily":
        return 24 * 3600
    return TTL_SECONDS[body["mode"]]


def cache_key(body):
    material = json.dumps({"v": CACHE_VERSION, "body": body}, sort_keys=True)
    return hashlib.sha256(material.encode()).hexdigest()


def connect():
    conn = sqlite3.connect(DB_PATH)
    conn.execute(
        "CREATE TABLE IF NOT EXISTS cache"
        "(key TEXT PRIMARY KEY, response TEXT, fetched_at REAL, latest_date TEXT)"
    )
    return conn


def fetch_live(body):
    key = os.environ.get("TRENDS_API_KEY") or os.environ["TMCP_API_KEY"]
    resp = requests.post(
        API_URL,
        json=body,
        headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
        timeout=60,
    )
    resp.raise_for_status()
    envelope = resp.json()
    if envelope.get("statusCode", 200) != 200:
        raise RuntimeError(f"Trends API error: {envelope.get('body', '')[:200]}")
    return envelope["body"]


def latest_date_of(data):
    if isinstance(data, list) and data:
        return str(data[-1].get("date", ""))[:10]
    if isinstance(data, dict):
        results = data.get("results")
        if isinstance(results, list) and results:
            dates = [
                str(r.get("recent_date", ""))[:10]
                for r in results
                if isinstance(r, dict) and r.get("recent_date")
            ]
            if dates:
                return max(dates)
    return ""


def expiry_for(latest_date, fetched_at, ttl_seconds):
    if latest_date:
        anchor = datetime.strptime(latest_date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
        return anchor.timestamp() + ttl_seconds
    return fetched_at + ttl_seconds


def get_or_fetch(body, ttl_seconds):
    key = cache_key(body)
    conn = connect()
    row = conn.execute(
        "SELECT response, fetched_at, latest_date FROM cache WHERE key = ?", (key,)
    ).fetchone()
    if row and time.time() < expiry_for(row[2], row[1], ttl_seconds):
        conn.close()
        return json.loads(row[0]), True
    raw = fetch_live(body)
    data = json.loads(raw)
    conn.execute(
        "INSERT OR REPLACE INTO cache (key, response, fetched_at, latest_date)"
        " VALUES (?, ?, ?, ?)",
        (key, raw, time.time(), latest_date_of(data)),
    )
    conn.commit()
    conn.close()
    return data, False


def verify_fresh(body):
    key = cache_key(body)
    conn = connect()
    row = conn.execute(
        "SELECT response, latest_date FROM cache WHERE key = ?", (key,)
    ).fetchone()
    if not row:
        conn.close()
        return None
    raw = fetch_live(body)
    data = json.loads(raw)
    fresh_date = latest_date_of(data)
    if fresh_date and fresh_date == row[1]:
        conn.execute(
            "UPDATE cache SET fetched_at = ? WHERE key = ?", (time.time(), key)
        )
        conn.commit()
        conn.close()
        return True
    if fresh_date:
        conn.execute(
            "INSERT OR REPLACE INTO cache (key, response, fetched_at, latest_date)"
            " VALUES (?, ?, ?, ?)",
            (key, raw, time.time(), fresh_date),
        )
        conn.commit()
    conn.close()
    return False


if __name__ == "__main__":
    body = {"mode": "get_time_series", "keyword": "air fryer", "source": "Google Search"}
    if len(sys.argv) > 1 and sys.argv[1] == "verify":
        result = verify_fresh(body)
        if result is True:
            print("fresh")
        elif result is False:
            print("stale, refetched")
        else:
            print("nothing cached")
    else:
        data, hit = get_or_fetch(body, ttl_for(body))
        print("cache hit" if hit else "cache miss", "| points:", len(data), "| latest:", data[-1])

The cache key carries the full request: mode, keyword, source, country, resolution, and windows. Change any of those and the key changes, so a cached growth result never answers a series read. CACHE_VERSION sits in the key material for one reason: bump it to 2 when the storage format changes, and every old entry stops matching. The raw response is stored as text exactly as received, so a later parse sees the same bytes the API sent. TTL_SECONDS covers only get_time_series, get_growth, and get_top_trends. get_context and get_top_posts have no entry, matching the table: get_context gets a recommended 1 hour at most and get_top_posts is never cached. ttl_for reads the resolution from the request and returns 1 day for a daily series instead of the 7 day default, so a daily call never inherits the weekly TTL. The 5 minute value for get_top_trends is the live-board value only: daily boards need 24 hours and Top Websites needs 30 days, so those boards need their own lookup.

The freshness check that decides hit or refetch

A TTL alone trusts the clock, so a second function verifies a hit against a fresh fetch on a schedule. It costs 1 request, so it is meant to run on a timer (wire verify into cron or a scheduler) and not on every read: once a day for daily series, once a week just after the next point is due for weekly series. The script runs it as python trends_cache.py verify, which prints fresh when the cached copy is still the newest, stale, refetched when it replaced the entry, and nothing cached when the cache holds no entry for the request.

def verify_fresh(body):
    key = cache_key(body)
    conn = connect()
    row = conn.execute(
        "SELECT response, latest_date FROM cache WHERE key = ?", (key,)
    ).fetchone()
    if not row:
        conn.close()
        return None
    raw = fetch_live(body)
    data = json.loads(raw)
    fresh_date = latest_date_of(data)
    if fresh_date and fresh_date == row[1]:
        conn.execute(
            "UPDATE cache SET fetched_at = ? WHERE key = ?", (time.time(), key)
        )
        conn.commit()
        conn.close()
        return True
    if fresh_date:
        conn.execute(
            "INSERT OR REPLACE INTO cache (key, response, fetched_at, latest_date)"
            " VALUES (?, ?, ?, ?)",
            (key, raw, time.time(), fresh_date),
        )
        conn.commit()
    conn.close()
    return False

The function returns True when the cached copy is still the newest, False when it replaced the entry, and None when the cache holds no entry for the request. The comparison uses the latest point date, not the value: a series can hold the same value across two weeks while the date moves, and the date is what proves the copy is current. A dashboard that reads the cache on every load and runs this check on a schedule gets fresh data without paying for a fetch per page view.

What the cache saves on a real call

The series call pulled November 18, 2026 answered in 0.68 seconds and carried 36,572 bytes of envelope, with the inner response at 32,365 bytes. A cache hit removes both the wait and the request. The growth call with two windows answered in 0.47 seconds, with 1,444 bytes of envelope and 1,295 bytes inside. A single window growth call answered with a Content-Length of 830 bytes. None of those numbers are large on their own, and that is the point: the saving is the request count, not the bytes.

The script ran twice against the live API on November 18, 2026. The first run missed the empty cache and fetched 261 points with the latest at 2026-11-14; the second run hit and served the same 261 points with no request. A verify run printed fresh, confirming the cached copy still matched the live latest date.

Each get_time_series and get_growth call costs 1 request, and the rate limits guide explains how those requests add up. Take a dashboard that reads the same series 20 times a day as an example: without a cache that is 140 calls a week, and with a 7 day TTL it is 1 call plus 1 freshness check. Plan limits live on pricing, so the exact saving in allowance terms depends on the plan, but the ratio holds on any of them.

Three responses that should never sit in a cache

Live boards and live posts change between reads, so caching them serves an old ranking as the current one. get_top_posts is fetched live on every call, and the ranking can move with each fetch, so a cached copy can be wrong the moment the hashtag page moves. get_context returns posts, videos, and markets from the last 7 days by default, and a cached copy misses every post published after the fetch. Live get_top_trends boards such as Google Trends, Reddit Hot Posts, and Steam Most Played update through the day: the get_top_trends guide shows the call, and a dashboard that needs the current board should call it fresh and skip the cache. When the data has no fixed refresh point, the safe TTL is zero.

Questions

Does the Trends API send cache headers?

No. The get_growth response checked on November 18, 2026 carried no Cache-Control, ETag, or Last-Modified header, so TTLs live in client code.

Can one cache serve both get_time_series and get_growth?

Yes, with the mode inside the cache key. The two calls return different shapes, a list of points and one result per window, so a shared key would hand a growth reader a series list.

Sources