connector-weatherapi

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Weather data with
weatherapi-client

使用
weatherapi-client
获取天气数据

Motoko bindings for WeatherAPI.com, generated from its OpenAPI spec. All nine operations live in a single module,
Apis/APIsApi
, and all nine are read-only
GET
s.
用于 WeatherAPI.com 的 Motoko 绑定,基于其 OpenAPI spec 生成。全部九项操作都位于同一个模块
Apis/APIsApi
中,且均为只读
GET
请求。

Backend

后端

A canister that reads the current temperature and a three-day maximum series. Non-replicated is the default, so you only supply the key:
motoko
import { realtimeWeather; forecastWeather } "mo:weatherapi-client/Apis/APIsApi";
import { type Config; defaultConfig } "mo:weatherapi-client/Config";
import Array "mo:core/Array"; // in scope so `days.map(…)` dot notation resolves

persistent actor {
  // The key is a query-string credential. Hold it in a stable variable set by
  // an admin call; never hard-code it in source.
  func config(apiKey : Text) : Config = { defaultConfig with auth = ?#apiKey apiKey };

  // `q` is any WeatherAPI location query: "Zurich", "47.37,8.55", a postcode,
  // an IATA code, or "auto:ip".
  public func currentTempC(apiKey : Text, q : Text) : async ?Float {
    let res = await* realtimeWeather(config apiKey, q, "");
    do ? { res.current!.temp_c! };
  };

  // Daily maxima for the next three days.
  public func maxTempsC(apiKey : Text, q : Text) : async [?Float] {
    let res = await* forecastWeather(config apiKey, q, #_3_, "", 0, 0, "", "no", "no", 0);
    let ?forecast = res.forecast else return [];
    let ?days = forecast.forecastday else return [];
    days.map(func(d) = do ? { d.day!.maxtemp_c! });
  };
}
一个读取当前温度和三日最高温度序列的 canister。默认采用非复制模式,因此只需提供 key:
motoko
import { realtimeWeather; forecastWeather } "mo:weatherapi-client/Apis/APIsApi";
import { type Config; defaultConfig } "mo:weatherapi-client/Config";
import Array "mo:core/Array"; // in scope so `days.map(…)` dot notation resolves

persistent actor {
  // The key is a query-string credential. Hold it in a stable variable set by
  // an admin call; never hard-code it in source.
  func config(apiKey : Text) : Config = { defaultConfig with auth = ?#apiKey apiKey };

  // `q` is any WeatherAPI location query: "Zurich", "47.37,8.55", a postcode,
  // an IATA code, or "auto:ip".
  public func currentTempC(apiKey : Text, q : Text) : async ?Float {
    let res = await* realtimeWeather(config apiKey, q, "");
    do ? { res.current!.temp_c! };
  };

  // Daily maxima for the next three days.
  public func maxTempsC(apiKey : Text, q : Text) : async [?Float] {
    let res = await* forecastWeather(config apiKey, q, #_3_, "", 0, 0, "", "no", "no", 0);
    let ?forecast = res.forecast else return [];
    let ?days = forecast.forecastday else return [];
    days.map(func(d) = do ? { d.day!.maxtemp_c! });
  };
}

The nine operations

九项操作

FunctionEndpointReturns
realtimeWeather(cfg, q, lang)
/current.json
RealtimeWeather200Response
forecastWeather(cfg, q, days, dt, unixdt, hour, lang, alerts, aqi, tp)
/forecast.json
ForecastWeather200Response
historyWeather(cfg, q, dt, unixdt, endDt, unixendDt, hour, lang)
/history.json
FutureWeather200Response
futureWeather(cfg, q, dt, lang)
/future.json
FutureWeather200Response
marineWeather(cfg, q, days, dt, unixdt, hour, lang)
/marine.json
MarineWeather200Response
astronomy(cfg, q, dt)
/astronomy.json
Astronomy200Response
timeZone(cfg, q)
/timezone.json
Location
ipLookup(cfg, q)
/ip.json
Ip
searchAutocompleteWeather(cfg, q)
/search.json
[Search]
days
is an enum, not a number:
ForecastWeatherDaysParameter
is
#_1_
…
#_14_
and
MarineWeatherDaysParameter
is
#_1_
…
#_7_
(the underscores are how the generator escapes numeric enum values —
#_3_
, not
#_3
or
3
).
函数端点返回值
realtimeWeather(cfg, q, lang)
/current.json
RealtimeWeather200Response
forecastWeather(cfg, q, days, dt, unixdt, hour, lang, alerts, aqi, tp)
/forecast.json
ForecastWeather200Response
historyWeather(cfg, q, dt, unixdt, endDt, unixendDt, hour, lang)
/history.json
FutureWeather200Response
futureWeather(cfg, q, dt, lang)
/future.json
FutureWeather200Response
marineWeather(cfg, q, days, dt, unixdt, hour, lang)
/marine.json
MarineWeather200Response
astronomy(cfg, q, dt)
/astronomy.json
Astronomy200Response
timeZone(cfg, q)
/timezone.json
Location
ipLookup(cfg, q)
/ip.json
Ip
searchAutocompleteWeather(cfg, q)
/search.json
[Search]
days
是枚举,而不是数字:
ForecastWeatherDaysParameter
的取值为
#_1_
至
#_14_
,
MarineWeatherDaysParameter
的取值为
#_1_
至
#_7_
(下划线是生成器转义数值枚举值的方式——应写为
#_3_
,而不是
#_3
或
3
)。

API key setup

API key 设置

  1. Sign up at weatherapi.com — the free tier covers current weather, 3-day forecast, astronomy, timezone, search and IP lookup. History, future, marine and 14-day forecasts need a paid plan and return 403 on free keys.
  2. Copy the key from the dashboard and pass it as
    auth = ?#apiKey key
    .
  3. The client appends it as
    ?key=…
    (WeatherAPI takes no
    Authorization
    header), so it appears in the request URL. Keep it in a stable variable written by an admin-only call, and never log the built URL.
  1. 在 weatherapi.com 注册——免费套餐支持当前天气、三日预报、天文、时区、搜索和 IP 查询。历史、未来、海洋和十四日预报需要付费套餐,使用免费 key 时会返回 403。
  2. 从 dashboard 复制 key,并按
    auth = ?#apiKey key
    的形式传入。
  3. 客户端会将其作为
    ?key=…
    附加(WeatherAPI 不接受
    Authorization
    header),因此它会出现在 request URL 中。应将其保存在由仅限管理员调用的方法写入的稳定变量中,绝不要记录构建后的 URL。

Calls are non-replicated by default

调用默认采用非复制模式

The package ships
is_replicated = ?false
in
defaultConfig
, and that is a correctness requirement here, not just a cost saving. Every response carries per-request clocks —
Location.localtime
/
localtime_epoch
,
Current.last_updated
/
last_updated_epoch
— which change second to second. A replicated outcall has every subnet node issue its own request and demands bit-identical bodies, so those fields would break consensus on most calls while burning ~13× the cycles. You don't set it yourself; the default is correct.
Override with
is_replicated = ?true
only together with a
transform
that strips the volatile fields.
该 package 在
defaultConfig
中提供了
is_replicated = ?false
,在这里这是正确性要求,不仅仅是节省成本。每个响应都包含按请求生成的时钟信息——
Location.localtime
/
localtime_epoch
、
Current.last_updated
/
last_updated_epoch
——这些值每秒都会变化。replicated outcall 会让每个 subnet 节点分别发出请求,并要求响应正文逐位一致,因此这些字段会在大多数调用中破坏共识,同时消耗约 13× 的 cycles。你不需要自行设置,默认值是正确的。
只有在同时使用会去除这些易变字段的
transform
时,才应将
is_replicated
覆盖为
?true
。

Everything is optional

所有字段均为可选

WeatherAPI marks no response field required, so the generated models are all-optional:
RealtimeWeather200Response.current : ?Current
,
Current.temp_c : ?Float
, and so on. Reach through them with a
do ?
block (
do ? { res.current!.temp_c! }
) rather than nested
switch
es, and decide what an absent field means for your caller — the API omits fields your plan does not cover (for example
air_quality
without the
aqi=yes
parameter).
WeatherAPI 未将任何响应字段标记为 required,因此生成的模型全部为 optional,例如
RealtimeWeather200Response.current : ?Current
、
Current.temp_c : ?Float
。应使用
do ?
block(
do ? { res.current!.temp_c! }
)访问这些字段,而不是嵌套使用
switch
,并明确字段缺失对调用方意味着什么——API 会省略当前套餐不涵盖的字段(例如未设置
aqi=yes
参数时不会返回
air_quality
)。

Empty string and zero mean "omit"

空字符串和零表示“不提供”

Optional query parameters are dropped when they are
""
or
0
, because WeatherAPI rejects empty
lang=
and zero-valued numerics. So passing
""
for
lang
,
dt
,
alerts
,
aqi
and
0
for
unixdt
,
tp
is how you say "not supplied" — there is no
?Text
parameter to leave
null
.
One consequence worth knowing:
hour = 0
does not select midnight
, it omits the
hour
filter entirely and you get the whole day's hourly array. Filter the returned
hour : ?[ForecastForecastdayInnerHourInner]
yourself if you need 00:00.
当可选查询参数为
""
或
0
时会被省略,因为 WeatherAPI 会拒绝值为空的
lang=
和数值为零的参数。因此,为
lang
、
dt
、
alerts
、
aqi
传入
""
,并为
unixdt
、
tp
传入
0
,就是表示“不提供”;不存在可保持
null
的
?Text
参数。
有一个值得注意的结果:
hour = 0
并不会选择午夜
,而是完全省略
hour
filter,并返回整天的 hourly array。如果需要 00:00,请自行过滤返回的
hour : ?[ForecastForecastdayInnerHourInner]
。

Errors

错误

Non-2xx responses and decode failures
throw Error.reject(…)
. The client is generated with
diagnostics
, so the message is
HTTP <status> body[<n>B]=<first 100 chars>: <reason>
— enough to tell a 401 (bad key) from a 403 (endpoint not on your plan) from a 400 (
q
not resolvable) without extra logging. Catch with
try
/
catch
and surface
Error.message(err)
.
非 2xx 响应和解码失败会
throw Error.reject(…)
。客户端在生成时启用了
diagnostics
,因此消息格式为
HTTP <status> body[<n>B]=<first 100 chars>: <reason>
——无需额外 logging,就足以区分 401(key 无效)、403(套餐不包含该端点)和 400(无法解析
q
)。使用
try
/
catch
捕获错误,并通过
Error.message(err)
返回错误信息。