A Python script talks to Trends API with requests. POST https://api.trendsapi.ai/api, Authorization: Bearer, JSON body with mode and source. The envelope is {"statusCode": int, "body": string}. body is a JSON string and must be parsed a second time. Official pip install trendsapi decodes that envelope. This page is the raw path. A Session is optional and worth it on a keyword list. Timeouts belong on the client. Cookie knobs from scrape libraries do not apply. SDK install and GitHub: Trends API SDKs. Field names: the API reference. Plan text: pricing.
pip install requests for the raw path
pip install requests
That is the dependency for this tutorial. The official package is pip install trendsapi from trendsapi-ai/TrendsAPI-py. Use that when the script should not see statusCode or a string body. The product MCP server at https://api.trendsapi.ai/mcp is a different runtime for agents. A batch job still uses HTTP.
Session reuse for a keyword list
import json
import os
import requests
session = requests.Session()
session.headers.update({
"Authorization": f"Bearer {os.environ['TRENDSAPI_KEY']}",
"Content-Type": "application/json",
})
def growth(keyword):
resp = session.post(
"https://api.trendsapi.ai/api",
json={
"mode": "get_growth",
"source": "google search",
"keyword": keyword,
"percent_growth": ["3M", "12M"],
},
timeout=60,
)
resp.raise_for_status()
outer = resp.json()
return json.loads(outer["body"])
# Labeled sample keywords, not a live pull
for term in ("bitcoin", "ethereum"):
print(term, growth(term).get("results", [])[:1])
One Session keeps TLS warm. A new requests.post per term still works. It is slower on a long list.
raise_for_status then json.loads body
raise_for_status catches 401 and 429 on the HTTP layer. statusCode inside a 200 envelope is the inner job. Only after the second parse do results or a series exist as objects. Do not print(resp.text) and stop.
Timeouts and retries that are not cookie knobs
timeout=60 is an HTTP timeout. It is not hl or tz. On 429, sleep with jitter and read pricing. Rotating headers will not mint a new plan. Failed non-200s do not count as successful calls.