Search code examples
rhttr

Body in API call from httr package


I would like to call my Philips Hue lights from R via the API and httr package. The problem is however that I can't get the body right. I'm sure the API works because GET calls work fine.

For example, the body in a PUT call to turn the lights on and off should look exactly like {"on":false}. The call looks like PUT(url = url), body = body1)

However, I cannot get this to work in the body section from the httr package. I already tried: body1 <- '{on:"false"}' Which returns: "{on:\"false\"}", body2 <- list(on = "false") returns $on [1] "false" and body3 <- toJSON(body2) returns {"on":["false"]}.

As you can see none of the above options exactly desired return and they all produce extra punctuation marks. Any idea how I can get exactly {"on":false} in the body?

Unfortunately, I cannot provide you with a reproducible example because there is no public sandbox environment available and I don't want everyone to control my lights ;-) However the documentation can be found here.


Solution

  • If you are using toJSON from the jsonlite package, then you can do

    library(jsonlite)
    PUT("https://url", body=toJSON(list(on = unbox(FALSE))))
    

    The unbox() will prevent the R vector from being wrapped in the brackets for a JSON array.