DEV Community

Alex Spinov
Alex Spinov

Posted on

OpenWeatherMap API: Build a Weather Dashboard in 30 Lines

OpenWeatherMap gives you current weather, forecasts, air quality, and historical data for any location on Earth. Free.

Here's how to build a useful weather dashboard in 30 lines.

Setup

  1. Get a free API key at openweathermap.org (1,000 calls/day free)
  2. pip install httpx rich

The Code

import httpx
from rich.console import Console
from rich.table import Table

API_KEY = 'your_free_api_key'
console = Console()

def weather(city):
    r = httpx.get('https://api.openweathermap.org/data/2.5/weather', params={
        'q': city, 'appid': API_KEY, 'units': 'metric'
    })
    d = r.json()
    return {
        'city': d['name'],
        'temp': d['main']['temp'],
        'feels_like': d['main']['feels_like'],
        'humidity': d['main']['humidity'],
        'wind': d['wind']['speed'],
        'description': d['weather'][0]['description'].title(),
        'pressure': d['main']['pressure']
    }

def dashboard(cities):
    table = Table(title='Weather Dashboard')
    table.add_column('City', style='cyan')
    table.add_column('Temp', style='bold')
    table.add_column('Feels Like')
    table.add_column('Weather')
    table.add_column('Humidity')
    table.add_column('Wind')

    for city in cities:
        w = weather(city)
        temp_color = 'red' if w['temp'] > 30 else 'blue' if w['temp'] < 10 else 'green'
        table.add_row(
            w['city'],
            f'[{temp_color}]{w["temp"]:.1f}°C[/{temp_color}]',
            f'{w["feels_like"]:.1f}°C',
            w['description'],
            f'{w["humidity"]}%',
            f'{w["wind"]} m/s'
        )

    console.print(table)

dashboard(['London', 'New York', 'Tokyo', 'Sydney', 'Moscow'])
Enter fullscreen mode Exit fullscreen mode

Output

┌─────────────────────────────────────────────────────┐
│                  Weather Dashboard                   │
├──────────┬────────┬───────────┬──────────┬──────────┤
│ City     │ Temp   │ Feels Like│ Weather  │ Humidity │
├──────────┼────────┼───────────┼──────────┼──────────┤
│ London   │ 12.3°C │ 10.1°C    │ Overcast │ 78%      │
│ New York │ 18.5°C │ 17.2°C    │ Clear    │ 45%      │
│ Tokyo    │ 22.1°C │ 21.8°C    │ Cloudy   │ 62%      │
│ Sydney   │ 19.8°C │ 19.0°C    │ Sunny    │ 55%      │
│ Moscow   │  3.2°C │  0.5°C    │ Snow     │ 89%      │
└──────────┴────────┴───────────┴──────────┴──────────┘
Enter fullscreen mode Exit fullscreen mode

5-Day Forecast

def forecast(city):
    r = httpx.get('https://api.openweathermap.org/data/2.5/forecast', params={
        'q': city, 'appid': API_KEY, 'units': 'metric'
    })
    data = r.json()['list']
    # Group by day, get daily highs
    daily = {}
    for item in data:
        date = item['dt_txt'][:10]
        temp = item['main']['temp_max']
        if date not in daily or temp > daily[date]['temp']:
            daily[date] = {
                'temp': temp,
                'weather': item['weather'][0]['description']
            }
    return daily
Enter fullscreen mode Exit fullscreen mode

Air Quality

def air_quality(lat, lon):
    r = httpx.get('https://api.openweathermap.org/data/2.5/air_pollution', params={
        'lat': lat, 'lon': lon, 'appid': API_KEY
    })
    aqi = r.json()['list'][0]['main']['aqi']
    labels = {1: 'Good', 2: 'Fair', 3: 'Moderate', 4: 'Poor', 5: 'Very Poor'}
    return labels.get(aqi, 'Unknown')
Enter fullscreen mode Exit fullscreen mode

Free Tier Limits

Feature Limit
API calls 1,000/day
Current weather Unlimited locations
5-day forecast 3-hour intervals
Air quality Available
Geocoding Available
Historical data Paid only

Build Ideas

  • Travel weather comparison (compare 5 destinations)
  • Running/cycling weather checker
  • Plant care reminder (water when humidity < 40%)
  • Air quality alert system

More API Tutorials


What weather-related tool would you build? I'm thinking about a "best time to run" predictor. 👇

API tutorials at dev.to/0012303

Top comments (0)