I have a curl code below that runs in a terminal and I want to convert it httr code in R.
curl -X POST "https://api.purpleair.com/v1/groups/zzz/members" -H "Content-Type: application/json" -H "X-API-Key: xxxxxxxxx" -d '{"sensor_index":"yyyyyy"}'
This R code doesn't quite work.
library(httr)
url <- "https://api.purpleair.com/v1/groups/zzz/members"
body <- list(sensor_index = "yyyyyy")
headers <- c("Content-Type" = "application/json",
"X-API-Key" = "xxxxxxxxx")
response <- POST(url, body = body, add_headers(.headers = headers))
It returns
"error" : "MissingIdentifierError",
"description" : "Missing sensor_id or sensor_index value."
I can't figure out how to turn -d '{"sensor_index":"yyyyyy"}'
into a body.
If you pass your body=
as a list, by default POST()
will use "multipart" encoding which more generally allows you to upload files and form data. But if you want POST
to turn the list into a JSON string for you, you need to set encode="json"
. When you use that value, it will also set the correct content-type for you so you don't need to explicitly set it in a header.