Building a Real-Time Weather Dashboard with Python and OpenWeatherMap API
Learn how to create a simple real-time weather dashboard in Python using the OpenWeatherMap API to fetch and display weather data.
Building a weather dashboard is a great way to practice working with APIs and Python. In this tutorial, you'll learn how to connect to the OpenWeatherMap API to get real-time weather data and display it in a user-friendly Python script.
First, you'll need to sign up for a free API key at OpenWeatherMap.org. This key will allow you to access their weather data.
Next, let's install the required Python package, requests, which we will use to make HTTP requests to the OpenWeatherMap API.
pip install requestsNow, let's write a Python script that fetches weather information for a city and displays it. Save this as weather_dashboard.py:
import requests
API_KEY = 'your_api_key_here' # Replace with your OpenWeatherMap API key
BASE_URL = 'http://api.openweathermap.org/data/2.5/weather'
def get_weather(city):
params = {
'q': city,
'appid': API_KEY,
'units': 'metric' # Use 'imperial' for Fahrenheit
}
response = requests.get(BASE_URL, params=params)
if response.status_code == 200:
return response.json()
else:
return None
def display_weather(data):
if data:
city = data['name']
weather_desc = data['weather'][0]['description'].capitalize()
temp = data['main']['temp']
humidity = data['main']['humidity']
wind_speed = data['wind']['speed']
print(f"Weather in {city}:")
print(f"Description: {weather_desc}")
print(f"Temperature: {temp}°C")
print(f"Humidity: {humidity}%")
print(f"Wind Speed: {wind_speed} m/s")
else:
print("Sorry, weather data could not be retrieved.")
def main():
city = input("Enter city name: ")
weather_data = get_weather(city)
display_weather(weather_data)
if __name__ == '__main__':
main()To run your script, simply execute it in the terminal or command prompt:
python weather_dashboard.pyEnter the city name when prompted, and the script will display the current weather conditions. This simple dashboard can be expanded with features like a graphical interface or additional data points.
By using Python and the OpenWeatherMap API, you can quickly build functional and real-time weather applications suitable for your projects or learning exercises.