我想知道人们对在响应体中不返回任何(null)的RESTful PUT操作有什么看法。
当前回答
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)
其他回答
HTTP响应的头和正文之间是有区别的。PUT永远不应该返回正文,但必须在报头中返回响应代码。如果成功就选择200,如果不成功就选择4xx。没有空返回码这样的东西。你为什么想做这个?
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)
如果REST API的后端是一个SQL关系数据库,那么
您应该在每个可以更新的记录中都有RowVersion(以避免丢失更新问题) 您应该总是在PUT之后返回记录的新副本(以获得新的RowVersion)。
如果您不关心丢失的更新,或者您希望强制客户端在PUT之后立即执行GET,那么不要从PUT返回任何东西。
“Created”的Http响应代码201以及指向客户端可以找到新创建资源的“Location”标头。
我认为服务器可以返回内容以响应PUT。如果您正在使用允许侧载数据的响应信封格式(例如ember-data所使用的格式),那么您还可以包括其他可能通过数据库触发器修改过的对象,等等(侧载数据显式地减少了请求的数量,这似乎是一个优化的好地方)。
如果我只是接受PUT,没有任何报告,我使用状态代码204,没有正文。如果我有什么要报告的,我会使用状态代码200,并包含一个主体。
推荐文章
- PATCH和PUT请求的主要区别是什么?
- 调用webrequest, POST参数
- 如何在Spring RestTemplate请求上设置“接受:”头?
- REST API最佳实践:查询字符串中的参数vs请求体中的参数
- Java中SOAP和rest式web服务的主要区别
- Android Scala编程
- 如何为Java创建REST客户端?
- Android 8.1升级后start前台失败
- file_get_contents(): SSL operation failed with code 1, failed to enable crypto
- 在HttpClient和WebClient之间进行选择
- 执行没有实体主体的HTTP POST被认为是不好的做法吗?
- JavaScript/jQuery下载文件通过POST与JSON数据
- 如何检查位置服务是否已启用?
- 基于Spring的RESTful认证
- 在Java中读取资源文本文件到字符串