πŸŽ‰ Welcome to PyVerse! Start Learning Today

Weather App using OpenWeatherMap API

Intermediate

Build a real-time weather application with Python APIs

1) Project Overview

The Weather App fetches real-time weather information (temperature, humidity, weather description, etc.) for any city using the OpenWeatherMap API.

Users simply type the name of a city, and the program displays:

  • 🌑️ Temperature
  • πŸ’§ Humidity
  • πŸŒ₯️ Weather condition
  • 🌬️ Wind speed

πŸ’‘ Why it's useful: Understanding weather conditions is one of the most common use-cases for APIs. This project teaches how to connect Python with external data sources, handle JSON responses, and display meaningful results.

2) Learning Objectives

By completing this project, learners will master:

ConceptDescription
APIs (Application Programming Interfaces)How to fetch live data from the web using HTTP requests
HTTP requests with requestsLearn to make GET requests and handle API responses
JSON data handlingParse and extract data from JSON (JavaScript Object Notation)
Error handlingManage invalid city names or network errors gracefully
Functions and Code ReusabilityWrite modular, reusable, and well-structured functions
Formatted OutputPresent real-time data clearly in the console

3) Step-by-Step Explanation

Follow these steps to build the weather app:

  1. Setup the Project File β€“ Create a Python file: weather_app.py
  2. Install Required Library β€“ Open your terminal or VS Code terminal and install the requests library (if not already installed): pip install requests
  3. Get Free API Access β€“
    1. Go to https://openweathermap.org/api
    2. Sign up for a free account
    3. Generate your API key (you'll need it in your code)
    🧩 Example API key format: your_api_key_here
  4. Import Libraries β€“ We'll use requests for API communication and json to parse the response
  5. Create the Weather Fetch Function β€“ Define a function that takes the city name and retrieves data from the OpenWeatherMap API
  6. Handle Errors β€“ If the user enters an invalid city name, the app should gracefully inform them instead of crashing
  7. Display Data in a User-Friendly Way β€“ Print temperature, weather description, humidity, and wind speed neatly formatted
  8. Make the Program Interactive β€“ Allow the user to enter multiple cities in a loop until they choose to exit

4) Complete, Verified, and Well-Commented Python Code

You can copy this into a file named weather_app.py and run it.

# -------------------------------------------------------------- # 🌀️ Weather App using OpenWeatherMap API # Author: Your Name # Level: Intermediate # Verified: Python 3.8+ # -------------------------------------------------------------- import requests # For making HTTP requests # ============================== # Step 1: Define API base URL and key # ============================== API_KEY = "your_api_key_here" # Replace with your actual OpenWeatherMap API key BASE_URL = "https://api.openweathermap.org/data/2.5/weather" # ============================== # Step 2: Define function to get weather data # ============================== def get_weather(city_name): try: # Construct API URL with parameters url = f"{BASE_URL}?q={city_name}&appid={API_KEY}&units=metric" # Make GET request to fetch data response = requests.get(url) # Convert response data (JSON) into Python dictionary data = response.json() # If city not found if data["cod"] == "404": print("❌ City not found. Please check the name and try again.\n") else: # Extract important information city = data["name"] country = data["sys"]["country"] temperature = data["main"]["temp"] humidity = data["main"]["humidity"] wind_speed = data["wind"]["speed"] weather_desc = data["weather"][0]["description"].capitalize() # Display formatted output print(f"\nπŸŒ† Weather Report for {city}, {country}:") print(f"🌑️ Temperature: {temperature}Β°C") print(f"πŸ’§ Humidity: {humidity}%") print(f"🌬️ Wind Speed: {wind_speed} m/s") print(f"πŸŒ₯️ Condition: {weather_desc}") print("-" * 45 + "\n") except requests.exceptions.RequestException: print("⚠️ Network error! Please check your internet connection.\n") # ============================== # Step 3: Main program loop # ============================== def main(): print("========== 🌦️ Weather App ==========") print("Get real-time weather updates easily!") print("====================================\n") while True: city = input("Enter city name (or type 'exit' to quit): ").strip() if city.lower() == "exit": print("πŸ‘‹ Thank you for using the Weather App! Goodbye!") break if city == "": print("⚠️ Please enter a valid city name.\n") else: get_weather(city) # ============================== # Step 4: Run the program # ============================== if __name__ == "__main__": main()

βœ… Code Verified:
β€’ Tested with real API data
β€’ Handles invalid inputs and network errors
β€’ Runs smoothly on Python 3.8–3.12
β€’ Easy to customize and extend

5) Example Output (Terminal Sample)

User Input:

Enter city name: London

Output:

πŸŒ† Weather Report for London, GB:
🌑️ Temperature: 15°C
πŸ’§ Humidity: 62%
🌬️ Wind Speed: 3.5 m/s
πŸŒ₯️ Condition: Broken clouds
---------------------------------------------

If user enters an invalid city:

Enter city name: abcxyz
❌ City not found. Please check the name and try again.

If user exits:

Enter city name: exit
πŸ‘‹ Thank you for using the Weather App! Goodbye!

6) Extension Challenge

🎯 To make this project more advanced

ChallengeDescription
πŸŒ‡ Add a GUI using TkinterCreate a simple interface with text boxes and buttons for entering cities
πŸ“ˆ Display 5-day forecastUse the /forecast endpoint of the API
πŸ—ΊοΈ Add Location Auto-detectUse geocoder or ipinfo API to get weather for the user's current location
πŸ’Ύ Save recent searchesWrite the last 5 searched cities to a CSV or text file

7) Summary

In this project, you learned how to:

  • βœ… Use APIs to fetch real-time data
  • βœ… Handle JSON responses
  • βœ… Build interactive command-line applications
  • βœ… Manage errors and network exceptions

πŸ’¬ "Congratulations! You've just connected Python with the real world β€” and built your first API-powered app!"

This project is a solid step toward more advanced Python projects such as:

  • GUI dashboards
  • Weather forecasting with visualization
  • IoT-based smart weather devices