Search code examples
rpostmanhttr

R httr package - Make POST request to an API with body


I try to make a post request to my API. In Postman it looks like this:

POST: http://localhost:5000/api/login
body: {"secret": "bla"}

This gives me back an access token which works fine. I try the same with the httr packge like this:

login <- list(
  secret = "bla"
)

httr::POST("http://localhost:5000/api/login", body = login, verbose(), content_type("application/json"))

This is the verbose output, I don´t know why I get back a 400 error.

-> POST /api/login HTTP/1.1
-> Host: localhost:5000
-> User-Agent: libcurl/7.64.1 r-curl/4.3 httr/1.4.1
-> Accept-Encoding: deflate, gzip
-> Accept: application/json, text/xml, application/xml, */*
-> Content-Length: 145
-> Content-Type: application/json; boundary=------------------------a4dc23f1d3e7221e
-> 
>> --------------------------a4dc23f1d3e7221e
>> Content-Disposition: attachment; name="secret"
>> 
>> bla
>> --------------------------a4dc23f1d3e7221e--

<- HTTP/1.0 400 BAD REQUEST
<- Content-Type: application/json
<- Content-Length: 91
<- Access-Control-Allow-Origin: *
<- Server: Werkzeug/1.0.0 Python/3.7.6
<- Date: Tue, 13 Oct 2020 15:14:54 GMT

What am I doing wrong?


Solution

  • Try to make sure the body is a json character vector instead of an r list.

    httr::POST("http://localhost:5000/api/login", body = jsonlite::toJSON(login), verbose(), content_type("application/json"))