|
| 1 | +#' Return list of available datasets |
| 2 | +#' |
| 3 | +#' @description |
| 4 | +#' Return a list of available datasets, available to filter by state and year |
| 5 | +#' |
| 6 | +#' @param state US state 2 character abbreviation |
| 7 | +#' |
| 8 | +#' @param year 4 year digit |
| 9 | +#' |
| 10 | +#' @param legiKey 32 character string provided by legiscan |
| 11 | +#' |
| 12 | +#' @returns available datasets for download |
| 13 | +#' |
| 14 | +#' @export |
| 15 | +getDatasetList <- function(state = NULL, year = NULL, legiKey = NULL){ |
| 16 | + op <- "getDatasetList" |
| 17 | + |
| 18 | + if (is.null(legiKey)){ |
| 19 | + legiKey <- getlegiKey() |
| 20 | + } |
| 21 | + if (nchar(legiKey)!=32){ |
| 22 | + warning(paste0("Invalid API Key: ",legiKey,"\nRegister <https://legiscan.com/user/register>\nStore with `setlegiKey`")) |
| 23 | + return(paste0("Invalid API Key: ",legiKey,"\nRegister <https://legiscan.com/user/register>\nStore with `setlegiKey`")) |
| 24 | + } |
| 25 | + |
| 26 | + if (!is.null(year)){ |
| 27 | + if(nchar(year) !=4){ |
| 28 | + warning("year should be 4 digits") |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + tryCatch({ |
| 33 | + req <- httr2::request("https://api.legiscan.com") |> |
| 34 | + httr2::req_url_query( |
| 35 | + key = legiKey, |
| 36 | + op = op, |
| 37 | + state = state, |
| 38 | + state = year, |
| 39 | + .multi = "explode" |
| 40 | + ) |> |
| 41 | + httr2::req_perform() |
| 42 | + |
| 43 | + status <- httr2::resp_status(req) |
| 44 | + if (status != 200) { |
| 45 | + stop(sprintf("API request failed with status code: %d", status)) |
| 46 | + } |
| 47 | + |
| 48 | + response <- httr2::resp_body_json(req) |
| 49 | + |
| 50 | + if (!is.null(response$status)) { |
| 51 | + if (response$status != "OK") { |
| 52 | + stop(sprintf("API returned error: %s", response$alert)) |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return(dplyr::bind_rows(response$datasetlist)) |
| 57 | + }, error = function(e) { |
| 58 | + stop(sprintf("Error in API request: %s", e$message)) |
| 59 | + }) |
| 60 | +} |
0 commit comments