Skip to content

API Reference

Client

Main async aggregation client.

initialize async

initialize() -> None

Validate provider configs and initialize provider instances.

close async

close() -> None

Close HTTP resources.

lookup_location_timezone async

lookup_location_timezone(
    latitude: float, longitude: float
) -> str

Resolve an IANA zone through the client's configured HTTP transport.

forecast async

forecast(request: ForecastRequest) -> ForecastResponse

Fetch forecasts from the selected providers.

get_provider_capabilities

get_provider_capabilities() -> dict[
    ProviderId, PluginCapabilities
]

Return capabilities for initialized providers.

get_configured_providers

get_configured_providers() -> list[ProviderId]

Return enabled configured providers.

Create and initialize an OmniWeather client.

plugins scopes the plugin set to this client instance — pass a sequence of plugins or a mapping keyed by provider id. When omitted, the client falls back to the process-global registry.

metrics_hooks receive a MetricEvent for every request attempt, retry, cache hit/miss, and quota consumption.

Request and response types

ForecastRequest

Bases: BaseModel

Public forecast request.

ForecastResponse

Bases: BaseModel

Public aggregated response.

ForecastResponseSummary

Bases: BaseModel

ProviderSuccess

Bases: BaseModel

Successful provider response.

ProviderError

Bases: BaseModel

Failed provider response.

ProviderErrorDetail

Bases: BaseModel

Structured provider error payload.

SourceForecast

Bases: BaseModel

A complete normalized forecast for one model or provider source.

WeatherDataPoint

Bases: BaseModel

A normalized point-in-time forecast row.

MinutelyDataPoint

Bases: BaseModel

Normalized minutely precipitation point.

DailyDataPoint

Bases: BaseModel

Normalized daily summary row.

WeatherAlert

Bases: BaseModel

Normalized weather alert.

WeatherCondition

Bases: str, Enum

Closed normalized condition vocabulary.

Granularity

Bases: str, Enum

ErrorCode

Bases: str, Enum

ProviderId

Bases: str, Enum

Every supported provider has a stable slug.

ProviderLogEvent dataclass

Structured log event emitted by the client for each provider interaction.

__setstate__

__setstate__(state: EventState) -> None

Restore current slot state or the dictionary state used before 1.0.

Configuration types

RetryPolicy

Bases: BaseModel

Retry policy for transient provider failures.

ProviderRegistration

Bases: BaseModel

Configuration for one registered provider.

RateLimitConfig

Bases: BaseModel

Global rate-limiting policy.

HTTPConfig

Bases: BaseModel

Shared HTTP client settings.

OmniWeatherConfig

Bases: BaseModel

Top-level client configuration.

Plugin protocol

ProviderConfigModel

Bases: BaseModel

Base model for provider-specific config payloads.

PluginCapabilities

Bases: BaseModel

Describes what a provider supports.

PluginFetchParams

Bases: BaseModel

Request parameters passed to one provider.

WeatherPlugin

Bases: Protocol

Protocol that every provider plugin must implement.

id property

id: ProviderId

Unique provider identifier.

name property

name: str

Human-readable provider name.

validate_config

validate_config(config: dict[str, Any]) -> Any

Return a validated config object or raise ValidationError.

initialize async

initialize(config: Any) -> PluginInstance

Return a configured plugin instance.

PluginInstance

Bases: Protocol

A configured, ready-to-use provider instance.

provider_id property

provider_id: ProviderId

Return the provider identifier.

fetch_forecast async

fetch_forecast(
    params: PluginFetchParams, client: AsyncClient
) -> PluginFetchResult

Fetch and normalize forecast data.

Implementations must not raise. Errors should be reported through PluginFetchError instead.

get_capabilities

get_capabilities() -> PluginCapabilities

Return provider capabilities metadata.

Metrics

Structured metric events emitted by the client.

MetricKind

Bases: StrEnum

Kinds of measurements the client emits.

MetricEvent dataclass

One measurement emitted by the client.

provider is None for cache events, which are observed at the shared HTTP transport where no per-provider attribution exists; those events carry the request url instead.

__setstate__

__setstate__(state: EventState) -> None

Restore slot state while applying the timestamp contract.

OpenTelemetry bridge

Optional OpenTelemetry bridge for MetricsHook events.

Requires the otel extra::

pip install "omni-weather-forecast-apis[otel]"

create_otel_metrics_hook

create_otel_metrics_hook(
    meter_provider: Any | None = None,
) -> MetricsHook

Build a MetricsHook that records events as OpenTelemetry metrics.

Instruments created (all under the omni_weather prefix):

  • omni_weather.requests (counter; attrs: provider, outcome)
  • omni_weather.request.duration_ms (histogram; attrs: provider)
  • omni_weather.retries (counter; attrs: provider, error_code)
  • omni_weather.cache (counter; attrs: outcome)
  • omni_weather.quota.consumed (counter; attrs: provider)
  • omni_weather.quota.exhausted (counter; attrs: provider)

meter_provider defaults to the globally configured provider.

Quota tracking

Daily request-quota tracking for providers with per-day call limits.

QuotaTracker

Bases: Protocol

Tracks how many requests were sent per provider per UTC day.

get_usage

get_usage(provider: ProviderId, day: date) -> int

Return the number of requests recorded for a provider on a day.

record_request

record_request(provider: ProviderId, day: date) -> None

Record one request for a provider on a day.

try_consume

try_consume(
    provider: ProviderId, day: date, limit: int
) -> bool

Record one request only when the provider has remaining quota.

InMemoryQuotaTracker

Process-local quota tracker; state is lost when the process exits.

try_consume

try_consume(
    provider: ProviderId, day: date, limit: int
) -> bool

Record one request only when the provider has remaining quota.

SqliteQuotaTracker

Quota tracker persisted in SQLite so limits survive across runs.

The CLI reuses the forecast database, giving free-tier daily caps (e.g. OpenWeather's 1,000 calls/day) durable enforcement.

try_consume

try_consume(
    provider: ProviderId, day: date, limit: int
) -> bool

Atomically reserve one daily request when quota remains.

HTTP caching

HTTP response caching with conditional-request revalidation.

Implements a small, standards-aware cache for GET requests as an httpx2 transport wrapper. Fresh responses (Cache-Control: max-age / Expires) are served without a network round-trip; stale responses that carry validators (ETag / Last-Modified) are revalidated with conditional headers and reused on 304 Not Modified.

MET Norway's terms of service require If-Modified-Since support and the NWS strongly encourages caching, so the cache is enabled by default.

CachingTransport

Bases: AsyncBaseTransport

Wrap a transport with an in-memory ETag/Expires-aware GET cache.

Environment placeholders

Environment-variable placeholder resolution for provider configs.

Keeps secrets such as API keys out of TOML files. Two placeholder forms are supported inside a provider config block:

  • a whole-string reference: api_key = "${OPENWEATHER_API_KEY}"
  • an explicit marker table: api_key = { env = "OPENWEATHER_API_KEY" }

Resolution is recursive through nested tables and arrays. A placeholder that names an unset environment variable raises :class:EnvVarNotSetError, which surfaces as a per-provider initialization error.

EnvVarNotSetError

Bases: LookupError

Raised when a config placeholder references an unset variable.

resolve_env_placeholders

resolve_env_placeholders(value: Any) -> Any

Recursively resolve ${VAR} and {env = "VAR"} placeholders.

SQLite persistence

save_forecast_response

save_forecast_response(
    database_path: str | Path,
    response: ForecastResponse,
    *,
    raw_archive_path: str | Path | None = None,
) -> int

Persist one normalized forecast response into SQLite.

save_provider_logs

save_provider_logs(
    database_path: str | Path,
    events: list[ProviderLogEvent],
    run_id: int | None = None,
) -> None

Persist provider log events into the provider_logs table.