3

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.

sckott
  • 5,755
  • 2
  • 26
  • 42

2 Answers2

3

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
2

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)
    )
)
Jeroen Ooms
  • 31,998
  • 35
  • 134
  • 207
  • 1
    Thanks for this, this is almost there, but I still need `ssh_keys` boxed in an array, so I had to `unbox()` all other params, but leave `ssh_keys` boxed. In addition, had to set `encode='json'` in the `POST()` call – sckott Sep 01 '14 at 17:13
  • I also had to add `encode='json'`. Otherwise I got an error: `Error in named(list(...)) : argument is missing, with no default` – Rustam Guliev Jun 01 '22 at 12:10