0

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>
Community
  • 1
  • 1
stevec
  • 41,291
  • 27
  • 223
  • 311
  • Have you looked at the docs? `?httr::POST` references `httr::add_headers`, which has examples, as does the [intro vignette](https://cran.r-project.org/web/packages/httr/vignettes/quickstart.html) – camille Jul 09 '19 at 18:31
  • This works for me. Maybe it's your package versions? I have httr 1.4.0, jsonlite 1.6, curl 3.2 – Andreas Jul 09 '19 at 19:34
  • @camille thank you. I had checked both but hadn't realised `add_headers` worked with functions other than `httr::GET`. Many thanks – stevec Jul 10 '19 at 07:36

1 Answers1

3

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'))
tvdo
  • 151
  • 3