-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather_api.py
52 lines (45 loc) · 1.59 KB
/
weather_api.py
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
import requests
from dotenv import load_dotenv
import os
load_dotenv()
class WeatherAPI:
"""
Manages the interface for fetching weather data from a remote API.
"""
def fetch_data(self, city, country):
"""
Abstract method to be implemented by subclasses.
Args:
city (str): Name of the city.
country (str): Name of the country.
Returns:
dict or None: Weather data fetched from the API or None if fetch fails.
"""
raise NotImplementedError("Subclasses should implement this method")
class RapidAPIWeather(WeatherAPI):
"""
Implements WeatherAPI using the RapidAPI Weather API.
"""
def fetch_data(self, city, country):
"""
Fetches weather data from the RapidAPI Weather API.
Args:
city (str): Name of the city.
country (str): Name of the country.
Returns:
dict or None: Weather data fetched from the API or None if fetch fails.
"""
url = "https://weatherapi-com.p.rapidapi.com/forecast.json"
querystring = {"q": f"{city},{country}", "days": "3"}
headers = {
"X-RapidAPI-Key": os.getenv('RAPIDAPI_KEY'),
"X-RapidAPI-Host": os.getenv('RAPIDAPI_HOST')
}
try:
response = requests.get(url, headers=headers, params=querystring)
response.raise_for_status()
data = response.json()
return data
except requests.exceptions.RequestException as e:
print(f"Error fetching data: {e}")
return None