【问题标题】:Create two or more APIs with same URL in play framework在 play framework 中创建两个或多个具有相同 URL 的 API
【发布时间】:2016-10-11 23:57:47
【问题描述】:

我有需要从查询字符串中读取值的用例。 目前我有两个不同的 API(其他人创建了代码)映射到相同的 URL

GET /service/class/:className/details controllers.Student.getStudentDetails(studentId)
GET /service/class/:className/details controllers.Student.getAllStudentsDetails()

如果 URL 中存在查询字符串,则应执行 API1,否则应执行 API2。

由于两个 API 的 URL 相同,我只能点击 get-student-details API(因为它在路由文件中具有更高的优先级)。 我正在寻找解决此问题的替代方法。

据我所知,我们不需要创建不同的 API 来处理查询字符串。 我正在考虑将 2 个不同的 API 合并到单个 API 中,这取决于请求中是否存在查询字符串。

我想知道是否有办法执行映射到相同 URL 的两个不同 API(唯一的区别是查询字符串)。

注意:我使用的是 play 2.4.6。

【问题讨论】:

    标签: scala api playframework playframework-2.0


    【解决方案1】:

    我发现使用单个控制器功能的方法很少(比如我们选择了getStudentDetails

    1) 有一个Option 参数:

      def getStudentDetails(studentId: Option[String]) = Action { studentId match {
          case Some(id) => // do something
          case None => // do something else
        }
        // ..
      }
    

    2) 在您的 http 请求中查找您的查询字符串参数:

      def getStudentDetails = Action { request =>
        request.queryString.get("studentId") match {
            case Some(list) => // do something...beware this is a List
            case None => // do something else
        }
        //...
      }
    

    【讨论】:

    • 是的,我正在考虑按照您的建议进行修复。
    • 但目前我们有两种不同的 API 用于这些情况,但 play 只允许使用一种 API。修复路由文件不能解决问题吗(Play 将允许同时命中两个 API)?
    • 哦,是的,您当然需要更改您的routes。我只是回答将这两个功能合并在一起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2020-03-27
    • 1970-01-01
    • 2018-10-04
    • 2011-10-12
    • 2022-01-12
    相关资源
    最近更新 更多