R/newsapi_key.R

Defines functions newsapi_key

Documented in newsapi_key

#' Load api key if present. If not append apikey to .Renviron

#' @param apikey Character sring api key

#' @return apikey
#' @importFrom httr http_error GET  status_code
#' @export
newsapi_key <- function(apikey) {

  if (missing(apikey)) {

    apikey <- Sys.getenv("NEWSAPIKEY")

    if (identical(apikey, "")) {
      stop("No valid apikey detected. Please put your key into the Renviron OR pass it to this function as formal argument",
        call. = FALSE)
    }
  } else {
    test_key <- paste0("https://newsapi.org/v2/sources?apiKey=", apikey, "&")
    resp <- httr::GET(test_key)
    if (httr::http_error(resp)) {
      stop("Newsapi request failed. Please validate your apikey.", httr::status_code(resp))
      call. = FALSE
    } else {
      cat(paste0("NEWSAPIKEY=", apikey), append = TRUE, fill = TRUE, file = file.path("~",
        ".Renviron"))
    }
  }
  return(apikey)
}
data-atelier/newsExtractoR documentation built on April 6, 2018, 2:54 a.m.