Spaces:
Sleeping
Sleeping
File size: 2,488 Bytes
47953fc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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."}) |