r-lib / httr

httr: a friendly http package for R
https://httr.r-lib.org
Other
986 stars 1.99k forks source link

more docs on creating a complex request body #726

Closed nick-youngblut closed 10 months ago

nick-youngblut commented 1 year ago

Currently the httr vignette only shows a simple example of creating a request body:

r <- POST("http://httpbin.org/post", body = list(a = 1, b = 2, c = 3))

It would be helpful to have more complex body example, given that POST requests can require formats such as:

{
  "key1":
    [
      {
      "key1" : "value",
      "key2" : "value",
      "key3" : "value"
      }
    ]
  }

...and naively trying to create such a structure in R with any of the following approaches does not work:

# using `c()`
body = list('key1' = c(list('key1' = 'value', 'key2' = 'value', 'key3' = 'value')))

 # using `array()`
body = list('key1' = array(list('key1' = 'value', 'key2' = 'value', 'key3' = 'value')))

 # using `matrix()`
body = list('key1' = matrix(list('key1' = 'value', 'key2' = 'value', 'key3' = 'value')))

In each approach, the resulting data structure is not list(vector(list())).

The POST function docs also do not describe how to create such a data structure in R.

hadley commented 10 months ago

httr has been superseded in favour of httr2, so is no longer under active development. But it sounds like your issue is really about how to create JSON from an R data structure, so you may find it easier to iterate directly with jsonlite::toJSON().