How to set a custom HTTP status code from inside OpenCPU R function

75 Views Asked by At

I have an R function on OpenCPU (provided from OpenCPU docker image: https://hub.docker.com/r/opencpu/rstudio/) which filters data by some criterias. If there is no data to return I want to send a message (No data) with 204 status code. How can I set status status code from inside the R function?

There is information in rApache documentation (http://rapache.net/manual.html). It is said there is a function setStatus() in rApache, but I couldn't set status code when calling this function. I tried to set 204 status code, but I get a default (for POST) 201 status code instead.

filterData <- function(filter_a = NULL, filter_b = NULL) {

  data <- as.data.frame(
    list("a" = c(1,2,3), "b" = c(3,2,1))
  )

  if (!is.null(filter_a)) {
    data <- subset(data, a == filter_a)
  }

  if (!is.null(filter_b)) {
    data <- subset(data, b == filter_b)
  }

  if (nrow(data) == 0) {
    setStatus(204L)
    return("No content")
  } else {
    return(data)
  }
}
1

There are 1 best solutions below

0
anselfinger On

The short answer: this is not possible.

The logic for setting the response status codes is encapsulated within openCPU. Status codes are managed within the res object. In case of POST requests openCPU will overwrite the status code in session_eval even if you would manage to set the status code in the internal object. OpenCPU would overwrite it with 201 Code after executing your custom code.