【发布时间】:2018-08-02 23:50:28
【问题描述】:
我正在尝试使用 httr 包将数据直接从 API 提取到 R 中。 API 不需要任何身份验证,并接受 lat、long、elevation、变量集和时间段的 JSON 字符串来估计任何位置的气候变量。这是我第一次使用 API,但下面的代码是我从各种 Stack Overflow 帖子中拼凑而成的。
library(jsonlite)
library(httr)
url = "http://apibc.climatewna.com/api/clmApi"
body <- data.frame(lat = c(48.98,50.2), ##two example locations
lon = c(-115.02, -120),
el = c(1000,100),
prd = c("Normal_1961_1990.nrm","Normal_1961_1990.nrm"),
varYSM = c("Y","SST"))
requestBody <- toJSON(list("output" = body),auto_unbox = TRUE) ##convert to JSON string
result <- POST("http://apibc.climatewna.com/api/clmApi", ##post to API
body = requestBody,
add_headers(`Content-Type`="application/json"))
content(result)
我尝试了各种不同的版本(例如手动编写 JSON 字符串,将正文作为列表放入 POST 中,encode = "json"),它始终运行,但内容始终包含以下错误消息:
$Message
[1] "An error has occurred."
$ExceptionMessage
[1] "Object reference not set to an instance of an object."
$ExceptionType
[1] "System.NullReferenceException"
如果我使用 GET 并直接在 URL 中指定变量
url = "http://apibc.climatewna.com/api/clmApi/LatLonEl?lat=48.98&lon=-115.02&el=1000&prd=Normal_1961_1990&varYSM=Y"
result <- GET(url)
content(result)
它会产生正确的输出,但是我一次只能获取一个位置的信息。目前没有任何关于这个 API 的公共文档,因为它很新,但我附上了使用 JS 下面解释它的部分草稿。我非常感谢任何关于我正在做的事情的帮助/建议错误的! 谢谢!
【问题讨论】:
-
API 是否记录在某处?网上好像找不到
-
不 - 这是一个非常新的开发,尚未正式发布。这是一个用于 ClimateBC 的 API,作为桌面应用已经存在了几年。