Python Snippets

Fetch and Display Weather Information from OpenWeatherMap API

import requests
import json
from datetime import datetime

def get_weather_data(city_name, api_key):
    """
    Fetch current weather data for a given city from OpenWeatherMap API.
    
    Args:
        city_name (str): Name of the city to get weather for
        api_key (str): Your OpenWeatherMap API key
    
    Returns:
        dict: Weather data if successful, None if error occurred
    """
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        'q': city_name,
        'appid': api_key,
        'units': 'metric'  # For Celsius; use 'imperial' for Fahrenheit
    }
    
    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # Raise an exception for bad status codes
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
        return None
    except json.JSONDecodeError:
        print("Error: Invalid JSON response")
        return None

def display_weather_info(weather_data):
    """
    Display formatted weather information.
    
    Args:
        weather_data (dict): Weather data from OpenWeatherMap API
    """
    if not weather_data:
        print("No weather data to display")
        return
    
    # Extract relevant information
    city = weather_data['name']
    country = weather_data['sys']['country']
    temperature = weather_data['main']['temp']
    feels_like = weather_data['main']['feels_like']
    humidity = weather_data['main']['humidity']
    pressure = weather_data['main']['pressure']
    description = weather_data['weather'][0]['description'].title()
    wind_speed = weather_data['wind']['speed']
    timestamp = datetime.fromtimestamp(weather_data['dt'])
    
    # Display formatted information
    print("=" * 50)
    print(f"Weather Information for {city}, {country}")
    print("=" * 50)
    print(f"Temperature:     {temperature}°C (feels like {feels_like}°C)")
    print(f"Description:     {description}")
    print(f"Humidity:        {humidity}%")
    print(f"Pressure:        {pressure} hPa")
    print(f"Wind Speed:      {wind_speed} m/s")
    print(f"Last Updated:    {timestamp.strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 50)

def main():
    # Replace with your actual API key from https://openweathermap.org/api
    API_KEY = "your_api_key_here"
    
    # Get city name from user
    city = input("Enter city name: ").strip()
    
    if not city:
        print("City name cannot be empty")
        return
    
    # Fetch weather data
    weather_data = get_weather_data(city, API_KEY)
    
    # Display information
    display_weather_info(weather_data)

if __name__ == "__main__":
    main()

This code snippet fetches and displays current weather information for any city using the OpenWeatherMap API. It’s useful for quickly checking weather conditions without leaving your terminal or integrating weather data into other applications.

Key features of this implementation:

  1. Error Handling: Properly handles network errors, invalid responses, and API issues
  2. User-Friendly Display: Formats weather information in a clear, readable way
  3. Flexible Units: Easily switch between Celsius and Fahrenheit by changing the ‘units’ parameter
  4. Current Data: Shows temperature, “feels like” temperature, humidity, pressure, wind speed, and description

To use this snippet:

  1. Sign up for a free API key at OpenWeatherMap
  2. Replace "your_api_key_here" with your actual API key
  3. Run the script and enter any city name when prompted

The script will display current weather conditions including temperature, humidity, pressure, and more. This is especially useful for:

Dependencies: