Weather App using API project (code) in Python

← Back to Projects

Weather App (using API) in Python.

About the project: This program will allow you to get current weather information for any city you specify.

It will fetch data from a public weather API, parse the information, and display it in a user-friendly format.


Before you run the code:

  • Get an API Key: You'll need a free API key from a weather service. A popular and easy-to-use one is OpenWeatherMap.
  • Go to https://openweathermap.org/
  • Sign up for a free account.
  • Once logged in, navigate to the "API keys" tab to find your personal API key.
  • Install requests library: Open your terminal or command prompt and run:
  • 
      pip install requests
      

How to use this program:

  • Save the code: Save the code below as a Python file (e.g., weather_app.py).
  • Get your API Key: Visit OpenWeatherMap, sign up for a free account, and get your API key.
  • Insert API Key: Open the weather_app.py file and replace 'YOUR_API_KEY' with the actual API key you obtained.
  • Install requests: If you haven't already, install the requests library by running pip install requests in your terminal.
  • Run the script: Open your terminal or command prompt, navigate to the directory where you saved the file, and run:
  • 
      python weather_app.py
      

The program will then prompt you to enter a city name, fetch the weather data, and display it. You can keep entering city names until you type q to quit.


Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# weather_app.py

import requests
import json
import os

# IMPORTANT: Replace 'YOUR_API_KEY' with your actual OpenWeatherMap API key
API_KEY = "YOUR_API_KEY"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather?"

def get_weather_data(city_name):
    """
    Fetches current weather data for a given city from OpenWeatherMap API.

    Args:
        city_name (str): The name of the city.

    Returns:
        dict or None: A dictionary containing weather data if successful, None otherwise.
    """
    complete_url = f"{BASE_URL}appid={API_KEY}&q={city_name}&units=metric"
    # The 'units=metric' parameter gets temperature in Celsius. Use 'imperial' for Fahrenheit.

    try:
        response = requests.get(complete_url)
        response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
        data = response.json()

        if data["cod"] == 200: # Check if the API call was successful
            return data
        else:
            print(f"Error: {data.get('message', 'Could not retrieve weather data.')}")
            return None
    except requests.exceptions.RequestException as e:
        print(f"Network error or invalid request: {e}")
        return None
    except json.JSONDecodeError:
        print("Error: Could not decode JSON response from API.")
        return None

def display_weather(weather_data):
    """
    Displays the extracted weather information in a user-friendly format.
    """
    if weather_data is None:
        return

    main_data = weather_data['main']
    weather_desc = weather_data['weather'][0]
    wind_data = weather_data['wind']
    
    city = weather_data['name']
    country = weather_data['sys']['country']
    temperature = main_data['temp']
    feels_like = main_data['feels_like']
    humidity = main_data['humidity']
    description = weather_desc['description']
    pressure = main_data['pressure']
    wind_speed = wind_data['speed']

    print("\n--- Current Weather ---")
    print(f"City: {city}, {country}")
    print(f"Temperature: {temperature:.1f}°C (Feels like: {feels_like:.1f}°C)")
    print(f"Description: {description.capitalize()}")
    print(f"Humidity: {humidity}%")
    print(f"Pressure: {pressure} hPa")
    print(f"Wind Speed: {wind_speed} m/s")
    print("-----------------------")

def main():
    """
    Main function to run the Weather App.
    """
    if API_KEY == "YOUR_API_KEY":
        print("WARNING: Please replace 'YOUR_API_KEY' in the script with your actual OpenWeatherMap API key.")
        print("You can get a free API key from https://openweathermap.org/api")
        return

    print("--- Python Weather App ---")
    print("Get current weather information for any city.")
    print("Type 'q' to quit at any time.")

    while True:
        city_name = input("\nEnter city name: ").strip()

        if city_name.lower() == 'q':
            print("Exiting Weather App. Goodbye!")
            break
        
        if not city_name:
            print("City name cannot be empty. Please enter a city.")
            continue

        weather_data = get_weather_data(city_name)
        if weather_data:
            display_weather(weather_data)
        else:
            print("Could not get weather for that city. Please try again.")

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()