首页 > 解决方案 > 设计 restful API 路径 - 用于返回过滤的资源和返回资源的修剪属性

问题描述

我不是在问@PathParam 和@QueryParam 之间有什么区别中已经提出的问题

这个问题与围绕宁静约定的“最佳实践”有关。

我有一个包含以下字段的问题资源。

 [  
       {  
          "questionId":6,
          "area":"TECHNICAL",
          "title":"Find the index of first 1 in an infinite sorted array of 0s and 1s",
          "description":"Given an infinite sorted array consisting 0s and 1s. The problem is to find the index of first 1 in that array. As the array is infinite, therefore it is guaranteed that number 1 will be present in the array.",
          "state":"ACTIVE",
          "difficultyLevel":"EASY",
          "skills":[  
             {  
                "skillId":1,
                "skillName":"ALGORITHM"
             },
             {  
                "skillId":2,
                "skillName":"PROGRAMMING"
             }
          ],
          "proposedBy":"agrawalo",
          "noOfTimesUsed":0,
          "examples":null,
          "probes":null,
          "approvedBy":null,
          "addedBy":null,
          "dateCreated":"2018-05-16T19:29:11.113",
          "dateLastUpdated":"2018-05-16T19:29:11.113"
       }, 
       {
        ...
       },
       ...
    ]

我从我的 spring 应用程序中暴露了一个休息控制器,以使用 pathparam "/questions" 返回所有问题

现在我想为以下情况设计 Rest URL(基本上是返回过滤后的问题集的 URL 和返回问题对象的一部分的 URL)。例如:

  1. 只返回所有问题的标题。
  2. 只返回所有技术问题的标题。
  3. 以算法的技巧返回问题。

我不认为有这样做的标准惯例。在那儿?但是,我想听听人们如何为上述用例设计 REST API。我也很想听听这种做法背后的原因。

这里的线索表示赞赏。

标签: javarestjax-rsspring-restcontroller

解决方案


正如您所提到的,没有标准的方法可以做到这一点。

我认为这两个是过滤器:

  • 返回..所有技术问题
  • 以算法的技巧返回问题。

在 REST 中,过滤器通常使用查询参数来实现。(路径参数用于标识资源。过滤器不是资源,因此它通常不是路径的一部分)

这可能看起来像这样:

  • /questions?area=technical
  • /questions?skill=algorithm

如果您需要更高级的过滤器,您可以查看 RSQL(例如:https ://github.com/jirutka/rsql-parser )

要只返回问题的标题,人们可能会争辩说这可以是一个单独的标题资源。

例如:

  • /question-titles
  • /question-titles?area=technial

如果您使用自定义媒体类型,您还可以为此资源定义简化的媒体类型并通过Accept-Header 请求此类型:例如

GET /questions?area=technial Accept: application/vnd.yourapp.question.short+json

或者您可以使用附加查询参数为调用者提供更多控制权:例如:

  • /questions?fields=title
  • /questions?output=reduced

推荐阅读