我想知道人们对在响应体中不返回任何(null)的RESTful PUT操作有什么看法。


当前回答

“Created”的Http响应代码201以及指向客户端可以找到新创建资源的“Location”标头。

其他回答

空的Request体符合GET请求的原始目的,空的响应体也符合PUT请求的原始目的。

我认为服务器可以返回内容以响应PUT。如果您正在使用允许侧载数据的响应信封格式(例如ember-data所使用的格式),那么您还可以包括其他可能通过数据库触发器修改过的对象,等等(侧载数据显式地减少了请求的数量,这似乎是一个优化的好地方)。

如果我只是接受PUT,没有任何报告,我使用状态代码204,没有正文。如果我有什么要报告的,我会使用状态代码200,并包含一个主体。

HTTP/1.1规范(第9.6节)讨论了适当的响应/错误代码。但是,它不处理响应内容。

你想要什么?一个简单的HTTP响应代码(200等)对我来说似乎是直接而明确的。

我在我的服务中使用了RESTful API,以下是我的观点: 首先,我们必须了解一个通用视图:PUT用于更新资源,而不是创建或获取资源。

我用:无状态资源和有状态资源来定义资源:

无状态的资源 对于这些资源,只返回带有空主体的HttpCode就足够了。 有状态资源 例如:资源的版本。对于这类资源,当您想要更改它时,您必须提供版本,因此返回完整的资源或将版本返回给客户端,因此客户端在更新操作后不需要发送get请求。

但是,对于服务或系统来说,最重要的是保持简单、清晰、易于使用和维护。

HTTP规范(RFC 2616)有许多适用的建议。以下是我的解读:

HTTP status code 200 OK for a successful PUT of an update to an existing resource. No response body needed. (Per Section 9.6, 204 No Content is even more appropriate.) HTTP status code 201 Created for a successful PUT of a new resource, with the most specific URI for the new resource returned in the Location header field and any other relevant URIs and metadata of the resource echoed in the response body. (RFC 2616 Section 10.2.2) HTTP status code 409 Conflict for a PUT that is unsuccessful due to a 3rd-party modification, with a list of differences between the attempted update and the current resource in the response body. (RFC 2616 Section 10.4.10) HTTP status code 400 Bad Request for an unsuccessful PUT, with natural-language text (such as English) in the response body that explains why the PUT failed. (RFC 2616 Section 10.4)