0

I have this curl command that I can call in bash

curl -X POST -H 'Content-Type: text/csv' --data-binary @data/data.csv https://some.url.com/invocations > data/churn_scored.jsonl

which posts a CSV file to the API endpoint and I redirect the results into a .jsonl file.

I can't find where I can specify a data file to POST to the endpoint like using curl's @.

What's the way to achieve the CURL post using R's curl package (or any other package)? The redirection of output I can figure out in another way.

xiaodai
  • 14,889
  • 18
  • 76
  • 140

2 Answers2

3

This is a very helpful site in converting curl commands to other languages: https://curl.trillworks.com/#r

When plugging in your curl command there I got this.

require(httr)

headers = c(
  `Content-Type` = 'text/csv'
)

data = upload_file('data/data.csv')
res <- httr::POST(url = 'https://some.url.com/invocations', httr::add_headers(.headers=headers), body = data)
casonadams
  • 956
  • 7
  • 7
1

To specific symbol @. From man curl:

--data-binary <data>
  (HTTP) This posts data exactly as specified with no extra processing whatsoever.
  If you start the data with the letter @, the rest should be a filename.  Data is
  posted in a similar manner as --data-ascii does, except that newlines are preserved
  and conversions are never done.

  If this option is used several times, the ones following the first will append data
  as described in -d, --data.

It seems no need to worry about @

As it mentioned by @chinsoon12, httr is a good nice method to handle request:

  • -X or --request translates to VERB function POST(), which includes --data-binary
  • -H or --header translates to add_headers() but there are special functions for setting content type (see below)

So it looks like:

library(httr)
response <- POST(
      url = "https://some.url.com/invocations",
      body = upload_file(
        path =  path.expand("data/data.csv"),
        type = 'text/csv'),
      verbose()
    )
# get response and write to you disk
Diya Li
  • 1,048
  • 9
  • 21