DEV Community

Alex Spinov
Alex Spinov

Posted on

Build a Weather CLI Tool in 20 Lines of Python (Using a Free API)

I wanted a weather check in my terminal. No browser, no app, just type weather Berlin and get the answer.

20 lines of Python later, I had it.


The Complete Script

import requests
import sys

def weather(city):
    url = f"https://api.open-meteo.com/v1/forecast"
    # First, geocode the city
    geo = requests.get(f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1").json()

    if not geo.get('results'):
        print(f"City '{city}' not found")
        return

    lat = geo['results'][0]['latitude']
    lon = geo['results'][0]['longitude']
    name = geo['results'][0]['name']
    country = geo['results'][0].get('country', '')

    # Get weather
    w = requests.get(url, params={
        'latitude': lat, 'longitude': lon,
        'current_weather': True
    }).json()['current_weather']

    print(f"\n  {name}, {country}")
    print(f"  Temperature: {w['temperature']}C")
    print(f"  Wind: {w['windspeed']} km/h")
    print(f"  Direction: {w['winddirection']}")

if __name__ == '__main__':
    city = ' '.join(sys.argv[1:]) if len(sys.argv) > 1 else 'London'
    weather(city)
Enter fullscreen mode Exit fullscreen mode

Usage:

python weather.py Berlin
python weather.py "New York"
python weather.py Tokyo
Enter fullscreen mode Exit fullscreen mode

Output:

  Berlin, Germany
  Temperature: 12.3C
  Wind: 15.2 km/h
  Direction: 220
Enter fullscreen mode Exit fullscreen mode

Why Open-Meteo?

  • No API key required
  • No signup
  • No rate limit (within reason)
  • Global coverage
  • Free for non-commercial use

Compare this to OpenWeatherMap which requires an API key, or Weather.com which requires a paid subscription for decent access.


Add It as a Shell Alias

# Add to .bashrc or .zshrc
alias weather='python3 /path/to/weather.py'
Enter fullscreen mode Exit fullscreen mode

Now just type weather Berlin from anywhere.


Extend It: 7-Day Forecast

def forecast(city, days=7):
    geo = requests.get(f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1").json()
    loc = geo['results'][0]

    w = requests.get('https://api.open-meteo.com/v1/forecast', params={
        'latitude': loc['latitude'],
        'longitude': loc['longitude'],
        'daily': 'temperature_2m_max,temperature_2m_min,precipitation_sum',
        'timezone': 'auto',
        'forecast_days': days
    }).json()

    print(f"\n  7-Day Forecast: {loc['name']}, {loc.get('country', '')}")
    print(f"  {'Date':12} {'High':>6} {'Low':>6} {'Rain':>8}")
    print(f"  {'-'*34}")

    for i in range(len(w['daily']['time'])):
        date = w['daily']['time'][i]
        high = w['daily']['temperature_2m_max'][i]
        low = w['daily']['temperature_2m_min'][i]
        rain = w['daily']['precipitation_sum'][i]
        print(f"  {date:12} {high:>5.1f}C {low:>5.1f}C {rain:>6.1f}mm")
Enter fullscreen mode Exit fullscreen mode

What CLI tools have you built?

Small Python scripts that solve daily annoyances are my favorite kind of coding. What is yours? Share in the comments — I am collecting ideas for a "developer CLI toolkit" article.


I write about Python, APIs, and developer tools. Follow for practical tutorials you can use today.


More from me: 10 Dev Tools I Use Daily | 77 Scrapers on a Schedule | 150+ Free APIs

Top comments (0)