Is there a way to add optional parameter in API using R Plumber?

北城以北 提交于 2021-01-28 08:47:17

问题


I have this routing that I'm trying to make it work:

#* @get /outcomes-aggregate/<categoryId:int>/<classId>/<perspectiveID>/<sn>
#* @serializer unboxedJSON
function(res, req, categoryId, classId,sn=NULL){
  
  ## initialization
  query <- NULL
  data_to_send <- list()
  ...
}

This api is supposed to take the request with optional sn value. However, this is not working. The sn value may or may not exist and the query is ran based on this value. But when I run it, I keep getting this error:

call: http://localhost:3982/outcomes-aggregated/1/342342

0   "404 - Resource Not Found"

It only works if I also include the sn.

call: http://localhost:3982/outcomes-aggregated/1/342342/NULL

How can I make this parameter optional? Or will I have to create another function without this value?

Update

I updated the routing and the logic to attempt to correct for this issue.

#* @get /outcomes-aggregate/<categoryId:int>/<classId>/<sn>
#* @serializer unboxedJSON
function(res, req, categoryId, classId,sn=NULL){
  
  ## initialization
  query <- NULL
  data_to_send <- list()
  ...

   if(missing(sn) || pracma::strcmp(sn, "NULL")){
    query <- paste0("SELECT * FROM classes WHERE classID = '", classId, "'")
  } else{
    query <- paste0("SELECT * FROM classes WHERE classID = '", classId, "' and sn = '", sn , "'")
  }
  ...

}

This is working for now but I have to still add NULL in the url. I'd love to hear a better way to do this.


回答1:


Your path has three parameters and you are only providing 2. It works when you provided a third one but it is not mapped to sn. It is mapped to perspectiveID.

/outcomes-aggregate/categoryId:int//




回答2:


Base on @BrunoTremblay's response, I ended up converting function to use query instead of path. This worked fine.

The new function looks like this:

#* @get /outcomes-aggregate <-- remove the path
#* @serializer unboxedJSON
function(res, req, categoryId, classId,sn=NULL){
  
  ## initialization
  query <- NULL
  data_to_send <- list()
  ...
}


来源:https://stackoverflow.com/questions/63496535/is-there-a-way-to-add-optional-parameter-in-api-using-r-plumber

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