假设您有一个 DSX 帐户,那么您还应该有一个 IBM Cloud 帐户。如果您在 IBM Cloud 中添加 Weather Company Data 服务,那么您将获得服务凭证(即用户名和密码)。有了凭据,您就可以使用 httr 库,例如,在 RStudio 中使用 Weather Company API 发出 HTTP 请求,例如:
library(httr)
r <- GET("https://<username>:<password>@twcservice.mybluemix.net:443/api/weather/v1/geocode/45.42/75.69/forecast/hourly/48hour.json?units=m&language=en-US")
content(r, "text")
[1] "{\"metadata\":{\"language\":\"en-US\",\"transaction_id\":\"1512488325604:776158712\",\"version\":\"1\",\"latitude\":45.42,\"longitude\":75.69,\"units\":\"m\",\"expire_time_gmt\":1512488925,\"status_code\":200},\"forecasts\":[{\"class\":\"fod_short_range_hourly\",\"expire_time_gmt\":1512488925,\"fcst_valid\":1512489600,\"fcst_valid_local\":\"2017-12-05T22:00:00+0600\",\"num\":1,\"day_ind\":\"N\",\"temp\":-5,\"dewpt\":-5,\"hi\":-5,\"wc\":-8,\"feels_like\":-8,\"icon_extd\":2600,\"wxman\":\"wx1210\",\"icon_code\":26,\"dow\":\"Tuesday\",\"phrase_12char\":\"Cloudy\",\"phrase_22char\":\"Cloudy\",\"phrase_32char\":\"Cloudy\",\"subphrase_pt1\":\"Cloudy\",\"subphrase_pt2\":\"\",\"subphrase_pt3\":\"\",\"pop\":0,\"precip_type\":\"snow\",\"qpf\":0.0,\"snow_qpf\":0.0,\"rh\":100,\"wspd\":6,\"wdir\":236,\"wdir_cardinal\":\"SW\",\"gust\":null,\"clds\":81,\"vis\":16.0,\"mslp\":1034.4,\"uv_index_raw\":0,\"uv_index\":0,\"uv_warning\":0,\"uv_desc\":\"Low\",\"golf_index\":null,\"golf_category\":\"\",\"... <truncated>
这将为您提供加拿大渥太华的 48 小时天气预报。
要获取结果的数据框,请使用以下内容:
library(httr)
library(jsonlite)
r <- GET("https://<username>:<password>@twcservice.mybluemix.net:443/api/weather/v1/geocode/45.42/75.69/forecast/hourly/48hour.json?units=m&language=en-US")
weather <- content(r, "text")
wData <- fromJSON(weather)
weatherDF <- data.frame(wData)
此处为https://console.bluemix.net/docs/services/Weather/weather_tutorials_samples.html#tutorials_samples 提供了一些向您展示如何在 IBM Cloud 上使用 Weather Company API 的示例。