JPC
JPC

Reputation: 25

R - Loop API Call

I'm using R to successful make API calls. For each individual call I need to alter one or two distinguishing ID's (in the case of the code below activity_id and/or name_id). The code is working fine however I am now in a position where I like to automate this process as opposed to manually changing the ID's for each call. I am wondering if there's a way to loop this using a data frame or list to store the relevant ID's.

I've searched across Stack however I'm yet to find or execute an appropriate solution.

Any help would be appreciated.

Thanks,

JPC

apiKey <-"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI"
example<- GET("url?activity_id=b5cb9359-f0e5-4939-9be3-fc95f8bc7d6b&name_id=f1e17fa6-c40c-4810-9c43-60939e2a9a99",add_headers(Authorization = paste("Bearer", apiKey)))
example <-content(example,"text")
example <-fromJSON(example,flatten = TRUE)
example <-unnest(example,data)
write.csv(example,"example.csv",row.names=F)

Upvotes: 1

Views: 552

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

We could write a function where we dynamically generate url using sprintf based on activity_id and name_id passed.

get_data <- function(activity_id, name_id) {

   url <- sprintf('url?activity_id=%s&name_id=%s', activity_id, name_id)
   example<- httr::GET(url,add_headers(Authorization = paste("Bearer", apiKey)))
   example <- httr::content(example,"text")
   example <- jsonlite::fromJSON(example,flatten = TRUE)
   example <- tidyr::unnest(example,data)
   return(example)
}

and then call it using Map.

out <- Map(get_data, activity_vec, name_vec)

Here activity_vec and name_vec are the vector of respective id's. This will return a list of dataframes in out which can be combined into one dataframe if needed before writing to csv.


If only name_id is changing we can do

get_data <- function(name_id) {
    url <- sprintf('url?activity_id=b5cb9359-f0e5-4939-9be3-fc95f8bc7d6&name_id=%s', name_id)
    example<- httr::GET(url,add_headers(Authorization = paste("Bearer", apiKey)))
    example <- httr::content(example,"text")
    example <- jsonlite::fromJSON(example,flatten = TRUE)
    example <- tidyr::unnest(example,data)
    return(example)
  }

out <- lapply(name_vec, get_data)

Upvotes: 2

Related Questions