在 R 中从 Marvel 的 API 检索数据(错误:is.response(x) 不是 TRUE) [英] Retrieving Data from Marvel's API in R (Error: is.response(x) is not TRUE)
问题描述
我正在尝试使用 R 从 Marvel 的 API 中检索数据.但我的代码如下所示:
I am trying to retrieve Data from Marvel's API with R. Yet my code looks like this:
library(jsonlite)
library(httr)
library(digest)
pb.txt <- Sys.time()
pb.date <- as.POSIXct(pb.txt, tz = Sys.timezone)
time.stamp = strtrim(format(pb.date, tz = "GMT", usetz = FALSE, "%Y-%m-%dT%H:%M:%SZ"), 24)
public.key <- "***********************"
private.key <- "**********************************"
hash <- digest(paste0(time.stamp, private.key, public.key), algo = "md5")
url <- GET(paste("http://gateway.marvel.com/v1/public/characters?ts=", time.stamp, "&apikey=", public.key, "&hash=", hash, sep = ""))
我在这里得到的错误是:
The Error I get here is after:
> content(url)
$code
[1] "InvalidCredentials"
$message
[1] "That hash, timestamp and key combination is invalid."
之前的主要问题是时间戳,我仍然不确定我是否以正确的方式计算它.这是 API 的文档.
Beforehand the main problem was the timestamp, and I am still not sure if I calculate it the right way. Here is the Documentation for the API.
我希望有更多 API 经验的人可以帮助我.
I hope anybody with more experiences with APIs could help me.
推荐答案
您可以使用它来引导参数到 API 请求(将您的密钥存储在命名相当明显的环境变量中,最好在 ~/.Renviron
):
You can use this to bootstrap the parameters to the API requests (storing your keys in the fairly obviously named environment variables, best set in ~/.Renviron
):
marvel_hash_params <- function() {
ts <- round(as.numeric(Sys.time())*1000) # can totally be just Sys.time(), too
to_hash <- sprintf("%s%s%s",
ts,
Sys.getenv("MARVEL_API_PRIVATE_KEY"),
Sys.getenv("MARVEL_API_PUBLIC_KEY"))
list(
ts=ts,
hash=digest::digest(to_hash, "md5", FALSE),
apikey=Sys.getenv("MARVEL_API_PUBLIC_KEY")
)
}
然后立即在您的辅助函数中初始化它们:
Then initialize them right away in your helper functions:
get_characters <- function(name) {
params <- marvel_hash_params()
params$name <- name
res <- httr::GET("https://gateway.marvel.com:443/v1/public/characters",
query=params)
httr::stop_for_status(res)
httr::content(res, as="parsed")
}
get_characters("spider-man")
即使您没有编写完整的软件包,我也建议您阅读 Hadley 的 建议
Even if you're not writing a full-on package, I'd suggest reading Hadley's recommendations
这篇关于在 R 中从 Marvel 的 API 检索数据(错误:is.response(x) 不是 TRUE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!