2

Mostly for my own understanding, how would you translate the following toy CURL example to R, using RCurl or httr:

  curl -v -X POST \
    https://someurl/endpoint \
-H "Content-Type: application/json" \
-H 'X-Api-Key: abc123' \
-d '{"parameters": [ 1, "foo", "bar" ]}'

I'm finding both packages a bit awkward for anything beyond simple GET requests.

I've tried:

library(httr)
 POST("https://someurl/endpoint", authenticate("user", "passwrd"), 
body = '{"parameters": [ 1, "foo", "bar" ]}', content_type_json())

Get a 400 status. My Curl version works perfectly.

Also tried:

POST("https://someurl/endpoint", add_headers('X-Api-Key: abc123'), 
body = '{"parameters": [ 1, "foo", "bar" ]}', content_type_json())

Also get 400 status.

I'm pretty sure the issue is with setting the headers.

Ben Rollert
  • 1,564
  • 1
  • 13
  • 21

3 Answers3

3

In this web page you can convert curl to many languajes: https://curl.trillworks.com/#r

In this case, in R is:

require(httr)

headers = c(
  'Content-Type' = 'application/json',
  'X-Api-Key' = 'abc123'
)

data = '{"parameters": [ 1, "foo", "bar" ]}'

res <- httr::POST(url = 'https://someurl/endpoint', httr::add_headers(.headers=headers), body = data)
MauriRamone
  • 469
  • 1
  • 3
  • 21
2

You can use httpbin.org for testing. Try:

curl -v -X POST \
    https://httpbin.org/post \
-H "Content-Type: application/json" \
-H 'X-Api-Key: abc123' \
-d '{"parameters": [ 1, "foo", "bar" ]}'

and save the result, then see how it compares with:

library(httr)

result <- POST("http://httpbin.org/post",
               verbose(),
               encode="json",
               add_headers(`X-Api-Key`="abc123"),
               body=list(parameters=c(1, "foo", "bar")))

content(result)

It's a pretty straightforward mapping.

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
0

The key is to escape the header names, in case anyone is curious. The direct translation is as follows:

POST("http://httpbin.org/post",
add_headers(`X-Api-Key`="abc123", `Content-Type` = "application/json"),
body='{"parameters": [ 1, "foo", "bar" ]}')
Ben Rollert
  • 1,564
  • 1
  • 13
  • 21