有没有办法使用 R Plumber 在 API 中添加可选参数? [英] Is there a way to add optional parameter in API using R Plumber?

查看:23
本文介绍了有没有办法使用 R Plumber 在 API 中添加可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个路由,我正在尝试使其工作:

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()
  ...
}

这个 api 应该接受带有可选 sn 值的请求.但是,这是行不通的.sn 值可能存在也可能不存在,并且基于该值运行查询.但是当我运行它时,我不断收到此错误:

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"

它只有在我还包含 sn 时才有效.

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?

更新

我更新了路由和逻辑以尝试更正此问题.

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 , "'")
  }
  ...

}

这暂时有效,但我仍然必须在 url 中添加 NULL.我很想听听一个更好的方法来做到这一点.

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.

推荐答案

根据@BrunoTremblay 的回复,我最终将函数转换为使用查询而不是路径.这工作得很好.

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

新函数如下所示:

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

这篇关于有没有办法使用 R Plumber 在 API 中添加可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆