REST最佳实践:您是否应该在POST和PUT调用中返回实体? [英] REST Best Practices: Should you return an entity on POST and PUT calls?

查看:119
本文介绍了REST最佳实践:您是否应该在POST和PUT调用中返回实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了遵守REST原则的最佳实践,是否最好在POST / PUT上返回创建/更新的实体?还是返回带有Location标头的空HTTP正文?

In order to respect the best practices of the REST principles, is it best to return the created/updated entity upon a POST/PUT ? Or return an empty HTTP body with the Location header?

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

More precisely, when a resource is created by a POST, should we return:



  • 状态201 +位置标头+(在HTTP正文中创建的实体)

OR


  • 状态201 +位置标头+(空主体)

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

When a resource is updated by a PUT, should we return:



  • 状态200 +(HTTP正文中的更新实体)


  • 状态204(空主体)


推荐答案

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

It might be beneficial to study the API's of other folks to see how they do it. Most of the useful public API's are published somewhere on the web.

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

For example, the Overmind project publishes their REST API here. In general, their approach is to return a JSON Dictionary containing the new or modified entity ID and all of its attributes:

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的API 能够返回XML或JSON。发生问题时,Twilio在HTTP响应主体中返回异常。在XML中,它们显示为< TwilioResponse>

Twilio's API is capable of returning XML or JSON. Twilio returns exceptions in the HTTP response body when something goes wrong. In XML, these appear as a <RestException> element within the <TwilioResponse>

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

In general, I can see returning the object on a PUT or POST as useful, because it will contain any modifications made to the properties of the object (such as default values).

这篇关于REST最佳实践:您是否应该在POST和PUT调用中返回实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆