REST 中 GET 和 DELETE 方法的响应应该是什么?

What should be the response of GET and DELETE methods in REST?

在 REST 中,假设客户端调用了 findAll 方法 (GET)- 它将简单地 return 实体列表 (DTO) 发送给客户端,HTTP 状态代码为 200。现在,假设客户端调用了DELETE 方法 removeObject(Object object)。参数中的对象在数据库中不存在,通常它会 return HTTP 状态代码 400。我希望客户端以更易于管理的方式(减少恐慌)知道 400 的真正原因。现在需要状态代码/描述,这在 GET 方法期间不是必需的。

我希望客户端对所有消息获得一致的响应。在基于 REST 的 API 中 return 有什么指南/最佳实践吗?

400 的状态代码很好,但您还 return 一些前端可以解析和理解的对象(即 json)。这样,您的前端会获得有关错误的更多信息,并可选择在将错误呈现给用户之前覆盖它。一些非常基本且几乎没有功能的伪代码:

后端:

return(status_code=400,
       body={message: {type: "error", description: "some text here"})

前端:

if (status_code >= 400):
    console.log(json.loads(response).message.description)

我希望 Rest api 在删除对象时以 200 响应。其他情况通常意味着我的请求出了问题。

如果我在对象被删除后请求它,我会期望 API 到 return 404,或者类似的东西。

请参考RFC 2616第9.7节

https://www.rfc-editor.org/rfc/rfc2616#section-9.7

REST 是什么意思?假设,我们参考 Roy Fielding and Http 1.1 标准。

根据标准,DELETE 是幂等方法。 IE。如果您多次请求 DELETE,副作用将是相同的。 IE。数据库中的所有相同记录将被标记为“已删除”或不存在。

首先,要请求 DELETE,您需要请求一个资源。说,http://some.url/to/resource。如果它从未出现 - 你应该用 404 响应。

标准的“9.7 删除”部分说:

A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

如果您没有从数据库中完全删除一条记录,并希望在后续请求中告知该资源已被删除且不再可用,那么标准的“10.4.11 410 Gone”部分说:

The 410 response is primarily intended to assist the task of web maintenance by notifying the recipient that the resource is intentionally unavailable and that the server owners desire that remote links to that resource be removed.

但是没有必要使用这个响应代码或提供一段时间,响应也可以是404。所以如果你想区分资源是否已被删除或从未存在过,请使用它。