from fastapi import FastAPI from fastapi.responses import JSONResponse from pytrends.request import TrendReq import time app = FastAPI(title="PyTrends API") @app.get("/health") async def health_check(): return {"status": "Health check", "message": "PyTrends API"} @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: return JSONResponse(status_code=429, content={"error": "Rate limited"}) @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: return JSONResponse(status_code=429, content={"error": "Rate limited"}) @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: return JSONResponse(status_code=429, content={"error": "Rate limited"}) @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: return JSONResponse(status_code=429, content={"error": "Rate limited"})