format_request.R 1.18 KB
Newer Older
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
1

Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
2
3
4
5
6
#' API query for SDMX output
#'
#' @param url url to query
#'
#' @return dataframe response
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
7
sdmx_request <- function(url) {
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
8
  as.data.frame(rsdmx::readSDMX(url))
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
9
10
}

Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
11
12
13
14
15
#' API query for JSON output
#'
#' @param url url to query
#'
#' @return response: dataframe or list of dataframes
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
16
json_request <- function(url) {
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
17
  jsonlite::fromJSON(rawToChar(httr::GET(url)$content))
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
18
19
}

Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
20
21
22
#' API query for CSV output
#'
#' @param url url to query
23
#' @importFrom utils read.csv
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
24
25
#'
#' @return dataframe response
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
26
27
csv_request <- function(url) {
  read.csv(url)
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
28
29
30
}

# Request function based on expected response
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
31
REQUEST_FUNCTION_MAPPING <- list(
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
32
33
34
35
  "SDMX-ML" = sdmx_request,
  "JSON" = json_request,
  "CSV" = csv_request
)
36
37


Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
38
39
#' Transform a list into a string of parameters
#' list("a" = list("1"), "b" = list("2", "3"))
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
40
#' becomes "a=1&b=2&b=3"
41
#'
42
#' @param filters named list
43
44
#'
#' @return formatted string of parameters
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
45
list_to_string <- function(filters) {
46
47
48
49
50
51
52
53
54
55
56
  string <- ""
  for (prop in ls(filters)) {
    for (value in filters[[prop]]) {
      if (string == "") {
        string <- glue::glue("{prop}={value}")
      } else {
        string <- paste(string, glue::glue("{prop}={value}"), sep = "&")
      }
    }
  }
  string
57
}
58