Expert Direction; Exceptional Results
This tutorial demonstrates how to fetch and display real-time weather information using Python and the OpenWeatherMap API.
requests
library (pip install requests
)The script prompts the user for a city name, builds a query URL using the OpenWeatherMap API, sends a GET request, and displays temperature, humidity, wind speed, and a weather description.
Enter a city: San Diego
Requesting: http://api.openweathermap.org/data/2.5/weather?q=San Diego&appid=XXXX&units=imperial
Weather in San Diego: overcast clouds
Temperature: 64.67°F
Humidity: 84%
Wind Speed: 4.61 mph
import requests
# Your API key
API_KEY = "your_api_key_here"
# Create city input prompt
city = input("Enter a city: ")
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=imperial"
# Send the GET request
response = requests.get(url)
print(f"Requesting: {url}")
# Check if the request was successful
if response.status_code == 200:
data = response.json()
# Extract useful info
weather = data["weather"][0]["description"]
temperature = data["main"]["temp"]
humidity = data["main"]["humidity"]
wind_speed = data["wind"]["speed"]
# Print it out nicely
print(f"Weather in {city}: {weather}")
print(f"Temperature: {temperature}°F")
print(f"Humidity: {humidity}%")
print(f"Wind Speed: {wind_speed} mph")
else:
print(f"Failed to get data: {response.status_code} - {response.text}")
Let’s talk through it. Sometimes the hardest part is just getting started.
Let's Discuss It