Default required = TRUE value for endpoint parameters in plumber R package

When defining API endpoints using {plumber} as, for instance, in the example of Quickstart vignette of plumber itself ref

#* Plot out data from the iris dataset
#* @param spec If provided, filter the data to only this species (e.g. 'setosa')
#* @get /plot
#* @serializer png
function(spec){
  myData <- iris
  title <- "All Species"

  # Filter if the species was specified
  if (!missing(spec)){
    title <- paste0("Only the '", spec, "' Species")
    myData <- subset(iris, Species == spec)
  }

  plot(myData$Sepal.Length, myData$Petal.Length,
       main=title, xlab="Sepal Length", ylab="Petal Length")
}

parameter spec becomes "required". It means you are forced to enter a value for it (as you can check in the swagger obtained by launching "Run API" in RStudio). Therefore, you cannot get the plot for the whole dataset when no value is passed for parameter spec.

There are ways to fix it, for instance by setting a default to NULL and changing the endpoint behavior if spec=NULL. Nevertheless, this is not the behavior expected according to the vignette mentioned above.

On the other hand, It looks like using progammatic API definition you can set required = FALSE for the parameter list.

Please, how can you change the default behavior of Plumber to use required = FALSE for spec parameter?

By default, if you do not provide a value in the function definition, the spec will output required = TRUE.

You can modify the spec on the fly if you not want that. You can also submit a PR or an issue if you think this behavior is odd.

#* @plumber 
function(pr) {
  pr$setApiSpec(function(apispec) {
    apispec$paths$`/plot`$get$parameters[[1]]$required <- FALSE
  })
}

#* Plot out data from the iris dataset
#* @param spec If provided, filter the data to only this species (e.g. 'setosa')
#* @get /plot
#* @serializer png
function(spec){
  myData <- iris
  title <- "All Species"
  
  # Filter if the species was specified
  if (!missing(spec)){
    title <- paste0("Only the '", spec, "' Species")
    myData <- subset(iris, Species == spec)
  }
  
  plot(myData$Sepal.Length, myData$Petal.Length,
       main=title, xlab="Sepal Length", ylab="Petal Length")
}

Thanks a lot for your answer.
Really clear.

Following your advise,
I will submit an issue as the example shown in plumber vignette Quickstart , does not work as expected (you cannot leave the spec parameter empty).

Technically, you can. It's just from the swagger interface. There won't be an issue if you call your API from curl or something else.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.