Boognish827
Boognish827

Reputation: 83

R - curl (not httr) POST request w/ JSON body

Let me start by saying that I understand how to do a POST request using "httr" and "crul" packages. I am working on developing an asynchronous method to sending multiple POST request with unique JSON body requests using the basic "curl" package. I have legitimate reasons for trying this with this package, but more importantly I'm just determined to get it to work. This may not be possible, or I may even be trying to wrong functions in "curl"...but wanted to see if anyone had any ideas.

I am trying to send a post request using curl_fetch_multi() as a POST request with a JSON in the body like this...

{
  "configuration": {
    "Id": 4507
  },
  "age": 0,
  "zip": 32411,
  "Date": "2020-12-23"
}

I have succeeded in at least getting getting error messages back form the API indicating an invalid body input using something along the lines of starting with an object containing each body i need to submit

   library(curl)
   library(jsonlite)
   library(magrittr)
   

   pool <- new_pool()

   # results only available through call back function
   cb <- function(req){cat("done:", req$url, ": HTTP:", req$status, "\n", "content:", rawToChar(req$content), "\n")}
   
   # Create request for each body
   for(i in 1:nrow(df)){
     
       curl_fetch_multi(
         "http://api.com/values?api_key=1234",
         done = cb,
         pool = pool,
         handle = new_handle() %>%
           handle_setopt(post = TRUE) %>%
           handle_setheaders("Content-Type"="application/vnd.v1+json") %>%
           handle_setform(body = df$body[[i]])   ###df$body[[i]] is a JSON string
       )
   }
   
   
   # This actually performs requests
   out <- multi_run(pool = pool)

done: http://api.com/values?api_key=1234 : HTTP: 400 
 content: {"errors":[{"code":"Service.input.invalid","message":"Invalid input"}]} 
done: http://api.com/values?api_key=1234 : HTTP: 400 
 content: {"errors":[{"code":"Service.input.invalid","message":"Invalid input"}]} 
....

I'm 90% positive it has to do with how it's attempting to call the JSON in handle_setform() setting of the handle. This is about where I am over my head and documentation is scarce.

Also, I am pretty sure the JSON is structured properly, as I can use them in other packages with no problem.

Any assistance would be greatly appreciated.

Upvotes: 3

Views: 1019

Answers (1)

Boognish827
Boognish827

Reputation: 83

Found the solution!!

Needed to use following settings with handle_setopts()

for(i in 1:nrow(df)){
 
   curl_fetch_multi(
     "http://api.com/values?api_key=1234",
     done = cb,
     pool = pool,
     handle = new_handle() %>%
           handle_setheaders("Content-Type"="application/v1+json") %>%
           handle_setopt(customrequest = "POST") %>%
           handle_setopt(postfields = df$body[[i]])  #df$body is list of JSON 
   )


}

out <- multi_run(pool = pool)

Upvotes: 3

Related Questions