knmidata package¶
Subpackages¶
Submodules¶
Module contents¶
Asynchronous Python client for the KNMI Data Platform with native xarray support.
- class knmidata.APIKeyAuth(*, api_key: str, header_name: str = 'Authorization')¶
Bases:
AuthStrategy that injects an API key directly into request headers.
The KNMI gateway expects the raw key in the
Authorizationheader (noBearerprefix).- Parameters:
api_key (str) – The raw API key provided by the KNMI developer platform.
header_name (str, default="Authorization") – The header name expected by the gateway.
- api_key: str¶
- auth_flow(request: Request) Generator[Request, Response, None]¶
Inject the raw API key into the specified header.
- header_name: str¶
- class knmidata.AsyncEDRClient(*, transport: AsyncTransport, auth: Auth)¶
Bases:
objectClient for querying the KNMI OGC EDR API service.
- Parameters:
transport (AsyncTransport) – Shared HTTP transport and concurrency semaphore.
auth (httpx.Auth) – Authentication strategy providing the personal EDR API key.
- auth: Auth¶
- async collection(collection_id: str) dict[str, Any]¶
Get metadata for a collection, including available parameters and output formats.
- Parameters:
collection_id (str) – EDR collection ID (e.g. ‘daily-in-situ-meteorological-observations’).
- Returns:
Parsed JSON response of the /collections/{id} endpoint.
- Return type:
dict[str, Any]
- async collections() dict[str, Any]¶
List all collections available in the EDR API.
- Returns:
Parsed JSON response of the /collections endpoint.
- Return type:
dict[str, Any]
- async get_area(collection: str, bbox: tuple[float, float, float, float], start_time: str | Timestamp | datetime | date | None = None, end_time: str | Timestamp | datetime | date | None = None, parameters: str | list[str] | None = None, output_format: Literal['CoverageJSON', 'GeoJSON'] = 'CoverageJSON', crs: str | None = None) Dataset¶
Get data over a spatial bounding box via /collections/{id}/area.
- Parameters:
collection (str) – EDR collection ID.
bbox (BBox) – Bounding box as (minx, miny, maxx, maxy).
start_time (TimeLike | None, default=None) – Start of the queried time interval (see get_position).
end_time (TimeLike | None, default=None) – End of the queried time interval (see get_position).
parameters (list[str] | None, default=None) – Parameter name or list of parameter names to query.
output_format (str, default="CoverageJSON") – Response format: ‘CoverageJSON’ or ‘GeoJSON’.
crs (str | None, default=None) – Coordinate reference system of bbox.
- Returns:
In-memory xarray dataset.
- Return type:
xr.Dataset
- async get_cube(collection: str, bbox: tuple[float, float, float, float], z: str | tuple[float, float], start_time: str | Timestamp | datetime | date | None = None, end_time: str | Timestamp | datetime | date | None = None, parameters: str | list[str] | None = None, output_format: Literal['CoverageJSON', 'GeoJSON'] = 'CoverageJSON', crs: str | None = None) Dataset¶
Get a 3D volume via /collections/{id}/cube.
- Parameters:
collection (str) – EDR collection ID.
bbox (BBox) – Bounding box as (minx, miny, maxx, maxy).
z (ZLevel) – Vertical level or interval (e.g. ‘100’ or (100, 500)).
start_time (TimeLike | None, default=None) – Start of the queried time interval (see get_position).
end_time (TimeLike | None, default=None) – End of the queried time interval (see get_position).
parameters (list[str] | None, default=None) – Parameter name or list of parameter names to query.
output_format (str, default="CoverageJSON") – Response format: ‘CoverageJSON’ or ‘GeoJSON’.
crs (str | None, default=None) – Coordinate reference system of bbox and z.
- Returns:
In-memory xarray dataset.
- Return type:
xr.Dataset
- async get_location(collection_id: str, location_id: str, start_time: str | Timestamp | datetime | date | None = None, end_time: str | Timestamp | datetime | date | None = None, parameters: str | list[str] | None = None, output_format: Literal['CoverageJSON', 'GeoJSON'] = 'CoverageJSON') Dataset¶
Get data for a single location (weather station) as an xarray.Dataset.
Uses /collections/{id}/locations/{location_id}. This is the typical way to get a time series for a station collection: note that /position with a POINT coordinate can return HTTP 404 (“The query returned no stations”) for these collections.
- Parameters:
collection_id (str) – EDR collection ID.
location_id (str) – Location identifier (station id, e.g. ‘0-20000-0-06260’ for De Bilt; see locations()).
start_time (TimeLike | None, default=None) – Start of the time interval (see get_position).
end_time (TimeLike | None, default=None) – End of the time interval (see get_position).
parameters (list[str] | None, default=None) – Parameter name or list of parameter names to query.
output_format (OutputFormat, default="CoverageJSON") – Response format: ‘CoverageJSON’ or ‘GeoJSON’.
- Returns:
In-memory xarray dataset.
- Return type:
xr.Dataset
- async get_position(collection: str, coords: tuple[float, float], start_time: str | Timestamp | datetime | date | None = None, end_time: str | Timestamp | datetime | date | None = None, parameters: str | list[str] | None = None, output_format: Literal['CoverageJSON', 'GeoJSON'] = 'CoverageJSON', crs: str | None = None) Dataset¶
Get station or point time-series via /collections/{id}/position.
Note: /position does server-side nearest-station matching, but only within a tolerance — it returns HTTP 404 (“The query returned no stations”) when no station is close enough to the point. For a reliable client-side nearest lookup use nearest_location(), then get_location() with the returned station id.
- Parameters:
collection (str) – EDR collection ID.
coords (Coords) – Point coordinates (lon, lat).
start_time (TimeLike | None, default=None) – Start of the queried time interval (ISO-8601 string, pandas Timestamp, datetime, or date; naive values are assumed UTC). Sent as an RFC 3339 interval: with both start and end as ‘start/end’, with only start_time as ‘start/..’.
end_time (TimeLike | None, default=None) – End of the queried time interval. With only end_time given the interval ‘../end’ is sent. For a single instant, pass the same value as start_time and end_time.
parameters (list[str] | None, default=None) – Parameter name or list of parameter names to query (see collection metadata).
output_format (str, default="CoverageJSON") – Response format: ‘CoverageJSON’ or ‘GeoJSON’.
crs (str | None, default=None) – Coordinate reference system of coords, e.g. ‘EPSG:4326’.
- Returns:
In-memory xarray dataset.
- Return type:
xr.Dataset
- async instances(collection_id: str) dict[str, Any]¶
List the instances of a collection.
- Parameters:
collection_id (str) – EDR collection ID.
- Returns:
Parsed JSON response of the /collections/{id}/instances endpoint.
- Return type:
dict[str, Any]
- async location(collection_id: str, location_id: str) dict[str, Any]¶
Get metadata for a single location.
- Parameters:
collection_id (str) – EDR collection ID.
location_id (str) – Location identifier.
- Returns:
GeoJSON Feature.
- Return type:
dict[str, Any]
- async locations(collection_id: str) dict[str, Any]¶
List the measurement locations of a collection as GeoJSON.
- Parameters:
collection_id (str) – EDR collection ID.
- Returns:
GeoJSON FeatureCollection.
- Return type:
dict[str, Any]
- async nearest_location(collection_id: str, coords: tuple[float, float]) dict[str, Any]¶
Find the measurement location nearest to coords (client-side).
/position does server-side nearest-station matching but only within a tolerance — it returns HTTP 404 “The query returned no stations” when no station is close enough. This helper always returns the closest station: it fetches /locations and computes haversine distances.
- Parameters:
collection_id (str) – EDR collection ID.
coords (Coords) – Point coordinates (lon, lat).
- Returns:
The nearest location: {‘id’, ‘name’, ‘coordinates’, ‘distance_km’, ‘properties’}.
- Return type:
dict[str, Any]
- Raises:
KNMIError – If the collection has no locations.
- transport: AsyncTransport¶
- class knmidata.AsyncKNMIClient(api_key: str | None = None, edr_key: str | None = None, max_concurrency: int = 15, timeout: float = 60.0, max_retries: int = 3)¶
Bases:
objectAsynchronous client composing all KNMI Data Platform API sub-services.
- opendata¶
Open Data API namespace: list_files, download_files, open_dataset (files already on disk), get_dataset, … (authentication resolved lazily on first access).
- Type:
- edr¶
EDR API namespace: collections, locations, get_location, get_position, get_area, get_cube, … (authentication resolved lazily on first access).
- Type:
- Parameters:
api_key (str | None, default=None) – API key used for the Open Data API. Falls back to the KNMI_OPENDATA_API_KEY environment variable (or KNMI_OPENDATA_API_KEY_FILE), then to the public anonymous key.
edr_key (str | None, default=None) – Dedicated EDR API key. KNMI issues separate keys per API, so an Open Data key does not work for EDR. Falls back to KNMI_EDR_API_KEY (or KNMI_EDR_API_KEY_FILE).
max_concurrency (int, default=15) – Maximum concurrent network requests.
timeout (float, default=60.0) – Read timeout in seconds.
max_retries (int, default=3) – Retries for transient failures (429/5xx/transport errors).
- async aclose() None¶
Close the underlying HTTP transport session.
- property edr: AsyncEDRClient¶
The EDR API namespace, lazily initializing its authentication.
- async get_dataset(dataset_name: str, dataset_version: str, **kwargs: Any) Dataset¶
Shortcut for client.opendata.get_dataset(…).
See AsyncOpenDataClient.get_dataset for the full parameter list (start_time, end_time, cache_dir, file_pattern, max_files, engine, combine, concat_dim, and per-file xarray.open_dataset kwargs).
- async get_timeseries(collection_id: str, location_id: str, start_time: str | Timestamp | datetime | date | None = None, end_time: str | Timestamp | datetime | date | None = None, parameters: str | list[str] | None = None, **kwargs: Any) Dataset¶
Shortcut for client.edr.get_location(…) (single station time series).
See AsyncEDRClient.get_location for the full parameter list (parameters, output_format).
- property opendata: AsyncOpenDataClient¶
The Open Data API namespace, lazily initializing its authentication.
- property transport: AsyncTransport¶
The shared HTTP transport.
- class knmidata.AsyncOpenDataClient(*, transport: AsyncTransport, auth: Auth)¶
Bases:
objectClient for the KNMI Open Data API (file-based bulk downloads).
Covers the whole Open Data workflow: list_files (catalog with cursor pagination and time filtering), get_download_url (presigned S3 URL per file), stream_file/download_files (atomic concurrent downloads to disk), open_dataset (open files already on disk into an xarray.Dataset), and get_dataset (list + download-if-missing + open in one call). Access it via client.opendata, or instantiate directly with your own transport/auth.
- Parameters:
transport (AsyncTransport) – Shared HTTP transport and concurrency semaphore.
auth (httpx.Auth) – Authentication strategy for the Open Data gateway.
- auth: Auth¶
- async download_files(dataset_name: str, dataset_version: str, filenames: list[str], destination_dir: str | Path | None = None) list[Path]¶
Download multiple files concurrently.
- Parameters:
dataset_name (str) – Name of the KNMI dataset.
dataset_version (str) – Dataset version identifier.
filenames (list[str]) – List of filenames to download.
destination_dir (PathLike | None, default=None) – Directory to save files into. Uses a temporary directory if None.
- Returns:
Local paths of downloaded files, in the same order as filenames.
- Return type:
list[Path]
- Raises:
KNMIError – If one or more files could not be downloaded.
- async get_dataset(dataset_name: str, dataset_version: str, start_time: str | Timestamp | datetime | date | None = None, end_time: str | Timestamp | datetime | date | None = None, cache_dir: str | Path | None = None, file_pattern: str | None = None, max_files: int | None = None, engine: str = 'h5netcdf', combine: Literal['by_coords', 'nested', 'no_conflicts'] = 'by_coords', concat_dim: str | None = None, **open_dataset_kwargs: Any) Dataset¶
Get matching archive files via Open Data and assemble an xarray.Dataset.
If cache_dir is given, files already on disk (matching the catalog size) are reused instead of re-downloaded, and the dataset is opened lazily from disk via open_dataset. If cache_dir is None, files are downloaded to a temporary directory, loaded into memory, and removed again.
- Parameters:
dataset_name (str) – KNMI dataset name.
dataset_version (str) – Dataset version identifier.
start_time (TimeLike | None, default=None) – Start timestamp (ISO-8601 string, pandas Timestamp, datetime, or date; naive values are assumed UTC).
end_time (TimeLike | None, default=None) – End timestamp (TimeLike, see start_time).
cache_dir (PathLike | None, default=None) – Local folder to cache downloaded NetCDF/HDF5 files in. If None, files are downloaded to a temporary directory and loaded into memory.
file_pattern (str | None, default=None) – Optional regular expression to keep only matching file names.
max_files (int | None, default=None) – Maximum number of files to download (after listing, ascending order).
engine (str, default="h5netcdf") – Xarray backend engine used to open each file (see files_to_dataset).
combine (CombineMethod, default="by_coords") – How to combine the per-file datasets (see files_to_dataset).
concat_dim (str | None, default=None) – Dimension to concatenate along when combine=’nested’.
**open_dataset_kwargs (Any) – Additional keyword arguments passed to xarray.open_dataset per file.
- Returns:
Combined multidimensional dataset.
- Return type:
xr.Dataset
- Raises:
NoFilesFoundError – If the query matches no files.
- async get_download_url(dataset_name: str, dataset_version: str, filename: str) str¶
Retrieve a temporary S3 presigned download URL for a file.
- Parameters:
dataset_name (str) – Name of the KNMI dataset.
dataset_version (str) – Dataset version identifier.
filename (str) – File name inside the dataset.
- Returns:
Temporary presigned download URL.
- Return type:
str
- async list_files(dataset_name: str, dataset_version: str, start_time: str | Timestamp | datetime | date | None = None, end_time: str | Timestamp | datetime | date | None = None, max_keys: int = 1000, sorting: str | None = None, order_by: str | None = None, file_pattern: str | None = None, max_files: int | None = None) list[str]¶
Fetch matching file names from the catalog, handling pagination automatically.
- Parameters:
dataset_name (str) – Name of the KNMI dataset (e.g., ‘rad_nl25_rac_mfbs_01h’).
dataset_version (str) – Dataset version identifier (e.g., ‘2.0’).
start_time (TimeLike | None, default=None) – Start timestamp filter (ISO-8601 string, pandas Timestamp, datetime, or date; naive values are assumed UTC). Requires server-side ordering by modification time, so order_by defaults to ‘lastModified’ when a time filter is given.
end_time (TimeLike | None, default=None) – End timestamp filter.
max_keys (int, default=1000) – Number of keys to request per pagination batch. Clamped to the API maximum of 1000.
sorting (str | None, default=None) – ‘asc’ or ‘desc’.
order_by (str | None, default=None) – Attribute to order/filter by: ‘filename’ (default), ‘lastModified’, or ‘created’. Set to ‘lastModified’ (the default when start_time or end_time is given) to make begin/end act as ISO-8601 timestamps; with the default ‘filename’ ordering, begin/end are compared as filename strings instead.
file_pattern (str | None, default=None) – Optional regular expression applied client-side to keep only matching file names.
max_files (int | None, default=None) – Stop paginating once this many matching files have been collected (after client-side pattern filtering).
- Returns:
List of unique file names available for download.
- Return type:
list[str]
- async open_dataset(source: str | Path | Sequence[str | Path], engine: str = 'h5netcdf', combine: Literal['by_coords', 'nested', 'no_conflicts'] = 'by_coords', concat_dim: str | None = None, **open_dataset_kwargs: Any) Dataset¶
Open already-downloaded files from disk into an xarray.Dataset (no network).
- Parameters:
source (PathLike | FilePaths) – A directory (all files in it, sorted by name — e.g. a cache_dir previously filled by get_dataset) or an explicit list of file paths.
engine (str, default="h5netcdf") – Xarray backend engine used to open each file (see files_to_dataset).
combine (CombineMethod, default="by_coords") – How to combine the per-file datasets (see files_to_dataset).
concat_dim (str | None, default=None) – Dimension to concatenate along when combine=’nested’.
**open_dataset_kwargs (Any) – Additional keyword arguments passed to xarray.open_dataset per file.
- Returns:
Combined multidimensional dataset, opened lazily from disk.
- Return type:
xr.Dataset
- async stream_file(url: str, target_path: Path, expected_size: int | None = None) Path¶
Stream download a file from a presigned URL in bounded memory.
The file is written to a
.partsibling and atomically moved into place, so an interrupted download is never mistaken for a complete file. Existing complete files are skipped.- Parameters:
url (str) – Direct presigned download URL.
target_path (Path) – Destination path on local disk.
expected_size (int | None, default=None) – Expected file size in bytes; used to validate the download and to decide whether an existing file can be skipped.
- Returns:
Path to the downloaded file.
- Return type:
Path
- transport: AsyncTransport¶
- class knmidata.AsyncTransport(max_concurrency: int = 15, timeout: float = 60.0, max_retries: int = 3, retry_backoff: float = 0.5)¶
Bases:
objectEncapsulates an httpx.AsyncClient bounded by a concurrency semaphore.
All requests should go through
request()(orstream()), which applies the semaphore, retries transient failures with backoff, and maps HTTP errors onto the knmidata exception hierarchy.- Parameters:
max_concurrency (int, default=15) – Maximum number of concurrent network requests permitted across the session.
timeout (float, default=60.0) – Read timeout in seconds (per chunk for streamed downloads).
max_retries (int, default=3) – Number of retries for transient failures (429/5xx/transport errors).
retry_backoff (float, default=0.5) – Base backoff in seconds; the actual delay is
retry_backoff * 2**attemptplus jitter, and honors theRetry-Afterresponse header when present.
- async aclose() None¶
Close the underlying HTTP client session.
- async get_json(url: str, *, auth: Auth | None = None, params: dict[str, Any] | None = None) Any¶
GET a URL and return the parsed JSON body.
- Parameters:
url (str) – Absolute URL.
auth (httpx.Auth | None, default=None) – Authentication strategy.
params (dict | None, default=None) – Query parameters.
- Returns:
Parsed JSON payload.
- Return type:
Any
- async request(method: str, url: str, *, auth: Auth | None = None, **kwargs: Any) Response¶
Perform an HTTP request with semaphore, retries, and error mapping.
- Parameters:
method (str) – HTTP method (e.g. ‘GET’).
url (str) – Absolute URL.
auth (httpx.Auth | None, default=None) – Authentication strategy; pass None for unauthenticated endpoints such as presigned S3 download URLs.
**kwargs (Any) – Forwarded to
httpx.AsyncClient.request(e.g.params).
- Returns:
Successful (2xx) response.
- Return type:
httpx.Response
- Raises:
KNMIAuthError – On HTTP 401/403.
KNMIHTTPError – On other HTTP error statuses after exhausting retries.
- stream(method: str, url: str, *, auth: Auth | None = None, **kwargs: Any) AsyncGenerator[Response, None]¶
Stream a response body while holding a concurrency slot.
- Parameters:
method (str) – HTTP method (e.g. ‘GET’).
url (str) – Absolute URL, typically a presigned S3 download URL.
auth (httpx.Auth | None, default=None) – Authentication strategy; usually None for presigned URLs.
**kwargs (Any) – Forwarded to
httpx.AsyncClient.stream.
- Yields:
httpx.Response – The open response stream.
- class knmidata.Authenticator(*args, **kwargs)¶
Bases:
ProtocolProtocol defining how credentials attach to HTTP requests.
- auth_flow(request: Request) Generator[Request, Response, None]¶
Apply authentication headers to the outgoing request.
- exception knmidata.KNMIAuthError¶
Bases:
KNMIErrorRaised when no valid API key can be resolved or the API rejects the key.
- class knmidata.KNMIClient(api_key: str | None = None, edr_key: str | None = None, max_concurrency: int = 15, timeout: float = 60.0, max_retries: int = 3)¶
Bases:
objectSynchronous facade wrapping AsyncKNMIClient for non-async environments.
All coroutines are executed on a dedicated background event loop in a separate thread, so the client can be called repeatedly (and from inside environments that already run an event loop, such as Jupyter).
- opendata¶
Synchronous facade for the Open Data API namespace.
- Type:
_SyncFacade
- edr¶
Synchronous facade for the EDR API namespace.
- Type:
_SyncFacade
- Parameters:
api_key (str | None, default=None) – API key used for the Open Data API. Falls back to the KNMI_OPENDATA_API_KEY environment variable (or KNMI_OPENDATA_API_KEY_FILE), then to the public anonymous key.
edr_key (str | None, default=None) – Dedicated EDR API key. KNMI issues separate keys per API, so an Open Data key does not work for EDR. Falls back to KNMI_EDR_API_KEY (or KNMI_EDR_API_KEY_FILE).
max_concurrency (int, default=15) – Maximum concurrent network requests.
timeout (float, default=60.0) – Read timeout in seconds.
max_retries (int, default=3) – Retries for transient failures (429/5xx/transport errors).
- close() None¶
Close the underlying connection pool and stop the background loop.
- property edr: _SyncFacade¶
Synchronous facade for the EDR API namespace (cached).
EDR auth is resolved lazily on first access.
- get_dataset(dataset_name: str, dataset_version: str, **kwargs: Any) Dataset¶
Shortcut for client.opendata.get_dataset(…) (synchronous).
See AsyncOpenDataClient.get_dataset for the full parameter list.
- get_timeseries(collection_id: str, location_id: str, start_time: str | Timestamp | datetime | date | None = None, end_time: str | Timestamp | datetime | date | None = None, parameters: str | list[str] | None = None, **kwargs: Any) Dataset¶
Shortcut for client.edr.get_location(…) (synchronous).
See AsyncEDRClient.get_location for the full parameter list.
- property opendata: _SyncFacade¶
Synchronous facade for the Open Data API namespace (cached).
- exception knmidata.KNMIError¶
Bases:
ExceptionBase class for all errors raised by knmidata.
- exception knmidata.KNMIHTTPError(status_code: int, url: str, body: str = '')¶
Bases:
KNMIErrorRaised when the KNMI API returns an unexpected HTTP status code.
- Parameters:
status_code (int) – HTTP status code returned by the API.
url (str) – Request URL that produced the error.
body (str) – Raw response body, usually a JSON error message from the gateway.
- class knmidata.NoAuth¶
Bases:
AuthStrategy for unauthenticated public endpoints.
- auth_flow(request: Request) Generator[Request, Response, None]¶
Pass the request through without modifying headers.
- exception knmidata.NoFilesFoundError¶
Bases:
KNMIErrorRaised when a dataset query matches no files.
- knmidata.files_to_dataset(file_paths: Sequence[str | Path], engine: str = 'h5netcdf', combine: Literal['by_coords', 'nested', 'no_conflicts'] = 'by_coords', concat_dim: str | None = None, **open_dataset_kwargs: Any) Dataset¶
Assemble local NetCDF/HDF5 files into an xarray.Dataset.
Implemented with xr.open_dataset + xr.combine_by_coords so that no dask installation is required.
- Parameters:
file_paths (FilePaths) – Paths to the downloaded NetCDF files.
engine (str, default="h5netcdf") – Xarray backend engine.
combine (CombineMethod, default="by_coords") – How to combine the per-file datasets: ‘by_coords’ (combine_by_coords), ‘nested’ (concat along concat_dim), or ‘no_conflicts’ (merge).
concat_dim (str | None, default=None) – Dimension to concatenate along when combine=’nested’.
**open_dataset_kwargs (Any) – Additional options forwarded to xr.open_dataset.
- Returns:
Combined multidimensional dataset.
- Return type:
xr.Dataset
- Raises:
KNMIError – If file_paths is empty, or combine=’nested’ without concat_dim.
- knmidata.get_dataset(dataset_name: str, dataset_version: str, api_key: str | None = None, **kwargs: Any) Dataset¶
One-line convenience function to get an Open Data dataset as an xarray.Dataset.
Downloads matching files (reusing cache_dir if given) and opens them.
- Parameters:
dataset_name (str) – KNMI dataset name.
dataset_version (str) – Dataset version identifier.
api_key (str | None, default=None) – Optional KNMI Open Data API key. Falls back to environment variables and the public anonymous key if omitted.
**kwargs (Any) – Forwarded to AsyncOpenDataClient.get_dataset: start_time, end_time, cache_dir, file_pattern, max_files, engine, combine, concat_dim, and per-file xarray.open_dataset keyword arguments.
- Returns:
Multidimensional dataset.
- Return type:
xr.Dataset
- knmidata.get_timeseries(collection_id: str, location_id: str, start_time: str | Timestamp | datetime | date | None = None, end_time: str | Timestamp | datetime | date | None = None, parameters: str | list[str] | None = None, edr_key: str | None = None, **kwargs: Any) Dataset¶
One-line convenience function to get a station time series via the EDR API.
- Parameters:
collection_id (str) – EDR collection ID (e.g. ‘daily-in-situ-meteorological-observations’).
location_id (str) – Station/location ID (e.g. ‘0-20000-0-06260’ for De Bilt; find ids via AsyncEDRClient.locations).
start_time (TimeLike | None, default=None) – Start of the time interval (ISO-8601 string, pandas Timestamp, datetime, or date; naive values are assumed UTC).
end_time (TimeLike | None, default=None) – End of the time interval (TimeLike, see start_time).
parameters (str | list[str] | None, default=None) – Variable(s) to get, e.g. ‘TG’ or [‘RH’, ‘TG’, ‘EV24’].
edr_key (str | None, default=None) – Optional KNMI EDR API key. Falls back to the KNMI_EDR_API_KEY environment variable (or KNMI_EDR_API_KEY_FILE). Note KNMI issues a separate key per API: the Open Data key does not work for EDR.
**kwargs (Any) – Forwarded to AsyncEDRClient.get_location (e.g. output_format).
- Returns:
In-memory dataset with a time dimension.
- Return type:
xr.Dataset
- knmidata.parse_coverage(payload: dict[str, Any], shared_parameters: dict[str, Any] | None = None) Dataset¶
Parse a single OGC CoverageJSON coverage into an xarray.Dataset.
Dimension order follows the order of the axes in
domain.axes, matching the flattened order of the range values.- Parameters:
payload (dict[str, Any]) – A single CoverageJSON coverage object.
shared_parameters (dict[str, Any] | None, default=None) – Parameter metadata from the enclosing CoverageCollection, used when the coverage itself has no “parameters” member (KNMI puts them at the collection level and only “ranges” in each coverage).
- Returns:
Multidimensional dataset.
- Return type:
xr.Dataset
- knmidata.parse_coveragejson(payload: dict[str, Any]) Dataset¶
Parse an OGC CoverageJSON payload into an xarray.Dataset.
Handles both single coverages and CoverageCollections (as returned by /area, /cube, or multi-location queries on station collections). Coverages are concatenated along the
stationdimension, labelled with the station id (WSI) when the response carries it, else the grid origin, else acoverageindex.- Parameters:
payload (dict[str, Any]) – Parsed JSON response from an EDR data query with f=CoverageJSON.
- Returns:
Multidimensional dataset.
- Return type:
xr.Dataset
- knmidata.parse_geojson(payload: dict[str, Any]) Dataset¶
Parse a GeoJSON FeatureCollection into an xarray.Dataset.
Used for EDR responses with f=GeoJSON (e.g. /locations or point queries on station collections). The dataset gets a ‘feature’ dimension, lon/lat/time coordinates when present, and one data variable per numeric property.
- Parameters:
payload (dict[str, Any]) – Parsed JSON response from an EDR query with f=GeoJSON.
- Returns:
Dataset with one entry per feature.
- Return type:
xr.Dataset
- knmidata.resolve_edr_auth(api_key: str | None = None) Auth¶
Resolve authentication strategy for the EDR API.
The EDR API has no anonymous key; every API key is tied to one API, so an Open Data key does not work here.
Resolution order: 1. Explicitly passed api_key. 2. Environment variable KNMI_EDR_API_KEY. 3. File path in environment variable KNMI_EDR_API_KEY_FILE.
- Parameters:
api_key (str | None, default=None) – Optional explicit API key.
- Returns:
Configured authentication strategy.
- Return type:
httpx.Auth
- Raises:
KNMIAuthError – If no key can be resolved from arguments or environment variables.
- knmidata.resolve_open_data_auth(api_key: str | None = None) Auth¶
Resolve authentication strategy for the Open Data API.
KNMI issues a separate key per API (an Open Data key does not work for the EDR API and vice versa), so there is no general KNMI_API_KEY.
Resolution order: 1. Explicitly passed api_key. 2. Environment variable KNMI_OPENDATA_API_KEY. 3. File path in environment variable KNMI_OPENDATA_API_KEY_FILE. 4. KNMI public anonymous key (scraped from the docs page, cached).
- Parameters:
api_key (str | None, default=None) – Optional explicit API key.
- Returns:
Configured authentication strategy.
- Return type:
httpx.Auth
- knmidata.show_versions() None¶
Print versions of knmidata and its runtime dependencies.
- knmidata.to_iso8601(value: str | Timestamp | datetime | date) str¶
Normalize a time-like value to an ISO-8601 string in UTC with a ‘Z’ suffix.
Naive values are assumed to be UTC; timezone-aware values are converted to UTC.
- Parameters:
value (TimeLike) – ISO-8601 string, pandas Timestamp, datetime, or date.
- Returns:
Timestamp in UTC, e.g. ‘2024-01-01T00:00:00Z’.
- Return type:
str