47 lines
1.8 KiB
R
47 lines
1.8 KiB
R
#' Perform a GET request with retries
|
|
#'
|
|
#' This function attempts to perform a GET request to the specified URL with the provided headers
|
|
#' and checks for a specific HTTP status code. It retries the request if the desired status code is not received,
|
|
#' or if the request results in an error.
|
|
#'
|
|
#' @param url_with_params The full URL to which the GET request is made, including any necessary query parameters.
|
|
#' @param headers A list of headers to include in the GET request.
|
|
#' @param code The desired HTTP status code for a successful request.
|
|
#'
|
|
#' @return NULL if the request does not succeed within the retry limit or if the desired status code is not achieved.
|
|
#' Otherwise, returns the response from the successful GET request.
|
|
#' @examples
|
|
#' \dontrun{
|
|
#' url <- "http://example.com/api"
|
|
#' headers <- list(Authorization = "Bearer TOKEN", Accept = "application/json")
|
|
#' code <- 200 # Looking for a '200 OK' response
|
|
#' response <- requests(url, headers, code)
|
|
#' if (is.null(response)) {
|
|
#' print("Request failed or did not return the expected status code.")
|
|
#' } else {
|
|
#' print("Request succeeded.")
|
|
#' }
|
|
#' }
|
|
#' @export
|
|
#' @import httr
|
|
request_api <- function(url_with_params,headers,code,retry_limit=5,timesleep=20){
|
|
retry_count <- 0
|
|
success <- FALSE
|
|
|
|
while(retry_count < retry_limit && !success) {
|
|
response <- tryCatch(GET(url_with_params, headers),error=function(e){print(e);NULL})
|
|
print(response)
|
|
if(!is.null(response) && (response$status_code %in% code)) {
|
|
success <- TRUE
|
|
} else {
|
|
print(url_with_params)
|
|
print(paste0("retry #",retry_count,"/",retry_limit))
|
|
retry_count <- retry_count + 1
|
|
Sys.sleep(timesleep*(1+retry_count/retry_limit))
|
|
}
|
|
}
|
|
if(!success) return(NULL)
|
|
else return(response)
|
|
|
|
}
|
|
|