Search code examples
rhttr

Pass array in query params httr


How do I pass an array into the query of httr? The request url should look like that: https://www.example.com/xyz?type=3&type=5

My current code looks like that:

POST(url,
query = data.frame("something" = "somethingElse", type = ),
add_headers(.headers = c("token" = token),
encode = "json")

How do I add those types from the url example to my R example?


Solution

  • The default encoding for httr doesn't like to use the same name multiple times, but it is possible to separate your values into lists which have duplicate names. Here's a helper function i've used that can help

    flattenbody <- function(x) {
      # A form/query can only have one value per name, so take
      # any values that contain vectors length >1 and
      # split them up
      # list(x=1:2, y="a") becomes list(x=1, x=2, y="a")
      if (all(lengths(x)<=1)) return(x);
      do.call("c", mapply(function(name, val) {
        if (length(val)==1 || any(c("form_file", "form_data") %in% class(val))) {
          x <- list(val)
          names(x) <- name
          x
        } else {
          x <- as.list(val)
          names(x) <- rep(name, length(val))
          x
        }
      }, names(x), x, USE.NAMES = FALSE, SIMPLIFY = FALSE))
    }
    

    Then you could use it with something like

    POST(url,
      query = flattenbody(list(something="somethingElse", type = c(3, 5))),
      add_headers(.headers = c("token" = token)),
      encode = "json"
    )