Search code examples
rhttr

How to make a POST request with header and data options in R using httr::POST?


I am trying make a POST request with data and header information using httr::POST. I can see how to make a POST request, but I am unable to get it to work with curl's data (-d) and header (-H) options.

This works perfectly in my terminal (obviously with different data/api, but exactly the same format)

curl -H "Accept: application/json" -H "Content-type: application/json" -d '{"name": "Fred", "age": "5"}' "http://www.my-api.com"

Question

How can the above POST request be made (with headers and data) using httr::POST ?

What I've tried so far

library(jsonlite)
my_data <- list(name="Fred", age="5") %>% toJSON

post_url <- "http://www.my-api.com"
r <- POST(post_url, body = my_data) # Data goes in body, I guess?
stop_for_status(r)

I get

Error: Bad Request (HTTP 400).

Inspecting r further

r
Response ["http://www.my-api.com"]
  Date: 2019-07-09 17:51
  Status: 400
  Content-Type: text/html; charset=UTF-8
<EMPTY BODY>

Solution

  • You could try this; with content type and headers added:

    link <- "http://www.my-api.com"
    df <- list(name="Fred", age="5")
    
    httr::POST(url = link,
               body =  jsonlite::toJSON(df, pretty = T, auto_unbox = T),
               httr::add_headers(`accept` = 'application/json'), 
               httr::content_type('application/json'))