Array in body for httr POST request

混江龙づ霸主 提交于 2019-12-02 07:38:48

问题


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.



来源:https://stackoverflow.com/questions/25609041/array-in-body-for-httr-post-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!