Application Programming Interface or APIs allow us to fetch data from a particular website or application. It serves as a link to get data from a particular URL. In this blog, I will illustrate the use of weather API to develop a weather application in Python. I will use this API to fetch data of weather of a particular city.
The idea is to create a class that takes in the name of a city. The class will contain a method that will print out the details like Temperature and Humidity of that user-input city.
Registering with OpenWeatherMap
First things first, to use any API, one needs an API-key which is unique and should be maintained confidential. For the weather API, OpenWeatherMap provides the service, and I was able to get my unique API by signing up on their website. It will be useful later in my Python code.
Python Code
Once I had my API-key, I saved it and started with my Python code. I initially started by importing the Python library requests which is famous for API based Python applications. It allows us to access data from a particular URL.
import requests
Next, I created a Class called CityWeather, to which the argument city needs to be passed. It is better to make this project object-oriented as this allows us to create objects for multiple cities and enhances its reusability.
Class CityWeather:
def __init__(self, city) -> None:
self.city = city
self.api_key = API_KEY # Replace with your OpenWeatherMap API key
self.base_url = "https://api.openweathermap.org/data/2.5/weather?q={}&appid={}".format(self.city, self.api_key)
params = {
"q": self.city,
"appid": self.api_key,
"units": "metric" # You can change the units to "imperial" for Fahrenheit
}
response = requests.get(self.base_url, params=params)
self.weather_data = response.json()
As seen in the code, parameters like the name of the city, the API key and units is passed on before accessing the URL. Subsequently, I request the data using get() function of the requests module and pass the URL and the initialized parameters as arguments. The response from the link is then stored as a JSON data.
Additionally, I created a method get_weather() that will print out the weather details that is stored in the variable weather_data.
def get_weather(self):
if self.weather_data["cod"] == "404":
print("City not found!")
else:
main_weather = self.weather_data["weather"][0]["main"]
description = self.weather_data["weather"][0]["description"]
temperature = self.weather_data["main"]["temp"]
humidity = self.weather_data["main"]["humidity"]
print(f"Weather in {self.city}:")
print(f"Main weather: {main_weather}")
print(f"Description: {description}")
print(f"Temperature: {temperature}°C")
print(f"Humidity: {humidity}%")
Because the response received from the URL was in JSON format, I separated the entities by calling the respective keys in weather_data. This is seen in the code from line 5 to 8. Every data is then printed as a result. Alternatively, I could also have returned those entity instead of printing it. The following figure illustrates the output of the entire program:
Summary
To summarize, I demonstrated the use of weather API to get weather details of a particular city. APIs, in this way, get be used to access different types of data. Another fun exercise I carried out was using ChatGPT API in Python program and using it on a website that I created using Flask. I wrote a blog on the experience which you can check it out here.
If you enjoyed reading this, show your support by subscribing to the MLS newsletter.