trymonolith commited on
Commit
89c7106
·
verified ·
1 Parent(s): e29a158

Add FastAPI application with pytrends endpoints

Browse files
Files changed (1) hide show
  1. app.py +143 -0
app.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Query
2
+ from pytrends.request import TrendReq
3
+ from fastapi.responses import JSONResponse
4
+ from typing import List, Optional
5
+ import pandas as pd
6
+ import json
7
+
8
+ app = FastAPI(
9
+ title="PyTrends API",
10
+ description="HTTP API for Google Trends data",
11
+ version="1.0.0"
12
+ )
13
+
14
+ # Initialize pytrends
15
+ pytrends = TrendReq(hl="en-US", tz=360)
16
+
17
+ @app.get("/")
18
+ def root():
19
+ return {
20
+ "message": "PyTrends API",
21
+ "endpoints": {
22
+ "/interest_over_time": "Get interest over time for keywords",
23
+ "/interest_by_region": "Get interest by region for keywords",
24
+ "/trending_searches": "Get trending searches for a country",
25
+ "/related_queries": "Get related queries for keywords"
26
+ }
27
+ }
28
+
29
+ @app.get("/interest_over_time")
30
+ def get_interest_over_time(
31
+ kw: List[str] = Query(..., description="Keywords to search"),
32
+ timeframe: str = Query("today 5-y", description="Timeframe for search"),
33
+ geo: str = Query("", description="Geographic location"),
34
+ gprop: str = Query("", description="Google property (images, news, youtube, etc.)"),
35
+ cat: int = Query(0, description="Category")
36
+ ):
37
+ try:
38
+ pytrends.build_payload(
39
+ kw_list=kw,
40
+ timeframe=timeframe,
41
+ geo=geo,
42
+ gprop=gprop,
43
+ cat=cat
44
+ )
45
+ df = pytrends.interest_over_time()
46
+ df = df.drop('isPartial', axis=1)
47
+ data = df.reset_index().to_dict('records')
48
+ # Convert datetime to string for JSON serialization
49
+ for record in data:
50
+ if 'date' in record:
51
+ record['date'] = str(record['date'])
52
+ return {
53
+ "data": data,
54
+ "keywords": kw,
55
+ "timeframe": timeframe,
56
+ "geo": geo
57
+ }
58
+ except Exception as e:
59
+ return JSONResponse(
60
+ status_code=400,
61
+ content={"error": str(e)}
62
+ )
63
+
64
+ @app.get("/interest_by_region")
65
+ def get_interest_by_region(
66
+ kw: List[str] = Query(..., description="Keywords to search"),
67
+ timeframe: str = Query("today 5-y", description="Timeframe for search"),
68
+ geo: str = Query("", description="Geographic location"),
69
+ gprop: str = Query("", description="Google property"),
70
+ resolution: str = Query("country", description="Resolution (country, region, metro, city)")
71
+ ):
72
+ try:
73
+ pytrends.build_payload(
74
+ kw_list=kw,
75
+ timeframe=timeframe,
76
+ geo=geo,
77
+ gprop=gprop
78
+ )
79
+ df = pytrends.interest_by_region(resolution=resolution)
80
+ data = df.reset_index().to_dict('records')
81
+ return {
82
+ "data": data,
83
+ "keywords": kw,
84
+ "resolution": resolution
85
+ }
86
+ except Exception as e:
87
+ return JSONResponse(
88
+ status_code=400,
89
+ content={"error": str(e)}
90
+ )
91
+
92
+ @app.get("/trending_searches")
93
+ def get_trending_searches(
94
+ country: str = Query("united_states", description="Country code (e.g., united_states, india, etc.)")
95
+ ):
96
+ try:
97
+ df = pytrends.trending_searches(pn=country)
98
+ data = df.values.tolist()
99
+ return {
100
+ "trending": data,
101
+ "country": country
102
+ }
103
+ except Exception as e:
104
+ return JSONResponse(
105
+ status_code=400,
106
+ content={"error": str(e)}
107
+ )
108
+
109
+ @app.get("/related_queries")
110
+ def get_related_queries(
111
+ kw: List[str] = Query(..., description="Keywords to search"),
112
+ timeframe: str = Query("today 5-y", description="Timeframe for search"),
113
+ geo: str = Query("", description="Geographic location")
114
+ ):
115
+ try:
116
+ pytrends.build_payload(
117
+ kw_list=kw,
118
+ timeframe=timeframe,
119
+ geo=geo
120
+ )
121
+ related = pytrends.related_queries()
122
+ result = {}
123
+ for kw_item in kw:
124
+ if kw_item in related:
125
+ top_queries = related[kw_item]['top']
126
+ rising_queries = related[kw_item]['rising']
127
+ result[kw_item] = {
128
+ "top": top_queries.reset_index().to_dict('records') if top_queries is not None else [],
129
+ "rising": rising_queries.reset_index().to_dict('records') if rising_queries is not None else []
130
+ }
131
+ return {
132
+ "related_queries": result,
133
+ "keywords": kw
134
+ }
135
+ except Exception as e:
136
+ return JSONResponse(
137
+ status_code=400,
138
+ content={"error": str(e)}
139
+ )
140
+
141
+ @app.get("/health")
142
+ def health_check():
143
+ return {"status": "healthy"}