空表的正确 REST 响应? [英] Proper REST response for empty table?
问题描述
假设您想通过调用 GET
到 api/users
来获取用户列表,但目前该表已被截断,因此没有用户.这种情况下的正确响应是什么:404
或 204
?
Let's say you want to get list of users by calling GET
to api/users
, but currently the table was truncated so there are no users. What is the proper response for this scenario: 404
or 204
?
推荐答案
我想说,两者都不是.
404 状态代码应保留用于未找到资源的情况.在这种情况下,您的资源是用户集合.此集合存在,但当前为空.就我个人而言,如果我一天收到 200
第二天收到 404
只是因为有人碰巧删除了几个用户.我应该做些什么?我的网址有错吗?是否有人更改了 API 而忽略了重定向.
The 404 status code should be reserved for situations, in which a resource is not found. In this case, your resource is a collection of users. This collection exists but it's currently empty. Personally, I'd be very confused as an author of a client for your application if I got a 200
one day and a 404
the next day just because someone happened to remove a couple of users. What am I supposed to do? Is my URL wrong? Did someone change the API and neglect to leave a redirection.
服务器已完成请求但不需要返回实体正文,并且可能想要返回更新的元信息.
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.
虽然在这种情况下这似乎是合理的,但我认为这也会让客户感到困惑.204
应该表示某些操作已成功执行,不需要返回数据.这非常适合作为对 DELETE
请求的响应,或者可能触发一些不需要返回数据的脚本.在 api/users
的情况下,您通常希望收到您的用户集合的表示.一次发送响应正文而另一次不发送是不一致的,并且可能会产生误导.
While this may seem reasonable in this case, I think it would also confuse clients. A 204
is supposed to indicate that some operation was executed successfully and no data needs to be returned. This is perfect as a response to a DELETE
request or perhaps firing some script that does not need to return data. In case of api/users
, you usually expect to receive a representation of your collection of users. Sending a response body one time and not sending it the other time is inconsistent and potentially misleading.
出于上述原因(一致性),我将返回一个空集合的表示.假设您使用的是 XML.非空用户集合的正常响应正文可能如下所示:
For reasons mentioned above (consistency), I would return a representation of an empty collection. Let's assume you're using XML. A normal response body for a non-empty collection of users could look like this:
<users>
<user>
<id>1</id>
<name>Tom</name>
</user>
<user>
<id>2</id>
<name>IMB</name>
</user>
</users>
如果列表是空的,你可以用这样的东西来回应(同时仍然使用 200
):
and if the list is empty, you could just respond with something like this (while still using a 200
):
<users/>
无论哪种方式,客户端都会收到遵循某种众所周知的格式的响应正文.没有不必要的混淆和状态代码检查.此外,没有违反任何状态代码定义.大家都很开心.
Either way, a client receives a response body that follows a certain, well-known format. There's no unnecessary confusion and status code checking. Also, no status code definition is violated. Everybody's happy.
您可以对 JSON 或 HTML 或您使用的任何格式执行相同操作.
You can do the same with JSON or HTML or whatever format you're using.
这篇关于空表的正确 REST 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!