Most weather API integrations break at the same moment: something upstream changes and your code assumed it wouldn’t. A field gets renamed. A new tp value returns a shape you didn’t anticipate. The JSON structure for nearest_area grows an extra nesting level. Your parser silently swallows it and starts returning None into a field that feeds a downstream alert.
This post is about building a WWO integration that survives that moment — specifically, how to snapshot the schema you depend on, isolate the parsing layer so changes don’t ripple into application logic, and handle the migration when you do need to update. These patterns apply whether you’re on the free tier hitting 500 calls/day or running enterprise volume.
The Core Problem: Your Parser Is Coupled to the Wire Format
The WWO Premium API returns JSON (or XML if you ask for it). The JSON structure for a forecast call looks roughly like this at the top level:
{
"data": {
"current_condition": [ { ... } ],
"weather": [ { "date": "...", "hourly": [ ... ], ... } ],
"nearest_area": [ { "areaName": [{"value": "..."}], ... } ]
}
}
That double-nested list-of-dicts pattern for string values (areaName[0].value) catches a lot of people off guard. The real problem isn’t learning it once — it’s that if you scatter data["nearest_area"][0]["areaName"][0]["value"] across fifteen files, you have fifteen places to update when anything shifts.
The fix is a single parsing boundary. Everything outside it works with your internal types. Everything inside it speaks JSON.
Step 1 — Snapshot the Fields You Actually Use
Before you write any versioning logic, write down exactly which fields your integration depends on. Not every field the API returns — the ones you read.
For a typical forecast integration this is usually:
current_condition[0].temp_C,.FeelsLikeC,.humidity,.windspeedMiles,.weatherDesc[0].value,.uvIndexweather[n].date,.maxtempC,.mintempCweather[n].hourly[m].chanceofrain,.windspeedMiles,.weatherDesc[0].valuenearest_area[0].areaName[0].value,.country[0].value
Commit this list to your repo — literally as a comment block or a small JSON schema file. It becomes your contract. When you upgrade or change how you call the API, diff against this list first.
Step 2 — Build a Parsing Layer With an Explicit Version Tag
The goal is one function that converts raw API JSON into a typed dataclass, and one place where the version assumption lives:
from dataclasses import dataclass
from typing import List, Optional
API_SCHEMA_VERSION = "premium-v1-2024-07"
@dataclass
class CurrentConditions:
temp_c: int
feels_like_c: int
humidity: int
wind_mph: int
description: str
uv_index: int
@dataclass
class ForecastDay:
date: str
max_c: int
min_c: int
rain_chance: int
wind_mph: int
description: str
@dataclass
class WeatherSnapshot:
schema_version: str
location: str
current: CurrentConditions
forecast: List[ForecastDay]
def parse_wwo_response(raw: dict) -> WeatherSnapshot:
"""Single parsing boundary. All JSON access lives here."""
data = raw["data"]
cc = data["current_condition"][0]
area = data["nearest_area"][0]
location = f"{area['areaName'][0]['value']}, {area['country'][0]['value']}"
current = CurrentConditions(
temp_c=int(cc["temp_C"]),
feels_like_c=int(cc["FeelsLikeC"]),
humidity=int(cc["humidity"]),
wind_mph=int(cc["windspeedMiles"]),
description=cc["weatherDesc"][0]["value"],
uv_index=int(cc["uvIndex"]),
)
forecast = []
for day in data["weather"]:
hourly = day["hourly"][0] # representative hour
forecast.append(ForecastDay(
date=day["date"],
max_c=int(day["maxtempC"]),
min_c=int(day["mintempC"]),
rain_chance=int(hourly.get("chanceofrain", 0)),
wind_mph=int(hourly["windspeedMiles"]),
description=hourly["weatherDesc"][0]["value"],
))
return WeatherSnapshot(
schema_version=API_SCHEMA_VERSION,
location=location,
current=current,
forecast=forecast,
)
Every other module in your codebase imports WeatherSnapshot, never the raw dict. If the JSON shape changes, you fix it in one function.
Step 3 — Test Against a Frozen Response Fixture, Not Live Calls
This is the step most integrations skip, and it’s why they break silently in production. Save a real API response to a JSON file and use it as the fixture for your parser tests. Never call the live API in unit tests.
# tests/fixtures/wwo_forecast_london.json — committed to repo
# tests/test_parser.py
import json, pathlib
from myapp.weather import parse_wwo_response
FIXTURE = json.loads(
(pathlib.Path(__file__).parent / "fixtures" / "wwo_forecast_london.json").read_text()
)
def test_parse_current_temp():
snapshot = parse_wwo_response(FIXTURE)
assert snapshot.current.temp_c == 14 # from the saved fixture
def test_location_string():
snapshot = parse_wwo_response(FIXTURE)
assert "London" in snapshot.location
def test_forecast_length():
snapshot = parse_wwo_response(FIXTURE)
assert len(snapshot.forecast) == 5
When you bump API_SCHEMA_VERSION, save a new fixture alongside the old one and run both. If the new fixture passes and the old one fails, you have a real breaking change to document.
Step 4 — Handling the Actual Migration
When you do need to update the parsing logic — say the API adds a field you want to use, or a parameter you rely on behaves differently at a new tp value — the migration pattern that holds up under live traffic is a fan-out with a feature flag:
import os
USE_NEW_PARSER = os.environ.get("WWO_PARSER_V2", "false") == "true"
def parse_wwo_response(raw: dict) -> WeatherSnapshot:
if USE_NEW_PARSER:
return _parse_v2(raw)
return _parse_v1(raw)
Deploy with the flag off. Enable it on a single instance or for a percentage of requests. Compare outputs in your logging layer before cutting over. It costs almost nothing to implement and means you can roll back a schema change in thirty seconds.
One real gotcha here: if you’re caching API responses (cache TTLs of 10–15 minutes are reasonable for forecast data), make sure your cache key includes the schema version string, not just the location and timestamp. Otherwise you’ll serve a v1-parsed snapshot through a v2 parser and get type errors that look like data corruption.
Step 5 — Alert on Parse Failures, Not Just HTTP Errors
HTTP 200 doesn’t mean your data is usable. The API can return a 200 with an error key inside the data object when a location doesn’t resolve, or return valid JSON with fewer hourly entries than you expected at a given tp setting. Neither of those will raise an exception in requests.
Add a lightweight validation step after parsing:
def validate_snapshot(snapshot: WeatherSnapshot) -> bool:
if not snapshot.location:
return False
if snapshot.current.temp_c < -90 or snapshot.current.temp_c > 60:
# physically implausible — likely a parse error
return False
if len(snapshot.forecast) == 0:
return False
return True
That temperature range check (-90 to 60°C) will catch the case where a field returns an empty string and int("") raises before you even reach validation — which is fine, because a crash is easier to debug than a silent zero. Push failures to whatever alerting system you already have. The point is to separate the “API responded” signal from the “API gave us something usable” signal.
Keeping the Blast Radius Small
The integrations that hold up long-term aren’t the ones that handle every edge case upfront. They’re the ones that isolate assumptions into a small, testable surface area — so when something shifts, you know exactly where to look.
The parsing boundary pattern here adds maybe 50 lines to a typical integration. A good early test of whether that boundary is actually tight: how many files do you need to touch to fix the chanceofrain vs chanceOfRain casing inconsistency between the marine and forecast APIs? If the answer is more than one, the boundary isn’t tight enough yet.
The post Versioning Your Weather API Integration Without Breaking Prod appeared first on Weather Blog.
