在R中从Marvel的API检索数据(错误:is.response(x)不为TRUE) [英] Retrieving Data from Marvel's API in R (Error: is.response(x) is not TRUE)

查看:132
本文介绍了在R中从Marvel的API检索数据(错误:is.response(x)不为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 = ""))

以下是我得到的错误:

> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆