Guides

Rain forecast in Python

Minute-by-minute rain for the next three hours at any point in Europe’s radar coverage, in one request.

This guide asks the Nimbo API for the rain at one place, prints the sentence it comes with, and adds up how much rain the next hour should bring. One file, one dependency.

Before you start

You need a key: get one free, no card. Keys start with nimbo_. Put it in an environment variable, so it stays out of your code: export NIMBO_KEY=nimbo_...

You also need Python 3.11 or newer (for datetime.fromisoformat on times ending in Z), and either pip install nimbo-weather (our library) or pip install requests (plain HTTP).

With our Python library

The quickest way: our client library, nimbo-weather on PyPI: typed answers, an async client, and retries on rate limits built in. It reads the key from NIMBO_KEY (or NIMBO_API_KEY).

pip install nimbo-weather
from nimbo_weather import Nimbo

forecast = Nimbo().nowcast(48.86, 2.35)  # Paris

if forecast.summary:
    print(forecast.summary.text)
for step in forecast.minutely[:6]:
    print(step.time, step.precip_mm_h, step.precip_probability)
print(forecast.attribution)  # show it with the data

Errors come as exceptions (OutOfCoverageError, RateLimitError, AuthenticationError, and others). The source is on GitHub.

Without the library: the complete example in plain HTTP

The same API with requests only, plus the next hour’s rain total and every error handled. Save it as rain.py and run python rain.py. It asks for Paris; change the coordinates to any point in the coverage.

import os
from datetime import datetime, timezone

import requests

BASE = "https://nimboweather.com"
KEY = os.environ["NIMBO_KEY"]


class NoForecastHere(Exception):
    """The point is outside the forecast area: asking again will not help."""


def nowcast(lat, lon, step=5, horizon=180):
    """The next `horizon` minutes of rain at one point, every `step` minutes."""
    r = requests.get(
        f"{BASE}/v1/nowcast",
        params={"lat": lat, "lon": lon, "step": step, "horizon": horizon},
        headers={"X-API-Key": KEY},
        timeout=10,
    )
    data = r.json()
    if r.status_code == 404 and data["error"] == "out_of_coverage":
        raise NoForecastHere(data["message"])
    if not r.ok:  # 401 bad key, 422 bad parameter, 429 allowance used up, 503 radar outage
        raise RuntimeError(f"{r.status_code} {data['error']}: {data['message']}")
    print("calls left this month:", r.headers.get("X-RateLimit-Remaining"))
    return data


def rain_next_hour(data):
    """Expected rain (mm) over the next 60 minutes from now, or None where radar does not see."""
    if data["coverage"] != "radar":
        return None
    now = datetime.now(timezone.utc)
    step_h = (datetime.fromisoformat(data["minutely"][1]["time"])
              - datetime.fromisoformat(data["minutely"][0]["time"])).total_seconds() / 3600
    total = 0.0
    for m in data["minutely"]:
        minutes_ahead = (datetime.fromisoformat(m["time"]) - now).total_seconds() / 60
        if 0 < minutes_ahead <= 60:  # skip the entries already in the past
            total += m["precip_mm_h"] * step_h
    return round(total, 1)


data = nowcast(48.86, 2.35)  # Paris
if data["stale"]:
    print("Radar data is late:", data["data_age_s"] // 60, "min old")
if data["summary"] is None:
    print("No radar coverage at this point")
else:
    print(data["summary"]["text"])
    print("Rain in the next hour:", rain_next_hour(data), "mm")

On a rainy afternoon it prints something like:

calls left this month: 19996
Moderate rain starting in 27 min, lasting at least 1 h 25 min
Rain in the next hour: 1.8 mm

What the answer holds

The fields this example reads. The API reference lists them all.

FieldMeaning
issue_timeWhen the forecast was made (UTC), from the last radar image. A new forecast comes every 10 minutes.
data_age_s, staleSeconds since issue_time, normally 300 to 1,020; stale is true when the radar data is late.
coverageradar where radar sees the point, no_radar where it does not (then rates are null).
summary.textA sentence you can show as it is, counted from the moment you asked.
summary.minutes_until_rain, rain_starts_at, rain_ends_atWhen the first shower starts and stops; null when there is none, or when it lasts past the end of the forecast.
minutely[].timeThe time each entry is valid for (UTC), every step minutes from issue_time.
minutely[].precip_mm_hRain rate in mm/h. Rain means 0.2 mm/h or more.
minutely[].precip_probabilityChance of rain, 0 to 1. precip_probability_1mm_h and precip_probability_5mm_h give the chance of heavier rain.

Choosing step and horizon

step sets the minutes between entries (1, 5, 10 or 15) and horizon how far the list goes (5 to 180 minutes). With step=1 you get one entry per minute, drawn between the 5-minute values; with 10 or 15 each entry keeps the highest value of the minutes it covers, so a short shower is never lost. The summary is the same whatever you choose, and every request counts as one call.

Common pitfalls

  • The first entries can be in the past. The list starts at issue_time, and an answer is typically 7 to 17 minutes younger than that. Compare each time with the clock, as rain_next_hour does.
  • no_radar is a 200, not an error. Inside the forecast grid where no radar sees, summary is null and every rate is None: check coverage before doing sums.
  • 404 out_of_coverage means outside Europe’s grid. Asking again will not help, so the example raises its own exception for it.
  • Late radar. When stale is true, the summary says the forecast is delayed instead of guessing. After 2 hours without radar, the API answers 503 forecast_unavailable: try again in 10 minutes.
  • The monthly allowance. Every answer carries X-RateLimit-Remaining. When it reaches zero, calls get 429 monthly_quota_exceeded until the month ends; there is never a surprise bill.
  • Asking too often. The forecast changes every 10 minutes. For many users near the same place, round the coordinates to two decimals (about 1 km) and keep each answer for a few minutes.

Next: Rain forecast in JavaScript