将 PUT 用于 "mark as favorite" 操作在语义上是否不正确?
Is it semantically incorrect to use PUT for a "mark as favorite" operation?
在我的应用程序中,我有 2 种类型:user
和 file
。 file
可以由 user
变成 "marked as favorite",以便于访问。我目前使用 PUT
方法时 "favoriting" a file
像这样:
PUT /user/fileList/
Body: { fileId: 'xxxx' }
服务器随后会将给定的 fileId
添加到用户的记录中(授权单独处理)。
这种 PUT
的用法在语义上是错误的还是其他不好的做法?有没有更好的方法来实现这种模式?对我来说,这感觉像是一个次优的解决方案(至少在语义上)。
没有。例如,Github 在他们的 API 中为存储库加注星标。
https://developer.github.com/v3/activity/starring/#star-a-repository
这里 PUT 和 POST 之间的相关区别是,当客户端知道 URL 资源应该在哪里时,他们应该使用 PUT,例如/user/starred/:owner/:repo
,当客户不知道或不应该知道应该在哪里创建资源时,客户应该使用 POST,例如POST /users
应该 return 一个 link 到 /users/138
引用 RFC 2616,它定义了 HTTP 1.1:
The PUT method requests that the enclosed entity be stored under the supplied Request-URI... If the Request-URI does not point to an existing resource, and that URI is
capable of being defined as a new resource by the requesting user agent, the origin server can create the resource
with that URI.
The POST method is used to request that the origin server accept the entity enclosed in the request as a new
subordinate of the resource identified by the Request-URI in the Request-Line.
所以在你的具体情况下,我会把 fileId
放在 URL 的某个地方(例如 /user/fileList/:fileId
而不是在正文中,因为客户端知道资源应该放在哪里。
在我的应用程序中,我有 2 种类型:user
和 file
。 file
可以由 user
变成 "marked as favorite",以便于访问。我目前使用 PUT
方法时 "favoriting" a file
像这样:
PUT /user/fileList/
Body: { fileId: 'xxxx' }
服务器随后会将给定的 fileId
添加到用户的记录中(授权单独处理)。
这种 PUT
的用法在语义上是错误的还是其他不好的做法?有没有更好的方法来实现这种模式?对我来说,这感觉像是一个次优的解决方案(至少在语义上)。
没有。例如,Github 在他们的 API 中为存储库加注星标。
https://developer.github.com/v3/activity/starring/#star-a-repository
这里 PUT 和 POST 之间的相关区别是,当客户端知道 URL 资源应该在哪里时,他们应该使用 PUT,例如/user/starred/:owner/:repo
,当客户不知道或不应该知道应该在哪里创建资源时,客户应该使用 POST,例如POST /users
应该 return 一个 link 到 /users/138
引用 RFC 2616,它定义了 HTTP 1.1:
The PUT method requests that the enclosed entity be stored under the supplied Request-URI... If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.
所以在你的具体情况下,我会把 fileId
放在 URL 的某个地方(例如 /user/fileList/:fileId
而不是在正文中,因为客户端知道资源应该放在哪里。