Search code examples
rcurlpostrcurlhttr

Curl code to R with postFrom or POST


I've attempted to covert some curl code using both the postForm & POST methods in R following some other examples on here, however, i'm encountering 400 errors.

Here's the Curl i want to translate:

curl -X POST --header 'Content-Type: application/json;charset=UTF-8' --
header 'Accept: application/json' -d '[
  {

"campaignKwType":"DESTINATION_LANDMARK",
"featureId": 9849,
"guid": "xyz",
"language": "ENG",
"lob": "HOTEL",
"matchType": "EXACT",
"posa": "GBR",
"remarketingType": "NEW_CUSTOMERS",
"searchEngine": "GOOGLE",
"superRegionCampRef": true
 } ]' 'https://apiaddress'

With postForm:

   x <- postForm("https://apiaddress",
         .opts = list(postfields = toJSON(list(campaignKwType = "DESTINATION_LANDMARK", featureId = 9849,  guid = "xyz", language = "ENG", lob = "HOTEL", matchType = "EXACT", posa = "GBR", remarketingType = "NEW_CUSTOMERS", searchEngine = "GOOGLE", superRegionCampRef = TRUE)),
                      httpheader = c('Content-Type' = 'application/json;charset=UTF-8', Accept = 'application/json')))

With POST:

x <- POST("https://apiaddress",
               verbose(),
               encode = "json",
               body = list(c(campaignKwType = "DESTINATION_LANDMARK", featureId = 9849,  guid = "xyz", language = "ENG", lob = "HOTEL", matchType = "EXACT", posa = "GBR", remarketingType = "NEW_CUSTOMERS", searchEngine = "GOOGLE", superRegionCampRef = TRUE))
               )

Would appreciate any pointers, i've used other questions as an example for both of these requests and i've also checked the curl itself works. Thanks!


Solution

  • I'm not sure why you have the c() in your list() in the POST version but i'd imagine that's not what you want. Just use

    x <- POST("https://apiaddress",
               verbose(),
               encode = "json",
               body = list(list(campaignKwType = "DESTINATION_LANDMARK", featureId = 9849,  guid = "xyz", language = "ENG", lob = "HOTEL", matchType = "EXACT", posa = "GBR", remarketingType = "NEW_CUSTOMERS", searchEngine = "GOOGLE", superRegionCampRef = TRUE))
               )