Python Weather App
This utility fetches current weather data for a specific city using the OpenWeatherMap API. It demonstrates how to make API calls with parameters, handle JSON responses, and manage HTTP errors.
Modules Used:
- requests: To send HTTP requests to the weather API.
- argparse: To handle city input and API key from the command line.
- json: Implicitly used by
requeststo parse the response.
Prerequisites
You need a free API key from OpenWeatherMap.
The Code
Save this as weather.py.
import argparse
import requests
import sys
def get_weather(city, api_key):
# OpenWeatherMap API endpoint
url = "http://api.openweathermap.org/data/2.5/weather"
params = {
'q': city,
'appid': api_key,
'units': 'metric' # Use 'imperial' for Fahrenheit
}
try:
print(f"Fetching weather for {city}...")
response = requests.get(url, params=params)
response.raise_for_status() # Raise exception for 4xx/5xx errors
data = response.json()
# Extract relevant info
weather_desc = data['weather'][0]['description']
temp = data['main']['temp']
humidity = data['main']['humidity']
wind_speed = data['wind']['speed']
city_name = data['name']
country = data['sys']['country']
print(f"\n--- Weather in {city_name}, {country} ---")
print(f"Condition: {weather_desc.capitalize()}")
print(f"Temperature: {temp}°C")
print(f"Humidity: {humidity}%")
print(f"Wind Speed: {wind_speed} m/s")
except requests.exceptions.HTTPError as e:
if response.status_code == 404:
print(f"Error: City '{city}' not found.")
elif response.status_code == 401:
print("Error: Invalid API Key. Please check your credentials.")
else:
print(f"HTTP Error: {e}")
except requests.exceptions.RequestException as e:
print(f"Connection Error: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="CLI Weather App")
parser.add_argument("city", help="Name of the city")
parser.add_argument("--api-key", required=True, help="Your OpenWeatherMap API Key")
args = parser.parse_args()
get_weather(args.city, args.api_key)
Usage
python weather.py London --api-key YOUR_ACTUAL_API_KEY