Andy Meinke Andy Meinke - 1 month ago 27
R Question

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

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.

Answer

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

Comments