Getting weather report using OpenWeather Map API

Python is a very popular language that can be used to perform a wide variety of tasks. We can use python to perform operations like Machine Learning, Data Science, web applications, Mobile applications, Automation, etc., very easily. In this tutorial, we will use python to access weather data from an API for a specific area.

To follow this tutorial, it is recommended to have a stable version of python 3 installed in your system. It is also recommended to use an IDE for writing the code. I am using the open-source Visual Studio code, one of the best cross-platform IDE for writing code.

Basic Requirements

In this tutorial, we were going to use the OpenWeatherMap API. The OpenWeatherMap API is a service that provides weather data including, current weather data, historical weather data, weather forecast, etc., to developers. So, they can integrate weather reports into their application. Though OpenWeatherMap API is a paid service, it also provides a free tier in which we cannot make more than 60 API calls per minute. So, to use the OpenWeatherMap, we need to get the API key found on the OpenWeatherMap website.

To access the API, we will use the requests library of python. Unfortunately, the request library is not present in the standard library of python, so we need to install it manually. We can install the requests library by using the pip package manager of python. Run the following command in your terminal.

pip install requests

Running the above command will install the requests library in our environment. You can check your installation by opening the python shell and running the code import requests in the shell as I did in the following image.

checking the installation of requests module by importing it
checking the installation of requests module by importing it

We will also use the JSON module of python to parse the JSON data returned by the OpenWeatherMap API. The JSON module comes with the python standard library, so we don’t have to perform any manual installation for the JSON library.

Getting the data using the requests library

We will use the requests library of python to send a get request at the OpenWeatherMap API. See the following code for demonstration.

# importing the required libraries
import requests
# Enter the api key of openweathermap here
api_key = "Add Your Api Key"
# Base url for the open map api
root_url = "http://api.openweathermap.org/data/2.5/weather?"
# City name for which we need the weather data
city_name = "bangalore"
# Building the final url for the API call
url = f"{root_url}appid={api_key}&q={city_name}"
# sending a get request at the url
r = requests.get(url)
# displaying the json weather data returned by the api
print(r.json())

In the above code, we first imported the request library into our code. The requests library has a get() function that can be used to send a GET request to a URL. We built a URL for the API call by adding the city name and the API key to the URL and use the get() function to send a GET request to the API. At last, we use the json() method of the response object in the argument of the print() function to display the JSON content returned by the API into the console. On running the above code, we will get the output as shown in the below image.

returned json data from the openweathermap api
returned JSON data from the OpenWeatherMap API

Parsing the Json data

We have displayed the raw JSON data that has been returned by the OpenWeatherMap API. But raw JSON data is tough to be read by users, so we need to parse it and transform it into human-readable form. The following code parses the JSON data returned by the API and displays some important weather information in a readable format. Add the following code to the last line in the previous code block.

# storing the returned json data into a variable
data = r.json()
# Checking If there is no error and the status code is 200
if data['cod'] == 200:
    # getting the temperature from the json data
    temp = data['main']['temp']
    # getting the pressure from the json data
    pressure = data['main']['pressure']
    # getting the humidity from the json data
    humidity = data['main']['humidity']
    # getting the description from the json data
    descr = data['weather'][0]['description']
    # getting the wind speed from the json data
    wind = data['wind']['speed']
    # Displaying all the data
    print(f"City Name : {city_name}")
    print(f"The Weather Condition is {descr}")
    print(f"The temperature is {temp}kelvin")
    print(f"The pressure is {pressure}hPa")
    print(f"The humidity is {humidity}%")
    print(f"The speed of wind is {wind}m/s")
else:
    # If any error occured then print this
    print("Something Went Wrong")

In the above code block, we first store the returned JSON data into a variable. The JSON data is stored in the form of a dictionary, so we access the required parameters like temperature, pressure, humidity, etc., by providing the keys of those values in the index. At last, we displayed the report using the print() function of python. On running the above code, we will get the output as shown in the below image.

parsing the json data returned by the oenweathermap api
parsing the JSON data returned by the OpenWeatherMap API

The final code

Let us build our final code, this code will prompt the user to enter a city name, and the program will display the weather information for that city. Look at the below code.

# importing the required libraries
import requests
# Enter the api key of openweathermap here
api_key = "Add Your Api Key"
# Base url for the open map api
root_url = "http://api.openweathermap.org/data/2.5/weather?"
# Input the City name for which we need the weather data
city_name = input("Please Enter The City Name : ")
# Building the final url for the API call
url = f"{root_url}appid={api_key}&q={city_name}"
# sending a get request at the url
r = requests.get(url)
# storing the returned json data into a variable
data = r.json()
# Checking If there is no error and the status code is 200
if data['cod'] == 200:
    # getting the temperature from the json data
    temp = data['main']['temp']
    # getting the pressure from the json data
    pressure = data['main']['pressure']
    # getting the humidity from the json data
    humidity = data['main']['humidity']
    # getting the description from the json data
    descr = data['weather'][0]['description']
    # getting the wind speed from the json data
    wind = data['wind']['speed']
    # Displaying all the data
    print(f"City Name : {city_name}")
    print(f"The Weather Condition is {descr}")
    print(f"The temperature is {temp}kelvin")
    print(f"The pressure is {pressure}hPa")
    print(f"The humidity is {humidity}%")
    print(f"The speed of wind is {wind}m/s")
else:
    # If any error occured then print this
    print("Something Went Wrong")

This is the final built program. On running the above program, we will get the output as shown in the below image.

the final code where the user will prompt to enter city name and the weather information will be displayed
the final code where the user will prompt to enter the city name, and the weather information will be displayed

Conclusion

In this tutorial, we have built a program that will take the city name as input from the user and then displays the weather information for that city. You may also want to see our tutorial on creating and reading Qr codes in python.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *