设计 restful API 路径 - 用于返回过滤后的资源和返回资源的修剪属性

Designing restful APIs path - for returning filtered resource and for returning trimmed properties of a resource

我不是在问 What is the difference between @PathParam and @QueryParam

中已经问过的问题

此问题与 "best practices" 周围 restful 约定有关。

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

 [  
       {  
          "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"
       }, 
       {
        ...
       },
       ...
    ]

我使用路径参数“/questions”

从我的 spring 应用程序向 return 所有问题公开了一个休息控制器

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

  1. return只有所有题目的标题。
  2. return所有技术问题只有标题。
  3. return 算法题。

我认为没有这样做的标准约定。有没有?但是,我想听听人们如何像上面那样为 use-cases 设计他们的 REST API。我也很想听听这种做法背后的原因。

在此表示感谢。

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

我认为这两个是过滤器:

  • return .. 所有技术问题
  • return 算法题。

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

这可能是这样的:

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

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

对于 return 只有问题的标题,人们可以争辩说这可以是一个单独的 title-resouces。

例如:

  • /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