DEV Community

Anurag Kumar
Anurag Kumar

Posted on Originally published at apiserpent.com

How to Get Google Trends Data with Python and Node

I run Serpent, the API used in the examples below.

To get Google Trends data in Python or Node, send one GET request with your search terms and read the JSON that comes back. You get an interest value from 0 to 100 for every term at every point in the range. The do-it-yourself route works too, but it is a four-step exchange with Google's private endpoints that you then have to keep alive.

Short answer: For a notebook or a one-off chart on your own laptop, a free library or the short script below is fine. For anything that runs on a server, feeds a dashboard or touches hundreds of terms, one API call is less code to own; for what the API costs, see current pricing. The pytrends library is archived and read-only, so do not start a new project on it. Google's own Trends API is an invite-only alpha, worth applying for if you can wait.

Google Trends has no official download button for developers. The website draws its charts from private JSON endpoints, and for years the standard way to read them from code has been an unofficial library. That route is now much shakier, and this guide shows what it takes and what the shorter route looks like.

The code for the one-call route is complete. The outputs shown for it are what each snippet prints for real answers the API returned on 20 November 2026. The do-it-yourself snippet’s output comes from a stand-in server, because this post makes no direct calls to Google.

What is actually in Google Trends data?

A series of points over time, each scaled from 0 to 100. Google's own training material says the data is “presented on a scale from 0-100, where each point on the graph is divided by the highest point”, which means a value is relative interest, not a count of searches. Google News Initiative: understanding the data has the full explanation.

You choose the terms (up to five on one chart), a place, a time range and a search type: web, images, news, YouTube or shopping. If you compare several terms in one request they share one scale, so you can see which leads. If you ask for them one at a time, each is scaled to its own peak and the numbers cannot be compared. The SEO planning post on Google Trends Data for SEO Content Planning leans on that difference.

Everything below is interest over time, the series behind the main chart. Related queries, regional maps and Trending Now are separate products at other vendors.

What happened to pytrends?

It stopped. The pytrends repository was archived by its owner on 17 April 2025 and is read-only. Its last release on PyPI is 4.9.2 from 13 April 2023. The README itself says it is looking for maintainers and is only good until Google changes its backend again.

The source in the repository's main branch visits the explore page first and keeps the NID cookie, and my earlier post on pytrends traced first-call errors to a missing cookie rather than a ban. I did not check whether the 2023 release on PyPI includes that cookie step.

A newer community library, trendspy, covers the same ground under an MIT licence, and its latest PyPI release is 0.1.6 from 25 December 2024. I did not run it for this post.

What does the do-it-yourself flow look like?

Four steps, read from the pytrends source on 20 November 2026. You visit the explore page to pick up a cookie, ask the explore address which widgets the page would draw, send the time-series widget's own request and token to the data address, and parse a reply that begins with a few junk characters.

Diagram comparing four steps you handle yourself to read Google Trends data with one GET request to the Serpent trends endpoint that returns JSON

Two routes from a search term to a timeline. On the left, four steps that stay in your own code. On the right, one request and one JSON response.

The four steps on the do-it-yourself route, and where each one bites.

Step What it means Where it bites
1. Get a cookie GET the explore page and keep the NID cookie in your session Without it, the next request can fail
2. Ask explore for widgets POST a JSON request holding the terms, place and time range; read the widgets list Each widget carries a token and a request body, and the field names are Google's private ones
3. Fetch the data GET the multiline address with that widget's own request and token A token only works with the request that produced it
4. Parse the reply Cut the junk prefix, read default.timelineData A non-JSON reply, an empty point, or a field renamed overnight

Here is the whole thing in Python. It needs the requests package and, as written, it is a sketch of the flow in the pytrends source rather than a promise about Google's current behaviour:

import json
import requests

BASE = "https://trends.google.com/trends"
HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; trends-demo/1.0)"}


def parse(text):
    """Google puts a few junk characters in front of its JSON. Cut to the first brace."""
    return json.loads(text[text.index("{"):])


def compact(obj):
    return json.dumps(obj, separators=(",", ":"))


def interest_over_time(terms, geo="", time_range="today 12-m", category=0, prop="", hl="en-US", tz=0):
    s = requests.Session()
    s.headers.update(HEADERS)

    # 1. Visit the explore page once, so the session holds the NID cookie.
    s.get(f"{BASE}/explore/", params={"geo": geo}, timeout=10)

    # 2. Ask which widgets the page would draw. Each one carries its own token and request body.
    req = {
        "comparisonItem": [{"keyword": t, "geo": geo, "time": time_range} for t in terms],
        "category": category,
        "property": prop,
    }
    r = s.post(f"{BASE}/api/explore", params={"hl": hl, "tz": tz, "req": compact(req)}, timeout=10)
    r.raise_for_status()
    widget = next(w for w in parse(r.text)["widgets"] if w["id"] == "TIMESERIES")

    # 3. Send that widget's own request and token to the data address.
    r = s.get(
        f"{BASE}/api/widgetdata/multiline",
        params={"hl": hl, "tz": tz, "req": compact(widget["request"]), "token": widget["token"]},
        timeout=10,
    )
    r.raise_for_status()
    return parse(r.text)["default"]["timelineData"]


if __name__ == "__main__":
    rows = interest_over_time(["python", "rust"], geo="US")
    first, last = rows[0], rows[-1]
    print(len(rows), "points")
    print(first["formattedTime"], first["value"], "...", last["formattedTime"], last["value"], "partial:", last["isPartial"])
Enter fullscreen mode Exit fullscreen mode

Run against the stand-in server, it prints:

53 points
Nov 16, 2025 [57, 43] ... Nov 15, 2026 [93, 71] partial: True
Enter fullscreen mode Exit fullscreen mode

That is about 40 lines for the happy path. Notice that value holds one number per term, in the order you asked for them, and that the last point is flagged as still in progress.

What is left for you to handle?

The unhappy paths. Google can answer step 2 or step 3 with an error, with an HTML page instead of JSON, or with a field that has been renamed. None of those is covered by the happy path above, and each one is code and tests you own.

Plan for these:

  • Maintenance. The endpoints are private, so a rename breaks your code on a day you did not choose.
  • Empty answers. Treat a reply with no timeline as “no data” only after you have proved it is not an error or an HTML page.

For a laptop and a dozen terms, that is fine. For a scheduled job, it is a small project. For what the API costs, see current pricing.

How do you get the same series with one request in Python?

Send a GET request to https://apiserpent.com/api/trends/interest with your key in the X-API-Key header. You need one parameter, q, which is 1 to 5 comma-separated terms. Four are optional: geo (such as US, GB or US-TX, worldwide if left out), time (default today 12-m), category and property (web, images, news, youtube or shopping).

Install requests, put your key in place of the placeholder, and run this:

import requests

API_KEY = "sk_live_your_api_key"
URL = "https://apiserpent.com/api/trends/interest"


def get_trends(q, geo="", time="today 12-m", prop="web", category=0):
    params = {"q": q, "time": time, "property": prop, "category": category}
    if geo:
        params["geo"] = geo
    r = requests.get(URL, params=params, headers={"X-API-Key": API_KEY}, timeout=60)
    r.raise_for_status()
    return r.json()


if __name__ == "__main__":
    data = get_trends("python,rust", geo="US")

    if not data["timeline"]:
        print("No trend data came back for these terms")
    else:
        print(len(data["timeline"]), "points,", data["time_range"], "| geo:", data["geo"] or "worldwide")
        for t in data["terms"]:
            print(f'{t["term"]:<8} average {t["average"]}')
        last = data["timeline"][-1]
        print("latest:", last["date"], last["values"], "(still in progress)" if last["is_partial"] else "(complete)")
Enter fullscreen mode Exit fullscreen mode

The output of a real call on 20 November 2026:

53 points, today 12-m | geo: US
python   average 58
rust     average 30
latest: Nov 15 – 21, 2026 [30, 20] (still in progress)
Enter fullscreen mode Exit fullscreen mode

The response has five fields: geo, time_range, property, terms and timeline. The documentation describes each one. Notice that the code checks timeline rather than the HTTP status. A query with nothing to show comes back in the same shape with an empty timeline, so the reliable test is whether you got rows.

You can try the same request in the playground without code, or read the field list on the Google Trends API page. A call took about 5.4 seconds at the median on a fixed set of 61 queries, and 90 percent of the answered calls finished within about 6.8 seconds, so keep the 60-second timeout generous.

And in Node?

Node 18 and later includes fetch, so the Node version needs no packages. This example compares three terms in one request and counts how many points each one leads. Save it as trends.mjs so top-level await works:

const API_KEY = "sk_live_your_api_key";
const ENDPOINT = "https://apiserpent.com/api/trends/interest";

async function getTrends(q, { geo = "", time = "today 12-m", property = "web", category = 0 } = {}) {
  const params = new URLSearchParams({ q, time, property, category: String(category) });
  if (geo) params.set("geo", geo);
  const res = await fetch(`${ENDPOINT}?${params}`, {
    headers: { "X-API-Key": API_KEY },
    signal: AbortSignal.timeout(60_000),
  });
  if (res.ok === false) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

const data = await getTrends("python,rust,go", { geo: "US" });

if (data.timeline.length === 0) {
  console.log("No trend data came back for these terms");
} else {
  // Several terms share one scale, so the highest value in a row is the term in the lead.
  const led = Object.fromEntries(data.terms.map((t) => [t.term, 0]));
  for (const row of data.timeline) {
    const top = Math.max(...row.values.map((v) => v ?? -1));
    led[data.terms[row.values.indexOf(top)].term] += 1;
  }
  console.log(`${data.timeline.length} points, ${data.time_range}, geo ${data.geo || "worldwide"}`);
  console.log("points led:", led);
}
Enter fullscreen mode Exit fullscreen mode

The output of a real call on 20 November 2026:

53 points, today 12-m, geo US
points led: { python: 0, rust: 0, go: 53 }
Enter fullscreen mode Exit fullscreen mode

“go” leads every week because it is also an everyday English word, so Google counts every search that contains it. That is the most common trap in Trends comparisons: pick terms that mean only one thing (“golang” rather than “go”) before you read anything into the lead.

Several terms share one scale, so the highest value in a row is the term in the lead for that point. A null in values means there is no data for that term at that point, which is why the code maps it to a number that can never win. For the JavaScript side of the request, the MDN page for AbortSignal.timeout() shows how to put a time limit on a fetch() call.

How do you read the rows?

Each row of timeline is one point in time. The table lists the four fields on a row and the two on each entry of terms:

The fields of a Google Trends response row.

Field Where What it holds
timestamp timeline[] The point's start as Unix seconds, in UTC
date timeline[] A readable label for the point
values timeline[] One value per term, 0 to 100, in the order of terms; null when there is no data
is_partial timeline[] True while the period is still in progress, so drop it before you average
term terms[] The term, in the order you sent it
average terms[] That term's average over the range when two or more terms are compared; null for a single term, because Google gives none

Two habits save trouble. Convert timestamp yourself rather than parsing date, and drop the partial point before you compute anything, because a half-finished week looks like a collapse in interest. This helper writes a CSV with one column per term:

import csv
import datetime as dt


def to_csv(data, path):
    """One row per point in time, one column per term. Null (no data) becomes an empty cell."""
    with open(path, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["date_utc", "is_partial"] + [t["term"] for t in data["terms"]])
        for row in data["timeline"]:
            day = dt.datetime.fromtimestamp(row["timestamp"], dt.timezone.utc).date().isoformat()
            w.writerow([day, row["is_partial"]] + ["" if v is None else v for v in row["values"]])


if __name__ == "__main__":
    from one_call import get_trends

    to_csv(get_trends("python,rust", geo="US"), "trends.csv")
    print(open("trends.csv").read().splitlines()[0])
    print(open("trends.csv").read().splitlines()[1])
    print(open("trends.csv").read().splitlines()[-1])
Enter fullscreen mode Exit fullscreen mode

It prints the header, the first row and the last row:

date_utc,is_partial,python,rust
2025-11-16,False,61,23
2026-11-15,True,30,20
Enter fullscreen mode Exit fullscreen mode

The CSV opens in a spreadsheet, or loads into pandas in one line. If you are building a report around it, automating SEO reports covers the scheduling side.

How many rows does each time range return?

It depends on the range, and the number is worth knowing before you size a table. On the fixed set of 61 queries, a 12-month range returned 53 weekly points, 3 months returned 93 daily points, 7 days returned 169 hourly points, 5 years returned 262 weekly points and 1 month returned 32 daily points.

Bar chart of how many points a call returns for five time ranges: 262 weekly for five years, 169 hourly for seven days, 93 daily for three months, 53 weekly for twelve months and 32 daily for one month

Points returned per time range in the fixed set of 61 queries, 20 November 2026. The default range, today 12-m, is in teal.

The ranges you can ask for are now 1-H, now 4-H, now 1-d, now 7-d, today 1-m, today 3-m, today 12-m, today 5-y, all, or two dates written as YYYY-MM-DD YYYY-MM-DD, starting no earlier than 2004-01-01. A longer or finer range comes back in the same single request, with more rows in it.

Which route should you pick?

  • A notebook, a class project or one chart from your own laptop: a free library or the short script above. It costs nothing in fees and the limits do not matter at that scale.
  • A script on a server, a scheduled job or a product feature: one API call. The four steps and their upkeep are not code you want to own.
  • Hundreds or thousands of terms: the API, with a thread pool or an async client around the Python function above, and a check for an empty timeline on every response.
  • You can get into Google's alpha: try the official Trends API alpha. Access is limited to a small number of testers and rolls out gradually.
  • Web search results, not search interest: the SERP APIs, with keyword ideas in the keyword research guide.

If you track rankings too, the Rank Tracking API sits under the same key.

How we checked this

Code. Every snippet was executed on 20 November 2026 on Python 3.15.2 (with requests 2.34.2) and Node 26.5.0. The HTTP host was swapped for a local stand-in server, so the request URLs, the X-API-Key header and the parameters were checked without a live call. For the one-call route, the stand-in served real answers the API returned on 20 November 2026 (two terms and three terms, United States, twelve months), so those outputs carry real search interest. The do-it-yourself snippet ran against made-up numbers in Google’s shape; no call was made to Google.

Measured numbers. The speed and row counts come from a fixed list of 61 queries, drawn before any call was made. Of those, 59 returned a full timeline, 1 correctly came back with no data and 1 failed and was not charged; the median call was about 5.4 seconds. On three pages compared side by side with Google's own Trends page in a browser, every date and every value matched. Treat these as a vendor's own result and test your own list.

What I could not verify:

  • The do-it-yourself code follows the flow in the pytrends source (re-read on 20 November 2026). I did not run it against Google, and Google's private field names may have changed since.
  • I did not install or run pytrends or trendspy. Their status comes from their GitHub and PyPI pages, read on 20 November 2026.
  • Whether pytrends 4.9.2 on PyPI includes the cookie step found in its main branch.
  • The format of the date label is not described here, because the values in the examples are made up.

Package versions and Google's endpoints change often, so test before you rely on either.

FAQ

How do I get Google Trends data in Python?

Send a GET request to the trends endpoint with your terms and an API key, then read the JSON. With the requests library that is one call: pass the terms as q and your key in the X-API-Key header. The response holds a timeline of timestamps and values from 0 to 100. Check that the timeline is not empty before you use the result.

Does pytrends still work?

It may work until Google changes its endpoints again, but nobody maintains it. Its repository was archived and made read-only on 17 April 2025, and the last PyPI release, 4.9.2, dates from 13 April 2023. The README says it is only good until Google changes its backend. Do not start a new project on it without a plan for the day it breaks.

Is there an official Google Trends API?

Google announced an official Trends API alpha on 24 July 2025. It is limited to a small number of testers, covers a rolling window of 1,800 days and scales values consistently across requests. If you cannot get access, developers use an open-source library or a paid Trends API instead.

How many terms can I compare in one Google Trends request?

Five. Terms in one request share a 0 to 100 scale, so you can see which leads. Separate requests are each scaled to their own peak, so the numbers from two requests cannot be compared directly. Google's own alpha API can compare dozens of terms, but the website and Serpent's endpoint take up to five.

Can I get hourly Google Trends data?

Yes, for short ranges. A time of now 7-d returned 169 hourly points in the 61-query check, and now 1-H, now 4-H and now 1-d are also accepted. Longer ranges come back at coarser steps: 93 daily points for three months and 53 weekly points for twelve months. Pick the range first, then expect the row count that goes with it.

Sources

Open-source projects and Google references (links checked when this post was drafted, 20 Nov 2026):

Language and platform references:


I run Serpent API; this post first appeared on apiserpent.com.

Top comments (0)