.api_req <- function(api, path) { httr2::request(paste0(api$base_url, path)) |> httr2::req_auth_basic(api$user, api$pass) } .api_check <- function(resp, path) { status <- httr2::resp_status(resp) if (status >= 400) { body <- tryCatch(httr2::resp_body_string(resp), error = function(e) "") log_error("api_error", path = path, status = status, body = body) } httr2::resp_check_status(resp) } api_get <- function(api, path, query = NULL) { req <- .api_req(api, path) if (!is.null(query) && length(query) > 0) { query <- Filter(Negate(is.null), query) if (length(query) > 0) req <- do.call(httr2::req_url_query, c(list(req), query)) } resp <- httr2::req_error(req, is_error = \(r) FALSE) |> httr2::req_perform() if (httr2::resp_status(resp) == 404) return(data.frame()) .api_check(resp, path) result <- httr2::resp_body_json(resp, simplifyVector = TRUE) if (is.null(result) || length(result) == 0) return(data.frame()) if (is.data.frame(result)) return(result) as.data.frame(result, stringsAsFactors = FALSE) } api_get_one <- function(api, path, query = NULL) { req <- .api_req(api, path) if (!is.null(query) && length(query) > 0) { query <- Filter(Negate(is.null), query) if (length(query) > 0) req <- do.call(httr2::req_url_query, c(list(req), query)) } resp <- httr2::req_error(req, is_error = \(r) FALSE) |> httr2::req_perform() if (httr2::resp_status(resp) %in% c(404, 204)) return(data.frame()) .api_check(resp, path) result <- httr2::resp_body_json(resp, simplifyVector = FALSE) if (is.null(result) || length(result) == 0) return(data.frame()) as.data.frame(lapply(result, function(x) if (is.null(x)) NA else x), stringsAsFactors = FALSE) } api_post <- function(api, path, body = list()) { log_debug("api_post", path = path) resp <- .api_req(api, path) |> httr2::req_body_json(body) |> httr2::req_error(is_error = \(r) FALSE) |> httr2::req_perform() .api_check(resp, path) if (httr2::resp_content_type(resp) == "" || httr2::resp_status(resp) == 204) return(invisible(NULL)) result <- httr2::resp_body_json(resp, simplifyVector = FALSE) if (is.null(result)) return(invisible(NULL)) result } api_put <- function(api, path, body = list()) { log_debug("api_put", path = path) resp <- .api_req(api, path) |> httr2::req_method("PUT") |> httr2::req_body_json(body) |> httr2::req_error(is_error = \(r) FALSE) |> httr2::req_perform() .api_check(resp, path) invisible(NULL) } api_patch <- function(api, path, body = list()) { log_debug("api_patch", path = path) resp <- .api_req(api, path) |> httr2::req_method("PATCH") |> httr2::req_body_json(body) |> httr2::req_error(is_error = \(r) FALSE) |> httr2::req_perform() .api_check(resp, path) invisible(NULL) } api_delete <- function(api, path) { log_debug("api_delete", path = path) resp <- .api_req(api, path) |> httr2::req_method("DELETE") |> httr2::req_error(is_error = \(r) FALSE) |> httr2::req_perform() .api_check(resp, path) invisible(NULL) }