Skip to main content

canairy

PyPI Python License

Typed Python clients for public German air-quality APIs.

Miners once carried canaries to warn them of bad air underground. canairy does the modern equivalent: it fetches official air-quality measurements and hands them to you as validated pydantic models.

Supported data sources:

Module Source Coverage
canairy.uba Umweltbundesamt (UBA), air-data API v4 All of Germany, from 2016
canairy.hh Hamburger Luftmessnetz (HH) Hamburg, hourly/daily from 2012, monthly from 1984

More federal-state networks are planned.

Features

  • One client class per data source with typed get_* methods
  • Responses parsed into pydantic models with real datetimes
  • Built-in HTTP caching (hishel), rate limiting (120 requests/min) and retries with exponential backoff
  • aq-downloader command for bulk downloads of UBA data

Installation

pip install canairy
# or
uv add canairy

Requires Python 3.12 or newer.

Note: canairy is pre-1.0. Expect breaking changes between minor versions.

Quickstart

Umweltbundesamt (UBA)

from datetime import datetime

from canairy.uba import UBAClient

uba = UBAClient()

# Hourly NO₂ at Hamburg-Sternschanze (DEHH008), 1 January 2024, 00:00–05:00
res = uba.get_measures(
    datetime(2024, 1, 1, 0),
    datetime(2024, 1, 1, 5),  # inclusive
    station="DEHH008",        # station code or numeric id
    component=5,              # NO2
    scope=2,                  # one-hour average
)

for m in res.data:
    print(m.date_start, m.value, m.index)
# 2024-01-01 00:00:00 45.0 2
# 2024-01-01 01:00:00 33.0 1
# ...

Components and scopes are numeric ids. Look them up with the metadata endpoints:

for c in uba.get_components(lang="en").data:
    print(c.id, c.code, c.unit, c.name)
# 1 PM10 µg/m³ Particulate matter
# 3 O3 µg/m³ Ozone
# 5 NO2 µg/m³ Nitrogen dioxide
# 9 PM2 µg/m³ Particulate matter  ← PM2.5
# ...

for s in uba.get_scopes(lang="en").data:
    print(s.id, s.code, s.name)
# 1 1TMW Daily average
# 2 1SMW One hour average
# ...

Find stations and filter them:

from canairy.uba.utils import filter_stations_active, filter_stations_by_network

stations = uba.get_stations(lang="en").data        # ~2,400 stations, incl. closed ones
networks = uba.get_networks(lang="en").data

hamburg = filter_stations_by_network(stations, networks, "HH")
running = filter_stations_active(hamburg, "2020-01-01", "2024-12-31")

Other endpoints: get_networks() and get_thresholds(use, component_id, scope_id).

Hamburger Luftmessnetz (HH)

from datetime import datetime

from canairy.hh import HHClient

hh = HHClient()

# Hourly NO₂ at all Hamburg stations
data = hh.get_component_data(
    "no2_1h",
    timespan="custom",
    start=datetime(2024, 1, 1, 0),
    end=datetime(2024, 1, 1, 3),
)
for d in data[:2]:
    print(d.datetime, d.station, d.value)
# 2024-01-01 03:00:00+01:00 80kt 31.0
# 2024-01-01 03:00:00+01:00 21bi 11.0

# Data for a single station
hh.get_station_data(
    "13ST", period="1h", timespan="custom",
    start=datetime(2024, 1, 1), end=datetime(2024, 1, 1, 3), core="no2",
)

Component codes combine a pollutant ("core") and an averaging period, for example no2_1h, pm10_24hg or pm25_1m. List them with get_components() and get_cores(). The other endpoints are get_stations(), get_station(code) and get_thresholds().

canairy.hh.aqi contains the bins, thresholds and ratings of the German air quality index (Luftqualitätsindex) as used by the Hamburg network.

Working with DataFrames

All results are pydantic models, so they convert easily:

import polars as pl  # or pandas

df = pl.DataFrame([m.model_dump() for m in res.data])

Bulk download (aq-downloader)

aq-downloader <outpath> [-y YEAR_START]

Downloads hourly data for PM10, PM2.5, O₃, NO₂ and SO₂ and 8-hour CO for every UBA station from YEAR_START (default 2016) up to last year. Each result is stored as a pickled dict at <outpath>/<year>/<station_code>/<component>_<scope>.pkl, and progress is logged to <outpath>/download.log. Expect this to run for a long time.

A Docker image for the downloader lives in downloader/.

Known issue: each year is currently requested until 31 December of the following year, so files of consecutive years overlap. Deduplicate after loading.

Good to know

  • Caching: responses are cached in .cache/hishel/ under the current working directory for as long as the servers allow: 5 minutes for HH and 3 hours for UBA, measurements included. Repeated calls within that time don't hit the API.
  • UBA
    • get_measures needs a station; query one station at a time.
    • The API counts hours 1–24; canairy converts to regular 0–23 datetimes for you.
    • Data starts on 2016-01-01.
  • HH
    • The API silently shortens long ranges, keeping the latest 31 days for 1h, 8hg and 24hg and the latest 365 days for 24h. With timespan="custom", get_station_data and get_component_data split longer ranges into several requests and join the results, so a year of hourly data costs about 12 requests. Other timespans are not split, and passing start/end with them raises ValueError; get_component_data treats start/end without a timespan as custom.
    • A missing end means now in Hamburg. A start after end raises ValueError; an open range that starts in the future returns [].
    • Times are local (Europe/Berlin). Naive start/end are taken as Hamburg time and aware ones are converted, so a timestamp from a previous result can be passed back as is. Results carry +01:00/+02:00 offsets.
    • Rows come newest first.
    • timespan="all" on station data only returns the last 12 months.

Development

uv sync                            # install with dev dependencies
uv run pytest                      # all tests, including live API calls
uv run ruff check src tests
uv run mypy src

# offline tests only
uv run pytest --ignore=tests/hh/test_hh_client.py --ignore-glob='tests/uba/test_get_*.py'

License

BSD 3-Clause, © 2025 Institut für Angewandte Medizininformatik. See LICENSE.

The data itself is provided by the Umweltbundesamt and the Hamburger Luftmessnetz under their respective terms of use.

Metadata

Release files for canairy 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for canairy 0.3.0
File Size Uploaded Provenance Actions
canairy-0.3.0.tar.gz 19.7 kB Without provenance Details for canairy-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for canairy 0.3.0
File Interpreter ABI Platform Actions
canairy-0.3.0-py3-none-any.whl Python 3 none any Details for canairy-0.3.0-py3-none-any.whl

Total release size: 42.2 kB

Release files / canairy-0.3.0.tar.gz

Download URL canairy-0.3.0.tar.gz
Size 19.7 kB
Tags Source
SHA-256 checksum
How to use checksums
f40c733bc3f8d10a4e45b48fb150bfc05cd75a931fffff9ce2c186b2e5cdef8d
BLAKE2b-256 checksum
How to use checksums
3d8426ebdbca729f0c3e5a2a7039cacbe7ec51c9d805d7881c283f9e96742260
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / canairy-0.3.0-py3-none-any.whl

Download URL canairy-0.3.0-py3-none-any.whl
Size 22.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5246726fa49bea3ecab5e2b00650ff32241f86380d8a2ac410e02f02f630372c
BLAKE2b-256 checksum
How to use checksums
d3022d8136c347ce1e4ee006e74d815833d4091e95bbaf6bc7f24b85bab36c88
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for canairy 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page