REST GET 的 HTTP 响应代码 - 未找到子资源(但未被标识符引用)
HTTP response code for REST GET - subresource not found (but not referenced by identifier)
我正在构建一个 REST API,并且在将响应代码返回到 GET 操作时遇到了一个难题。
我在网上找到了许多示例和答案,但不是针对我的特定情况。
这是我到目前为止发现和理解的内容:
如果返回一个空列表(比如 /library/authors/{authorId}/books),一个响应代码为 200 的空列表就足够了
如果请求具有 ID 的特定资源(比如 /library/authors/{authorId}/books/{bookId}),响应将是空着 404
这总结了我的大部分用例,我很满意。
但是,如果我访问一个没有id的子资源会怎样?
例如,为了论证,假设作者可以有很多书,但只有一本自传。他要么有,要么没有。我不希望用户传入自传 id,因为系统可以自行判断是否存在,端点是这样的:
GET /library/authors/{authorId}/auto-biography
如果作者存在但没有自传(为NULL),http响应码是否为:
- 204(空内容)
- 404(资源不存在)
提前致谢!
通过语义工作
GET /library/authors/1/auto-biography
/library/authors/1/auto-biography
是一个标识符。 resource 本身是一些概念,例如“作者 1 的自传”;请注意,我们可以谈论该资源,即使它实际上可能还不存在。
A resource can map to the empty set, which allows references to be made to a concept before any realization of that concept exists
出现在 HTTP 响应正文中的不是资源,而是资源的表示。
所以现在看看状态码
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
一个粗略的类比:假设您尝试获取文件的内容。 404
在语义上与 FileNotFound 一致; 204
表示文件长度为零字节。
404
通常会附有“对错误情况的解释,以及它是暂时的还是永久的情况”。它表示客户端尝试使用不应该可用的 link。
另一方面,204
什么也没有——表示是零字节长,怎么可能有数据。这是 200
响应的特例,通知客户端(和中间组件)响应正文有意留空。
我正在构建一个 REST API,并且在将响应代码返回到 GET 操作时遇到了一个难题。 我在网上找到了许多示例和答案,但不是针对我的特定情况。 这是我到目前为止发现和理解的内容:
如果返回一个空列表(比如 /library/authors/{authorId}/books),一个响应代码为 200 的空列表就足够了
如果请求具有 ID 的特定资源(比如 /library/authors/{authorId}/books/{bookId}),响应将是空着 404
这总结了我的大部分用例,我很满意。
但是,如果我访问一个没有id的子资源会怎样?
例如,为了论证,假设作者可以有很多书,但只有一本自传。他要么有,要么没有。我不希望用户传入自传 id,因为系统可以自行判断是否存在,端点是这样的:
GET /library/authors/{authorId}/auto-biography
如果作者存在但没有自传(为NULL),http响应码是否为:
- 204(空内容)
- 404(资源不存在)
提前致谢!
通过语义工作
GET /library/authors/1/auto-biography
/library/authors/1/auto-biography
是一个标识符。 resource 本身是一些概念,例如“作者 1 的自传”;请注意,我们可以谈论该资源,即使它实际上可能还不存在。
A resource can map to the empty set, which allows references to be made to a concept before any realization of that concept exists
出现在 HTTP 响应正文中的不是资源,而是资源的表示。
所以现在看看状态码
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
一个粗略的类比:假设您尝试获取文件的内容。 404
在语义上与 FileNotFound 一致; 204
表示文件长度为零字节。
404
通常会附有“对错误情况的解释,以及它是暂时的还是永久的情况”。它表示客户端尝试使用不应该可用的 link。
204
什么也没有——表示是零字节长,怎么可能有数据。这是 200
响应的特例,通知客户端(和中间组件)响应正文有意留空。