1

Some APIs give a token back with the API call instead of the result, then you make a second API call with that token to get the query result. Right now, I just use Sys.sleep() within a function to guess that amount of time it may take for the query to finish and the token to be useable. Seems like there must be a better way. That is, can you iteratively send the second API call with the token every X number of seconds, or fractions of seconds, until success?

Here is a minimal example using the TotalImpact API (http://total-impact.org/api-docs).

require(RCurl); require(stringr); require(RJSONIO)

foo <- function(url, sleep) {
  tt <- getURL(url)
  token <- str_extract(tt[[1]], "[a-z0-9]+")
  message("Pausing a bit for the query to finish...")
  Sys.sleep(time = sleep)
  fromJSON(
    getURL(
      paste("http://total-impact-core.herokuapp.com/item/", token, sep='')))
}
myurl <- "http://total-impact-core.herokuapp.com/tiid/doi/10.1371/journal.pcbi.1000361"
sleeptime <- 4
foo(myurl, sleeptime)

> sessionInfo()
R version 2.15.1 (2012-06-22)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

locale:
[1] C/en_US.UTF-8/C/C/C/C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] RJSONIO_0.98-1 stringr_0.6    RCurl_1.91-1   bitops_1.0-4.1 devtools_0.7  

loaded via a namespace (and not attached):
[1] digest_0.5.2 httr_0.1.1   memoise_0.1  plyr_1.7.1   tools_2.15.1
4

0 回答 0