例如,您为用户/9运行一个GET请求,但没有id为#9的用户。 哪个是最佳响应码?

200好了 202年接受 204无内容 400错误请求 404未找到


当前回答

使用公共枚举对响应内容进行编码,以允许客户端打开它并相应地派生逻辑。我不知道你的客户如何区分“数据未找到”404和“网络资源未找到”404之间的区别?您不希望有人浏览到userZ/9,并让客户端怀疑请求是否有效,但没有返回数据。

其他回答

为了总结或简化,

2xx:可选数据:格式良好的URI: Criteria不是URI的一部分:如果Criteria是可选的,可以在@RequestBody和@RequestParam中指定,应该导致2xx。例如:按名称/状态过滤

标准是URI的一部分:如果标准是强制性的,只能在@PathVariable中指定,那么它应该导致4xx。例如:按唯一id查找。

对于所问的情况: "users/9"将是4xx(可能是404) 但是对于“用户”呢?Name =superman”应该是2xx(可能是204)

Just an addition from a developer that struggled many times with this situation. As you might have noticed it is always a discussion whether you return a 404 or 200 or 204 when a particular resource does not exist. The discussion above shows that this topic is pretty confusing and opinion based ( while there is a http-status-code standard existing ). I personally recommend, as it was not mentioned yet I guess, no matter how you decide DOCUMENT IT IN YOUR API-DEFINITION. Of course a client-side developer has in mind when he/she uses your particular "REST"- api to use his/her knowledge about Rest and expects that your api works this way. I guess you see the trap. Therefor I use a readme where I explicitly define in which cases I use which status code. This doesn't mean that I use some random definion. I always try to use the standard but to avoid such cases I document my usage. The client might think you are wrong in some specific cases but as it is documented, there is no need for additional discussions what saves time for you and the developer.

One sentence to the Ops question: 404 is a code that always comes in my mind when I think back about starting to develop backend-applications and I configured something wrong in my controller-route so that my Controller method is not called. With that in mind, I think if the request does reach your code in a Controller method, the client did a valid request and the request endpoint was found. So this is an indication not to use 404. If the db query returns not found, I return 200 but with an empty body.

这个话题中的答案(在撰写本文时已经有26个)完美地说明了开发人员理解他们正在使用的构造的语义是多么重要。

如果不理解这一点,那么响应状态代码是响应的属性而不是其他属性就不明显了。这些代码存在于响应的上下文中,它们在此上下文中之外的含义是未定义的。

响应本身就是请求的结果。请求对资源进行操作。资源、请求、响应和状态代码是HTTP的结构,就HTTP而言:

HTTP提供了与资源(第2节)交互的统一接口,无论其类型、性质或实现如何,通过操作和传输表示(第3节)。

换句话说,响应状态码的范围受到一个接口的限制,该接口只关心一些目标资源,并处理用于与这些资源交互的消息。服务器应用程序逻辑超出了范围,您使用的数据也不重要。

当使用HTTP时,它总是与资源一起使用。资源被以太转移或操纵。在任何情况下,除非我们在量子世界中,资源要么存在要么不存在,不存在第三种状态。

如果发出HTTP请求来获取(传输)资源的表示(如本问题中所示),而资源不存在,则响应结果应该显示一个带有相应404代码的失败。目标-获取表示-没有达到,资源没有找到。在HTTP上下文中不应该有对结果的其他解释。

RFC 7231超文本传输协议(HTTP/1.1):语义和内容,在这里多次提到,但主要是作为状态码描述的参考。我强烈建议通读整个文档,而不仅仅是第6节,以便更好地理解HTTP接口及其组件的作用域和语义。

在以前的项目中,我使用了404。如果没有用户9,则没有找到对象。因此404 Not Found是合适的。

如果对象存在,但没有数据,则为204 no Content。我认为在你的例子中,这个物体并不存在。

为什么不用410呢?它表示所请求的资源不再存在,客户端希望永远不会对该资源发出请求,在您的例子中是users/9。

你可以在这里找到更多关于410的详细信息:https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html