Retrieving Data from Marvel's API in R (Error: is.response(x) is not TRUE)

Retrieving Data from Marvel's API in R (Error: is.response(x) is not TRUE)

我正在尝试使用 R 从 Marvel 的 API 中检索数据。但我的代码如下所示:

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 = ""))

我在这里得到的错误是在:

之后
> content(url) 

$code
[1] "InvalidCredentials"

$message
[1] "That hash, timestamp and key combination is invalid."

之前的主要问题是时间戳,我仍然不确定我是否以正确的方式计算它。 这是 API 的 Documentation

我希望对 API 有更多经验的人可以帮助我。

您可以使用它来 bootstrap API 请求的参数(将您的密钥存储在名称相当明显的环境变量中,最好在 ~/.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")
  )

}

然后立即在您的辅助函数中初始化它们:

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 的 recommendations