In this project, you’ll learn how to create a Weather notification project in python that fetches real-time weather data from open weather map api and delivers customizable weather notifications to keep you informed and prepared.
This weather app project that we are building displays the current weather conditions for a given city entered by a user.
In this project we are using the OpenWeatherMap API which provides weather data for different cities around the world. To use the API, we need to provide an API key that is unique to our account. We assign our API key to the api_key variable in the program below.
Here the user is asked to enter the name of the city for which they want to query the weather information once the user inputs the city name it is assigned to a city variable.
Next, A URL for the API endpoint is constructed by formatting the city and api_key variables into the URL string.
python requests
library is used to send the GET
request to the API endpoint using the requests.get()
function by passing in the URL as an argument.
The response
variable contains the server`s response to our request.
If the server response status code is 200
from the server it indicates a successful response, Once we get the successful response, we convert the response data to JSON format using the response.json()
function and assign it to the data variable. We then use the print function to print out the relevant weather information for the city, which includes the temperature, feels like the temperature, and weather description.
If the response status code is not 200, we print an error message indicating the status code and reason for the failure.
To configure an API key visit https://openweathermap.org/appid OpenWeatherMap link to grab your developer key which is so good and yet free.
# install requests library
import requests
api_key = 'd45e2043a4446121012b702d2b214b21'
while True:
city = input('Enter city name (or type "exit" to quit): ')
if city.lower() == 'exit':
print('Exiting weather app')
break
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(f"Weather information for {city}:")
print(f"Temperature: {data['main']['temp']}°C")
print(f"Feels like: {data['main']['feels_like']}°C")
print(f"Weather description: {data['weather'][0]['description']}")
else:
print(f"Error: {response.status_code} - {response.reason}")