Build a Simple Weather App in Python Using OpenWeatherMap API

In this tutorial, we’ll create a simple weather app in Python that fetches real-time weather data from the OpenWeatherMap API. This app will allow users to input a city name and display the location’s current temperature, humidity, and weather description. By the end of this tutorial, you’ll have a functional weather app and a better understanding of how to work with APIs in Python.

Pre-requisites

Before we begin, make sure you have the following installed on your system:

  1. Python 3.x
  2. A text editor or IDE of your choice

Additionally, you’ll need an API key from OpenWeatherMap, which you can obtain by creating a free account on their website (https://openweathermap.org/).

Now, let’s dive in!

Part 1: Setting up the Project

First, let’s set up a virtual environment for our project:

python3 -m venv weather-app-env
source weather-app-env/bin/activate

Next, install the ‘requests’ library, which we’ll use to make API calls:

pip install requests

Create a new file called weather_app.py and open it in your text editor or IDE.

Part 2: Importing Libraries and Setting API Key

At the beginning of the weather_app.py file, import the necessary libraries and set your OpenWeatherMap API key as follows:

import requests
import json

API_KEY = 'your_api_key_here'

Replace ‘your_api_key_here’ with the API key you obtained from OpenWeatherMap.

Part 3: Define Functions to Fetch and Display Weather Data

Now let’s define two functions: fetch_weather_data() and display_weather_data().

fetch_weather_data() will take a city name as input and make an API call to OpenWeatherMap to fetch the weather data for that city. The function should return the JSON response.

def fetch_weather_data(city):
    base_url = 'http://api.openweathermap.org/data/2.5/weather?'
    complete_url = f"{base_url}appid={API_KEY}&q={city}"
    response = requests.get(complete_url)
    return response.json()

Next, let’s create the display_weather_data() function. This function will take the JSON response from fetch_weather_data() as input, extract the relevant information, and display it in a user-friendly format.

def display_weather_data(weather_data):
    if weather_data['cod'] != '404':
        main_data = weather_data['main']
        # Convert from Kelvin to Celsius
        temperature = main_data['temp'] - 273.15 
        humidity = main_data['humidity']
        weather_description = weather_data['weather'][0]['description']

        print(f"Temperature: {temperature:.2f}°C")
        print(f"Humidity: {humidity}%")
        print(f"Weather description: {weather_description.capitalize()}")

    else:
        print("City not found. Please try again.")

Part 4: Main Function and User Interaction

Now we’ll create a main function to handle user input and call our previously defined functions.

def main():
    city = input("Enter the name of the city: ")
    weather_data = fetch_weather_data(city)
    display_weather_data(weather_data)

Finally, call the main function to run our weather app:

if __name__ == "__main__":
    main()

Your complete weather_app.py file should look like this:

import requests
import json

API_KEY = 'your_api_key_here'

def fetch_weather_data(city):
    base_url = 'http://api.openweathermap.org/data/2.5/weather?'
    complete_url = f"{base_url}appid={API_KEY}&q={city}"
    response = requests.get(complete_url)
    return response.json()

def display_weather_data(weather_data):
    if weather_data['cod'] != '404':
        main_data = weather_data['main']
        # Convert from Kelvin to Celsius
        humidity = main_data['humidity']
        temperature = main_data['temp'] - 273.15  
        weather_description = weather_data['weather'][0]['description']

        print(f"Temperature: {temperature:.2f}°C")
        print(f"Humidity: {humidity}%")
        print(f"Weather description: {weather_description.capitalize()}")

    else:
        print("City not found. Please try again.")

def main():
    city = input("Enter the name of the city: ")
    weather_data = fetch_weather_data(city)
    display_weather_data(weather_data)

if __name__ == "__main__":
    main()

Save the file and run it in your terminal:

python weather_app.py

You should now see a prompt to enter a city name. Type in a city and press Enter to see the current weather data for that location.

Part 5: Conclusion

Congratulations! You’ve just built a simple weather app in Python using the OpenWeatherMap API. This project demonstrates how to make API calls, handle JSON data, and display information in a user-friendly format. You can enhance this app by implementing error handling, adding a graphical user interface, or incorporating weather data such as wind speed and direction.

As you continue to explore APIs and Python development, you’ll discover countless opportunities to create exciting and useful applications. Keep learning, experimenting, and building projects to sharpen your skills and bring your ideas to life. Good luck, and happy coding!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s