Jsonapi 资源不存在:404 或 { "data": null }?

Jsonapi resource is not present: 404 or { "data": null }?

如果客户端请求我的 REST 应用程序中不存在的资源,例如

http://localhost:8080/app/foo/1

并且该 ID 不存在 Foo 资源,我应该 return 一个 404 错误代码吗?或者我应该 return 200 和 body 的 {"data": null }

阅读 this thread from ember data 让我觉得我应该 return 404。

但是当我读到 this passage from the JSONAPI spec 它让我觉得我应该 return {"data " : null}:

Primary data MUST be either:

  • a single resource object, a single resource identifier object, or null, for requests that target single resources
  • an array of resource objects, an array of resource identifier objects, or an empty array ([]), for requests that target resource collections

因为这个案例似乎针对单个资源。

在解析数据部分中说:

A server MUST respond to a successful request to fetch an individual resource or resource collection with a 200 OK response.

"successful" 是什么意思?如果查询没有找到任何东西,因为那里没有条目,查询 运行 并得到准确的结果,是否成功?

同节以下为:

null is only an appropriate response when the requested URL is one that might correspond to a single resource, but doesn’t currently.

我不清楚这是什么意思。

那是哪一个,为什么?

(这并不是要专门针对 ember-data,我想澄清一下我应该怎么做才能符合规范。我只提到 ember-data 因为它看起来像jsonapi 应该如何工作的工作参考实现。)

你link的部分要讲一个'document'。如果没有文件,则那里所说的一切都不适用于答复。还有:

A JSON object MUST be at the root of every JSON API request and response containing data.

请注意其中的 'containing data' 部分。

Return 404 Not Found.

我知道我迟到了,但我的回答可能对任何迷失的灵魂都有用。

1.0 specification 特别提到:

[... ] A server MUST respond with 404 Not Found when processing a request to fetch a single resource that does not exist, except when the request warrants a 200 OK response with null as the primary data (as described above).

引用的段落可用 here, under "Fetching resources". Specifically, the last part of the quote regarding the usage of null touches on the topics of reachability

最终,所有 REST API 都应该是超媒体驱动的。这里的关键词是"exploration"。 JSON:API 允许通过 link 探索整个资源图(请参阅规范的相应 section)。如果在使用 404 Not Found{"data": null} 之间犹豫不决,请问问自己:您的 API 是否将任何 link 暴露给相关资源?

  • 如果是,这意味着请求在语义上是有效的,即使资源不存在或不包含任何数据,因此您应该以 {"data": null} 响应。例如,关系和相关资源通常可从根资源的 links 中获得,无论是否为空都无关紧要。

  • 如果不是,这意味着您的资源根本不存在,您应该回复 404 Not Found。这方面的一个例子可能是 /users/1234567890,其中没有 {"id": 1234567890} 的用户。在 /users 处获取 public 列表时,它不会出现,因此,您将永远无法通过以下超媒体驱动浏览到达 link。

总而言之,规范对此并不十分明确,但恕我直言,意图非常明确。请记住,您毕竟是在设计 REST API。