2

我正在设计一个用于将记录插入“解决方案”表的 REST API。一个“解决方案”有一个solverID,problemID。我有两种不同的设计:

POST /solutions

并在 JSON 中将solverID 和problemID 与解决方案的内容一起传递。或者将solverID和problemID放在URI中:

POST /users/:solver_id/problems/:problem_id/solutions 

哪个设计更好?

4

3 回答 3

1

和第一个一起去。我会尽可能保持您的网址简洁明了。这里有一些其他的例子。不确定你的整个结构。

POST /solutions

GET /solutions?solverid=123  //query solutions by user

GET /users/555/problems      // problems for a given user
GET /users/555/solutions     // solutions for a given user

GET /problems/987/solutions  // solutions for a given problem
于 2013-03-14T23:42:08.507 回答
1

在一致的层次结构中定义资源是一种很好的做法,以便它们易于理解和预测。

假设这是检索问题的 URL -

GET     /users/{solverId}/problems/{problemId}

它清楚地表明问题属于 {solverId}。

以下 URL 将清楚地表明我们正在检索 {solverId} 解决的问题的所有解决方案

GET     /users/{solverId}/problems/{problemId}/solutions

要为 {problemId} 创建一个新的解决方案,您可以在

POST     /users/{solverId}/problems/{problemId}/solutions

要检索特定的解决方案,您将继续

GET     /users/{solverId}/problems/{problemId}/solutions/{solutionId}

何时在路径与查询中使用 ID?

如果肯定需要 ID 来标识资源,请在路径中使用它。在上述场景中,由于需要所有三个 Id 来唯一标识一个解决方案,所以它们都应该在路径中。

假设您要检索在特定日期范围内给出的解决方案,您将使用以下内容

GET     /users/{solverId}/problems/{problemId}/solutions?startDate={}&endDate={}

这里 startDate 和 endDate 不能唯一标识资源,它们只是用于过滤结果的参数。

于 2013-03-18T17:17:43.363 回答
0

我想出了一个方案:只有在路由不需要认证的情况下才在路由中包含用户ID,否则可以从认证信息中找出用户ID,上面的路由就变成了:

POST /problems/:problem_id/solutions
于 2013-03-18T16:51:03.193 回答