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

匿名 (未验证) 提交于 2019-12-03 01:09:02

问题:

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." 

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.

I hope anybody with more experiences with APIs could help me.

回答1:

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

Even if you're not writing a full-on package, I'd suggest reading Hadley's recommendations



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!