Get API Key
Register at openweathermap.org → API keys. Free tier = 1,000 calls/day.
Complete Implementation
Python
import os, requests
from datetime import datetime
API_KEY = os.getenv("OPENWEATHER_API_KEY", "your_key_here")
BASE = "https://api.openweathermap.org/data/2.5"
def get_current(city, units="metric"):
r = requests.get(f"{BASE}/weather", params={"q": city, "appid": API_KEY, "units": units}, timeout=10)
r.raise_for_status()
return r.json()
def get_forecast(city, units="metric"):
r = requests.get(f"{BASE}/forecast", params={"q": city, "appid": API_KEY, "units": units, "cnt": 40}, timeout=10)
r.raise_for_status()
return r.json()["list"]
def display_current(d, units):
sym = "°C" if units == "metric" else "°F"
print(f"\n{'='*40}")
print(f" {d['name']}, {d['sys']['country']}")
print(f" {d['weather'][0]['description'].title()}")
print(f" Temp: {d['main']['temp']}{sym} (feels like {d['main']['feels_like']}{sym})")
print(f" Humidity: {d['main']['humidity']}% Wind: {d['wind']['speed']} m/s")
print("="*40)
def display_forecast(forecast, units):
sym = "°C" if units == "metric" else "°F"
print("\n5-Day Forecast:")
seen = set()
for entry in forecast:
dt = datetime.fromtimestamp(entry["dt"])
if dt.hour == 12 and dt.date() not in seen:
seen.add(dt.date())
print(f" {dt.strftime('%a %b %d')}: {entry['main']['temp']}{sym} {entry['weather'][0]['description']}")
city = input("City: ").strip()
units = input("Units metric/imperial [metric]: ").strip() or "metric"
try:
display_current(get_current(city, units), units)
display_forecast(get_forecast(city, units), units)
except requests.HTTPError as e:
print(f"Error {e.response.status_code}: city not found or invalid API key")Bash
export OPENWEATHER_API_KEY=your_key_here
python weather.pyTip: Store the API key in .env and load with python-dotenv — never commit API keys to git.