Building a Weather App using Python and API


Building a Weather App using an API is a great project to practice working with APIs, handling JSON data, and displaying it dynamically in a Python application. Below is a step-by-step guide to build a simple weather app that fetches weather data from a public weather API and displays it to the user.

Steps to Build a Weather App using Python

Install Required Libraries

You'll need the requests library to interact with the API.

Optionally, you can use tkinter for creating a graphical user interface (GUI).

Install requests using:

pip install requests

Get an API Key

Sign up for a free account at a weather API provider like OpenWeatherMap.

Go to OpenWeatherMap and get your free API key.

The API endpoint you will use is: http://api.openweathermap.org/data/2.5/weather.

Step 1: Basic Weather App with Console Output

Python Code to Fetch Weather Data

Here's the basic script that fetches and displays weather data in the console:

import requests

# Function to get weather data
def get_weather(city, api_key):
    # Define the URL for OpenWeatherMap API
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"

    # Send GET request to fetch the weather data
    response = requests.get(url)

    # If the response is successful
    if response.status_code == 200:
        data = response.json()
        
        # Extract relevant information
        main = data['main']
        weather = data['weather'][0]
        
        temperature = main['temp']
        pressure = main['pressure']
        humidity = main['humidity']
        description = weather['description']
        
        # Print the weather data
        print(f"Weather in {city}:")
        print(f"Temperature: {temperature}°C")
        print(f"Pressure: {pressure} hPa")
        print(f"Humidity: {humidity}%")
        print(f"Description: {description}")
    else:
        print("City not found. Please try again!")

# Main execution
if __name__ == "__main__":
    city = input("Enter city name: ")
    api_key = 'YOUR_API_KEY'  # Replace with your OpenWeatherMap API key
    get_weather(city, api_key)

How the Code Works:

  • The user inputs the city name.
  • The requests.get method sends a request to the OpenWeatherMap API and retrieves the data in JSON format.
  • The relevant weather information like temperature, humidity, and description is extracted from the JSON response.
  • If the city is valid, the weather details are displayed in the console. Otherwise, an error message is shown.

Example Output:

Enter city name: London
Weather in London:
Temperature: 15°C
Pressure: 1010 hPa
Humidity: 78%
Description: clear sky

Step 2: Enhance the App with GUI Using Tkinter (Optional)

For a more interactive app, we can use Tkinter (built-in Python library) to create a GUI.

Install Tkinter (if not already installed)

Tkinter is included by default in Python distributions, but if it's not installed, you can install it with:

pip install tk

Python Code for GUI Weather App

import tkinter as tk
import requests

# Function to get weather data
def get_weather():
    city = city_entry.get()
    api_key = 'YOUR_API_KEY'  # Replace with your OpenWeatherMap API key
    
    # URL for OpenWeatherMap API
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    
    # Send GET request to the API
    response = requests.get(url)
    
    if response.status_code == 200:
        data = response.json()
        main = data['main']
        weather = data['weather'][0]
        
        temperature = main['temp']
        pressure = main['pressure']
        humidity = main['humidity']
        description = weather['description']
        
        # Update the result label with weather information
        result_label.config(text=f"Temperature: {temperature}°C\nPressure: {pressure} hPa\nHumidity: {humidity}%\nDescription: {description}")
    else:
        result_label.config(text="City not found. Please try again!")

# Setting up the Tkinter window
window = tk.Tk()
window.title("Weather App")

# Input field for city name
city_label = tk.Label(window, text="Enter city name:")
city_label.pack()

city_entry = tk.Entry(window)
city_entry.pack()

# Button to fetch weather data
get_weather_button = tk.Button(window, text="Get Weather", command=get_weather)
get_weather_button.pack()

# Label to display the results
result_label = tk.Label(window, text="", font=('Arial', 12))
result_label.pack()

# Start the Tkinter event loop
window.mainloop()

How the GUI App Works:

  • The user inputs the city name in a text field.
  • The user clicks the "Get Weather" button.
  • The app sends a request to the OpenWeatherMap API and updates the label with the weather details if the city is valid.
  • If the city is invalid, an error message is shown.

Example GUI Output:

Once you enter the city name and press Get Weather, the app will display:

Temperature: 15°C
Pressure: 1010 hPa
Humidity: 78%
Description: clear sky

Step 3: Enhance the App with Additional Features

  • Add a Refresh Button: Create a button to refresh the weather details for the current city.
  • Error Handling: Handle edge cases such as invalid API keys, invalid city names, etc.
  • Location by Coordinates: Allow users to get weather by geographical coordinates (latitude and longitude) instead of city name.
  • Graphical Visualization: Use a library like Matplotlib to display temperature trends or forecast data visually.

Final Thoughts

Building this weather app allows you to practice key programming concepts like working with APIs, handling JSON, and creating graphical user interfaces. You can further enhance the app by adding features such as forecasts, temperature graphs, or background images that change based on the weather condition.