Search code examples
rapipostrcurlhttr

R POST API request with httr returns bad requests


Would like to implement the following POST request with curl with the httr package in R

curl 'https://api.openfigi.com/v2/mapping' \
--request POST \
--header 'Content-Type: application/json' \
--data '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]'

Based on this Git issue I tried:

library(jsonlite)
library(rjson)
#> 
#> Attaching package: 'rjson'
#> The following objects are masked from 'package:jsonlite':
#> 
#>     fromJSON, toJSON
library(httr)

url = 'https://api.openfigi.com/v2/mapping'

body1 = list(
  idType = jsonlite::unbox('ID_WERTPAPIER'),
  idValue = jsonlite::unbox('851399'),
  exchCode = jsonlite::unbox('US')
)
r = httr::POST(url, body = body1, encode = 'json', verbose())

body2 = rjson::toJSON(list(
  idType = "ID_WERTPAPIER",
  idValue = "851399",
  exchCode = "US"
))

r = httr::POST(url, body = body2, encode = "form", verbose())

Created on 2019-08-26 by the reprex package (v0.3.0)

But both are bad requests.


Solution

  • The following seems to work if you just translate the curl. Is that sufficient?

    require(httr)
    
    headers = c(
      `Content-Type` = 'application/json'
    )
    
    data = '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]'
    
    r <- httr::POST(url = 'https://api.openfigi.com/v2/mapping', httr::add_headers(.headers=headers), body = data)
    print(r$status_code)