Search code examples
rcurlhttr

Translating CURL to R


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.


Solution

  • 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.