Last modified: Feb 01, 2026 By Alexander Williams
Google Trends API Python Guide & Tutorial
Google Trends is a powerful tool. It shows what the world is searching for. You can access this data programmatically. Python makes it easy. This guide will show you how.
We will use the unofficial pytrends library. It interacts with Google Trends. You can pull data for analysis. This is useful for marketers, researchers, and developers.
What is the Google Trends API?
Google Trends visualizes search interest. The API provides access to this data. It is not an official public API. The pytrends library simulates browser requests.
You can track keyword popularity over time. Compare multiple search terms. Analyze interest by region. The data is normalized from 0 to 100.
This is invaluable for market research and content strategy. Understanding this data flow is a key part of any Python API data pulling skill set.
Setting Up Your Python Environment
First, you need Python installed. Then, install the required library. Use pip, the Python package installer.
pip install pytrends
You may also want pandas for data handling. Install it if you don't have it.
pip install pandas
Now, you are ready to start coding. Create a new Python file. Import the necessary modules.
Connecting to Google Trends
Start by importing pytrends. Create a connection object. This object will handle all requests.
from pytrends.request import TrendReq
# Create a connection
pytrends = TrendReq(hl='en-US', tz=360)
# hl: language, tz: timezone offset (e.g., 360 for CST)
The TrendReq constructor sets up the connection. Parameters like hl (host language) and tz (timezone) are important. They affect the data returned.
Building a Payload and Fetching Data
You must build a payload. This defines your data query. Specify keywords, timeframe, and geography.
# Build payload
kw_list = ["Python", "JavaScript"]
pytrends.build_payload(kw_list, cat=0, timeframe='today 12-m', geo='', gprop='')
The build_payload method prepares your request. The kw_list contains your search terms. The timeframe can be 'now 1-H', 'today 5-y', or a custom date range like '2023-01-01 2023-12-31'.
After building the payload, you can fetch data. The main method for this is interest_over_time.
# Fetch interest over time data
interest_over_time_df = pytrends.interest_over_time()
print(interest_over_time_df.head())
Python JavaScript isPartial
date
2023-05-28 67 33 False
2023-06-04 68 32 False
2023-06-11 66 34 False
2023-06-18 70 30 False
2023-06-25 69 31 False
The result is a pandas DataFrame. It shows normalized interest scores. The isPartial column indicates if data for that date is incomplete.
Exploring Key API Methods
The pytrends library offers several useful methods. Each serves a different analytical purpose.
Interest by Region
See where keywords are most popular. Use the interest_by_region method.
# Get interest by region
region_df = pytrends.interest_by_region(resolution='COUNTRY', inc_low_vol=True)
print(region_df.sort_values(by='Python', ascending=False).head())
This helps with geographic targeting. It's crucial for localized campaigns.
Related Queries
Discover what else people search for. The related_queries method returns top and rising queries.
# Get related queries
related_queries_dict = pytrends.related_queries()
print(related_queries_dict['Python']['top'].head())
This is great for keyword research. It reveals search intent and content opportunities.
Real-Time Trends
Fetch trending searches in real-time. Use the trending_searches method.
# Get daily trending searches
trending_df = pytrends.trending_searches(pn='united_states') # pn is country
print(trending_df.head())
This is perfect for newsjacking or social media monitoring.
Building a Practical Example
Let's create a script. It will compare three programming languages. We will plot their interest over the past year.
import matplotlib.pyplot as plt
# Setup
pytrends = TrendReq(hl='en-US', tz=360)
kw_list = ["Python", "Java", "C++"]
pytrends.build_payload(kw_list, timeframe='2023-01-01 2023-12-31')
# Get data
data = pytrends.interest_over_time()
# Plot
data.drop(columns=['isPartial']).plot(figsize=(12, 6), linewidth=2)
plt.title('Programming Language Search Interest (2023)')
plt.ylabel('Relative Interest')
plt.xlabel('Date')
plt.grid(True)
plt.tight_layout()
plt.show()
This script fetches a full year of data. It then creates a clear line chart. Visualization makes trend analysis immediate.
Handling the numerical data from APIs correctly is essential. For more on this, see our Python API number handling guide.
Best Practices and Limitations
Google Trends data is normalized. A score of 100 means peak popularity. A score of 50 means half as popular. You cannot compare absolute search volumes.
The unofficial API has limits. Google may block excessive requests. Always add delays between calls. Use time.sleep() to be polite.
import time
# ... make a request ...
time.sleep(2) # Wait 2 seconds before next call
Handle errors gracefully. Network issues or rate limits can occur. Use try-except blocks in your code.
For building robust systems that use such APIs, understanding Python API frameworks is highly beneficial.