33import requests
44import pandas as pd
55
6-
76API_URL = "https://love-the-air.herokuapp.com/api"
8- pd .DataFrame ()
97
108
119def get_states () -> List [str ]:
@@ -18,14 +16,11 @@ def get_states() -> List[str]:
1816 >>> states
1917 ['Andhra Pradesh','Karnataka', 'Assam',....]
2018 """
21- try :
22- r = requests .get (f'{ API_URL } /states' )
23- status = r .status_code
24- if status != 200 :
25- Exception (f'failed to fetch states { r .status_code } ' )
26- return r .json ()['states' ]
27- except Exception as e :
28- print (e )
19+ r = requests .get (f'{ API_URL } /states' )
20+ status = r .status_code
21+ if status != 200 :
22+ raise Exception (f'failed to fetch states { r .status_code } ' )
23+ return r .json ()['states' ]
2924
3025
3126def get_cities (state : str ) -> List [str ]:
@@ -46,14 +41,11 @@ def get_cities(state: str) -> List[str]:
4641 >>> cities
4742 ['Eloor', 'Ernakulam', 'Kannur', 'Kochi', 'Kollam', 'Kozhikode', 'Thiruvananthapuram']
4843 """
49- try :
50- r = requests .get (f'{ API_URL } /state/{ state } ' )
51- status = r .status_code
52- if status != 200 :
53- Exception (f'failed to fetch cities with status:{ status } ' )
54- return r .json ()['cities' ]
55- except Exception as e :
56- print (e )
44+ r = requests .get (f'{ API_URL } /state/{ state } ' )
45+ status = r .status_code
46+ if status != 200 :
47+ raise Exception (f'failed to fetch cities with status:{ status } ' )
48+ return r .json ()['cities' ]
5749
5850
5951def get_stations (city : str ) -> List [dict ]:
@@ -73,14 +65,11 @@ def get_stations(city: str) -> List[dict]:
7365 >>> stations
7466 [{'id': 'site_5334', 'live': True, 'name': 'Polayathode, Kollam - Kerala PCB'}]
7567 """
76- try :
77- r = requests .get (f'{ API_URL } /city/{ city } ' )
78- status = r .status_code
79- if status != 200 :
80- Exception (f'failed to fetch stations with status:{ status } ' )
81- return r .json ()['stations' ]
82- except Exception as e :
83- print (e )
68+ r = requests .get (f'{ API_URL } /city/{ city } ' )
69+ status = r .status_code
70+ if status != 200 :
71+ raise Exception (f'failed to fetch stations with status:{ status } ' )
72+ return r .json ()['stations' ]
8473
8574
8675def get_data (from_date : str , to_date : str ,
@@ -123,31 +112,71 @@ def get_data(from_date: str, to_date: str,
123112 "station_id" : station_id ,
124113 "criteria" : criteria
125114 }
126- try :
127- r = requests .post (f'{ API_URL } /data' , json = payload )
128- status = r .status_code
129- if status == 422 :
130- print (r .json ())
131- elif status == 200 :
132- return _format (json = r .json ())
133- except Exception as e :
134- print (e )
135-
136-
137- def _format (json : dict ) -> pd .DataFrame :
115+ r = requests .post (f'{ API_URL } /data' , json = payload )
116+ status = r .status_code
117+ if status == 422 :
118+ print (r .json ())
119+ elif status == 200 :
120+ return _format (json_data = r .json ())
121+
122+
123+ def _format (json_data : dict ) -> pd .DataFrame :
138124 """
139125 Return a well formatted Dataframe from json
140126
141127 Parameters
142128 ----------
143- json: json response from request response
129+ json_data: json response from request response
130+ """
131+ data = json_data ['data' ]
132+ if not data :
133+ raise Exception ("API returned empty data" )
134+ else :
135+ df = pd .DataFrame (data = data ).drop ('exceeding' , axis = 1 )
136+ columns = []
137+ for _ , col in enumerate (df .columns ):
138+ if '_' in col :
139+ col = col .split ('_' )[- 1 ]
140+ columns .append (col )
141+ df .columns = columns
142+ return df
143+
144+ def save_data (path : str , from_date : str , to_date : str ,
145+ station_id : str , criteria : str ):
146+ """
147+ wrapper around get data method to save
148+ data into a file
149+
150+ Parameters
151+ ----------
152+ path : path to store file
153+ from_date : str/ISO datetime
154+ Starting Date from which data is required
155+ to_date : str/ISO datetime
156+ End Date until which the date is required
157+ station_id : str
158+ Station Id as listed in the station dictionary
159+ criteria: str
160+ Frequency of data required
161+ Supported Criteria
162+ - 24 Hours
163+ - 8 Hours
164+ - 4 Hours
165+ - 1 Hours
166+ - 30 Minute
167+ - 15 Minute
144168 """
145- data = json ['data' ]
146- df = pd .DataFrame (data = data ).drop ('exceeding' , axis = 1 )
147- columns = []
148- for _ , col in enumerate (df .columns ):
149- if '_' in col :
150- col = col .split ('_' )[- 1 ]
151- columns .append (col )
152- df .columns = columns
153- return df
169+ formats = ['csv' , 'xlsx' , 'json' ]
170+ ff = path .split ('.' )[- 1 ]
171+ df = get_data (from_date = from_date ,
172+ to_date = to_date ,
173+ station_id = station_id ,
174+ criteria = criteria )
175+ if ff not in formats :
176+ raise Exception (f'FileFormat { ff } Not Supported!' )
177+ if ff == 'csv' :
178+ df .to_csv (path , index = False )
179+ elif ff == 'excel' :
180+ df .to_excel (path , index = False )
181+ elif ff == 'json' :
182+ df .to_json (path , index = False )
0 commit comments