web-services - REST 最佳实践 : Should you return an entity on POST and PUT calls?

标签 web-services rest crud principles

为了尊重 REST 原则的最佳实践,是否最好在 POST/PUT 时返回创建/更新的实体?还是返回带有 Location header 的空 HTTP 正文?

更准确地说,当一个资源通过 POST 创建时,我们应该返回:

  • Status 201 + Location header + (the created entity in the HTTP body)

OR

  • Status 201 + Location header + (empty body)


当资源被 PUT 更新时,我们应该返回:

  • Status 200 + (the updated entity in the HTTP body)

OR

  • Status 204 (empty body)

最佳答案

研究其他人的 API 以了解他们如何做到这一点可能会有所帮助。大多数有用的公共(public) API 都发布在网络上的某个地方。

例如,Overmind 项目发布了他们的 REST API here .通常,他们的方法是返回一个 JSON 字典,其中包含新的或修改的实体 ID 及其所有属性:

Operation                     HTTP Method   URL           Query string
--------------------------    -----------   ---           ------------
Create node for a specific 
provider                      POST          /api/nodes/   provider_id=PROVIDER_ID

HTTP Payload returned
---------------------
JSON dict with id of node created (generated on the server side) and all other 
attributes of the node

Twilio's API能够返回 XML 或 JSON。当出现问题时,Twilio 在 HTTP 响应正文中返回异常。在 XML 中,这些显示为 <RestException> <TwilioResponse> 中的元素

一般来说,我可以看到在 PUT 或 POST 上返回对象很有用,因为它将包含对对象属性所做的任何修改(例如默认值)。

关于web-services - REST 最佳实践 : Should you return an entity on POST and PUT calls?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20383007/

相关文章:

web-services - Delphi Web 服务如何工作? (在运行时添加方法??)

c# - 通过网络序列化对象

url - 如何在浏览器中指定 ReSTLet 响应的格式?

ruby-on-rails - Rails 单表继承。共享 Controller ,如何更新 (CRUD)

android - Android 中的 Sugar ORM : update a saved object in SQLite

php - 更新具有两个文件字段的表单

.net - 调用 .net webservice 时出现问题?

java - 如何使用 qaf Web 服务请求调用来管理具有多个请求的 cookie?

session - session 是否用于 REST 身份验证?

ios - 使用 swift 将用户 ID 永久保存为 iOS 应用程序的登录数据