Waiting for an API request to complete

January 26, 2013
By

(This article was first published on Recology - R, and kindly contributed to R-bloggers)

Dealing with API tokens in R

In my previous post I showed an example of calling the Phylotastic taxonomic name resolution API Taxosaurus here. When you query their API they give you a token which you use later to retrieve the result (see examples on their page above). However, you don't know when the query will be done, so how do we know when to send the query to rerieve the data?


As the time this takes depends on how big the query is and other things, we don't know when we can get the result. I struggled with this for a bit, but then settled on using a while loop.


So what does this look like? Basically we just keep sending the request for data until we get it.

iter <- 0  # make an iterator so each time we call
output <- list()  # make an empty list to put data into
timeout <- "wait"
while (timeout == "wait") {
    iter <- iter + 1  # increase the iterator each time
    temp <- fromJSON(getURL(retrieve))  # send the request and parse the JSON
    if (grepl("is still being processed", temp["message"]) == TRUE) {
        timeout <- "wait"
    } else {
        output[[iter]] <- temp  # put result from query in the list
        timeout <- "done"  # we got the result so timeout is now done, making the while loop stop
    }
}

Get the .Rmd file used to create this post at my github account - or .md file.

Written in Markdown, with help from knitr.

To leave a comment for the author, please follow the link and comment on his blog: Recology - R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.