Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Google Trends API for Python & AI Agents (Fast & Cost-Effective Alternative)

PyPI Version License: MIT Python Versions PRs Welcome Maintained

Complete developer guide, lightweight Python client SDK, and high-performance API reference for Google Trends API powered by APINEED. Fast, structured, and cost-effective data extraction with zero browser automation overhead, automated anti-bot defense, and enterprise gateway reliability.


Managed Gateway: Powered by APINEED

Integrating the Google Trends API into automated data pipelines, autonomous web scrapers, and AI workflows often results in IP blocks, dynamic CAPTCHA challenges, and severe 429 Too Many Requests rate limit errors. Scraping directly without managed proxies requires costly residential IP infrastructure and endless headless browser maintenance.

This repository routes all requests through the APINEED Managed Gateway, giving you rock-solid, production-grade access to Google Trends API:

  • Unified Authentication: A single Bearer API key unlocks Google Trends API along with all APINEED intelligence tools.
  • Dramatic Cost Reduction: Query the service at $0.003125 per request (87.5% more affordable than SerpApi).
  • Automated Anti-Bot Defense: Upstream proxy rotation, browser fingerprint impersonation, and automated CAPTCHA solving are entirely handled by the gateway.
  • Zero Headless Browsers: No Puppeteer, Playwright, or Selenium binaries required—just fast, structured JSON returned directly from the endpoint.
  • Direct Portal Link: Get Instant Google Trends API API Key on APINEED (Free Test Credits Included)

Table of Contents


Executive Overview

The Google Trends API provides high-throughput, structured access to Google's data and intelligence ecosystem. A lightweight, reliable Google Trends API client for Python. Fetch historical interest over time, real-time 24-hour trending topics, regional interest breakdown, and query autocompletions without browser automation, protobuf parsing errors, or rate-limit blocks.

Operating production data scrapers, automated search pipelines, or autonomous AI agent tool callers against Google directly is notoriously difficult. Developers face continuous friction including strict rate limits, geo-blocking, headless browser maintenance overhead, dynamic DOM changes, and aggressive anti-scraping defenses. Furthermore, legacy commercial platforms charge steep enterprise premiums that make high-volume data retrieval financially unsustainable.

The APINEED Managed Gateway solves these operational challenges. By proxying requests through a resilient global infrastructure, the APINEED Google Trends API delivers clean, standardized JSON data with sub-second response times, automated proxy rotation, CAPTCHA bypass, and up to 87.5% cost savings compared to SerpApi.


Key Features & Data Extraction Capabilities

  • Clean Python and REST Interfaces: Predictable JSON responses without internal Google wrapper baggage.
  • Complete Scope Coverage: Supports Interest Over Time, Trending Now (breaking 4h/24h/48h/7d topics), and Autocomplete.
  • Dual Runtime Support: Drop-in client (client.py) and command-line scripts for terminal pipelines.
  • AI Agent Ready: Native integrations for LangChain tools and OpenAI Structured Function Calling.
  • Normalized JSON Output: No cryptic protobuf structures or brittle page parsing.

Installation & Quick Setup

Install the lightweight dependency and clone the repository:

# Install requests (the only required runtime dependency)
pip install requests

# Or clone the official repository
git clone https://github.com/Apineed/google-trends-api.git
cd google-trends-api

Obtain your APINEED API key and set it in your environment:

# Set your APINEED API key in the shell
export APINEED_API_KEY="your_apineed_api_key_here"

# On Windows PowerShell:
# $env:APINEED_API_KEY="your_apineed_api_key_here"

Tip: Sign up at APINEED (Google Trends API) to receive instant API credentials and free test credits.


Python Quickstart & Implementation

Execute queries using the bundled, zero-dependency client.py client:

from client import GoogleTrendsClient

client = GoogleTrendsClient(api_key="your_apineed_api_key")

# Compare search interest over the past 3 months
result = client.interest_over_time(
    query="DeepSeek,OpenAI",
    geo="US",
    date="today 3-m"
)
for point in result.get("data", []):
    print(point["date"], point["values"])

# Real-time trending topics
trending = client.trending_now(geo="US", hours="PAST_24_HOURS", max_results=5)
for item in trending.get("trends", []):
    print(f"- {item['title']} | Vol: {item['search_volume']}+")

API Methods & Reference

The included client.py wrapper encapsulates all REST endpoints for Google Trends API into simple, typed Python methods:

client.interest_over_time(...)

Fetch search interest trend over time or compare terms.

  • Gateway Endpoint: /v1/tools/google_trends_search/invoke
  • HTTP Method: POST
  • Output Return: Clean JSON dictionary containing extracted result attributes.
Parameter Type Required Default Description
query str Yes - Search term(s), comma-separated for comparison
geo Optional[str] No None Two-letter country code
date Optional[str] No "today 3-m" Date window (e.g. today 1-m, today 3-m, now 7-d)
data_type Optional[str] No "INTEREST_OVER_TIME" Output metric
language Optional[str] No "en" Language code

client.trending_now(...)

Fetch current trending searches (breaking topics).

  • Gateway Endpoint: /v1/tools/google_trends_trending_now/invoke
  • HTTP Method: POST
  • Output Return: Clean JSON dictionary containing extracted result attributes.
Parameter Type Required Default Description
geo str No "US" Two-letter country code
hours str No "PAST_24_HOURS" Trend duration: PAST_4_HOURS, PAST_24_HOURS, PAST_7_DAYS
language str No "en" Language code
max_results int No 20 Max items returned (1-100)
max_related_queries int No 10 Max sub-queries per item (0-50)

client.autocomplete(...)

Fetch Google Trends search suggestions.

  • Gateway Endpoint: /v1/tools/google_trends_autocomplete/invoke
  • HTTP Method: POST
  • Output Return: Clean JSON dictionary containing extracted result attributes.
Parameter Type Required Default Description
query str Yes - Partial query for suggestions
language str No "en" Language code

Structured Response Schema

All queries processed by the APINEED Google Trends API gateway return deterministic, standardized JSON objects:

{
  "request_id": "req_trends_7a3b",
  "tool": "google_trends_search",
  "output": {
    "query": "DeepSeek,OpenAI",
    "data": [
      { "date": "2026-06-22", "values": [45, 78] },
      { "date": "2026-06-29", "values": [52, 81] }
    ]
  },
  "usage": { "price_usd": "0.003125", "quota": 312 }
}

AI Agent & RAG Pipeline Integration

Empower autonomous AI agents and Retrieval-Augmented Generation (RAG) systems with real-time intelligence from Google Trends API:

from langchain.tools import tool
from client import GoogleTrendsClient

trends_client = GoogleTrendsClient(api_key="your_api_key")

@tool
def get_search_trends(country_code: str) -> str:
    """Useful for finding hot trending topics and breaking viral news in a specific country."""
    data = trends_client.trending_now(geo=country_code, hours="PAST_24_HOURS", max_results=5)
    return str(data.get("trends", []))

Large-Scale Pagination & Concurrency Guide

When processing high-volume requests with Google Trends API, follow this concurrent execution pattern using Python's built-in concurrent.futures:

import concurrent.futures
from client import GoogleTrendsClient

# Initialize client
client = GoogleTrendsClient()
targets = [
    {"query": "OpenAI,DeepSeek", "date": "today 3-m"},
    {"query": "Claude,Gemini", "date": "today 3-m"},
    {"query": "AI Agents,Automation", "date": "today 3-m"},
]

def process_target(target):
    try:
        return client.interest_over_time(query=target["query"], date=target["date"])
    except Exception as err:
        print(f"Error fetching trends for {target}: {err}")
        return None
# Execute parallel extraction with thread pool
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    results = list(executor.map(process_target, targets))

print(f"Successfully processed {len(results)} queries via Google Trends API.")

Enterprise Production Best Practices

To ensure maximum throughput, stability, and cost-efficiency when deploying Google Trends API in production:

  1. Implement Intelligent Result Caching: Cache repetitive requests using Redis, Memcached, or local LRU cache to reduce latency and save API usage credits.
  2. Handle Transient Network Failures: Use exponential backoff retry algorithms with jitter to gracefully handle occasional network timeouts.
  3. Optimize Result Boundaries: Set result limits (max_results or page) appropriately for LLM contexts to avoid prompt token bloating while preserving semantic relevance.
  4. Environment Variable Management: Never hardcode API keys in source control. Always read credentials via environment variables (APINEED_API_KEY).
  5. Connection Pooling: Use the client's internal requests session for connection reuse across repeated requests.

Cost Comparison: APINEED vs SerpApi

Compare the operational savings of utilizing APINEED for Google Trends API workloads:

Provider Platform Starting Plan Monthly Quota Cost per 1,000 Requests Cost per Individual Request
Unofficial Scrapers Free (until blocked) Unpredictable N/A N/A
SerpApi $25.00 / mo 1,000 $25.00 $0.025
APINEED Pay-As-You-Go Unlimited $3.125 $0.003125 (87.5% Lower)

Key Takeaway: APINEED eliminates steep upfront monthly subscriptions and per-query surcharges, saving up to 87.5% compared to SerpApi.


Direct HTTP cURL Command Reference

You can also interact directly with the Google Trends API gateway using standard cURL commands:

curl -X POST "https://apineed.com/v1/tools/google_trends_trending_now/invoke" \
  -H "Authorization: Bearer YOUR_APINEED_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "geo": "US",
    "hours": "PAST_24_HOURS",
    "max_results": 10
  }'

Security, Privacy & Data Compliance

  • Encrypted in Transit: All interactions with the APINEED Google Trends API are secured using TLS 1.3 encryption.
  • Zero Query Logging Option: APINEED operates a stateless gateway architecture ensuring your search parameters, business intelligence targets, and proprietary customer queries are not permanently stored or harvested.
  • Enterprise SLA: Guaranteed 99.9% uptime SLA backed by redundant multi-region proxy clusters.

Troubleshooting & Status Codes

HTTP Status Diagnosis Resolution
401 Unauthorized Invalid or missing APINEED API key Verify that APINEED_API_KEY is exported and valid on your APINEED dashboard.
400 Bad Request Malformed JSON payload or missing required parameter Validate your request body matches the parameters in the API Methods & Reference.
429 Too Many Requests Concurrency limit reached for your account tier Implement exponential backoff retries or upgrade your account quota on APINEED.
502 / 504 Gateway Delay Upstream data provider timeout Retry the request with standard exponential backoff.

Frequently Asked Questions (FAQ)

Does Google provide an official Google Trends REST API?

No. Google does not offer a public REST API for Google Trends. This library uses APINEED normalized gateway endpoints to return clean, standardized JSON feeds.

How frequently are real-time trends updated?

The trending_now endpoint provides updates every few minutes, tracking breaking search queries over 4-hour, 24-hour, 48-hour, and 7-day windows.

Is this a pytrends alternative?

Yes. Unlike pytrends which scrapes Google Trends directly and frequently breaks due to rate limits and protobuf changes, this library uses the APINEED managed gateway for stable, normalized JSON responses.

Can I compare multiple search terms?

Yes. Pass comma-separated terms to the query parameter (e.g., 'ChatGPT,Claude,Gemini') to compare search interest between terms.


License

This repository, sample code, and the Python client SDK are open-sourced under the permissive MIT License. Free for commercial and non-commercial usage.

About

Lightweight Google Trends API for Python. Interest over time, trending now, autocomplete. 87.5% lower cost than SerpApi.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages