Array in body for httr POST request

2019-03-06 03:16发布

问题:

This curl call works to create a new droplet on Digital Ocean

curl -X POST "https://api.digitalocean.com/v2/droplets" \
   -d '{"name":"test3","region":"nyc2","size":"512mb","image":5562742,"ssh_keys":[89103]}' \
   -H "Authorization: Bearer $TOKEN" 
   -H "Content-Type: application/json"

However, I'm having trouble getting an httr::POST() request to work only when the parameter ssh_keys is given. In the above method the ssh_keys parameter, if given, has to be an array.

I assumed the list of parameters could be passed to the body as, e.g., where the ssh_keys parameter is inside a list

args <- list(name="test3", region="nyc2", size="512mb", image="5562742", ssh_keys=list(891111))
POST(url, config=auth, body=args)

I assume this is what's happening on the inside:

jsonlite::toJSON(args)

[1] "{ \"name\" : [ \"test3\" ], \"region\" : [ \"nyc2\" ], \"size\" : [ \"512mb\" ], \"image\" : [ \"5562742\" ], \"ssh_keys\" : [ [ 89103 ] ] }"

Which I imagine would work, but perhaps that's not what's happening? Fiddling with the encode parameter in POST doesn't seem to help.

The curl call works from terminal, but using httr::POST() I keep getting the error message

You specified invalid ssh key ids for Droplet creation.

回答1:

Maybe something like:

req <- POST(
    url = "https://api.digitalocean.com/v2/droplets",
    body = toJSON(args, auto_unbox=TRUE),
    add_headers (
        "Content-Type" = "application/json",
        "Authorization" = paste("Bearker", TOKEN)
    )
)


回答2:

In this specific case,

x <- jsonlite::toJSON(args, auto_unbox=TRUE)
cat(x)

seems to return the correct format (assuming the problem is not with the headers) so them

POST(url, config=auth, body=x)

should send the correct request.



标签: r httr jsonlite