pytrends-api-2 / app.py
trymonolith's picture
Create app.py
47953fc verified
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pytrends.request import TrendReq
import asyncio
import time
app = FastAPI(title="PyTrends API")
@app.get("/health")
async def health_check():
return {"status": "Health check endpoint", "message": "Get interest over time for keywords", "interest_by_region": "Get interest by region for keywords", "trending_searches": "Get trending queries for a keywords", "related_queries": "Get related queries for keywords", "note": "If you get a 429 error, Google Trends is rate limiting. Wait a few minutes and try again."}
@app.get("/interest_over_time")
async def interest_over_time(keyword: str):
try:
pytrends = TrendReq(hl='en-US', tz=360)
time.sleep(0.5)
pytrends.build_payload([keyword], timeframe='today 12-m')
df = pytrends.interest_over_time()
return {"data": df.to_dict()}
except Exception as e:
return JSONResponse(status_code=429, content={"error": str(e), "note": "If you get a 429 error, Google Trends is rate limiting. Wait a few minutes and try again."})
@app.get("/interest_by_region")
async def interest_by_region(keyword: str):
try:
pytrends = TrendReq(hl='en-US', tz=360)
time.sleep(0.5)
pytrends.build_payload([keyword])
df = pytrends.interest_by_region()
return {"data": df.to_dict()}
except Exception as e:
return JSONResponse(status_code=429, content={"error": str(e), "note": "If you get a 429 error, Google Trends is rate limiting. Wait a few minutes and try again."})
@app.get("/trending_searches")
async def trending_searches():
try:
pytrends = TrendReq(hl='en-US', tz=360)
time.sleep(0.5)
df = pytrends.trending_searches(pn='united_states')
return {"data": df.to_dict()}
except Exception as e:
return JSONResponse(status_code=429, content={"error": str(e), "note": "If you get a 429 error, Google Trends is rate limiting. Wait a few minutes and try again."})
@app.get("/related_queries")
async def related_queries(keyword: str):
try:
pytrends = TrendReq(hl='en-US', tz=360)
time.sleep(0.5)
pytrends.build_payload([keyword])
df = pytrends.related_queries()
return {"data": str(df)}
except Exception as e:
return JSONResponse(status_code=429, content={"error": str(e), "note": "If you get a 429 error, Google Trends is rate limiting. Wait a few minutes and try again."})