REST Best Practices: Should you return an entity on POST and PUT calls?

无人久伴 提交于 2019-12-04 15:59:55

问题


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?

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

  1. Status 201 + Location header + (the created entity in the HTTP body) ?
  2. or Status 201 + Location header + (empty body) ?

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

  1. Status 200 + (the updated entity in the HTTP body) ?
  2. or Status 204 (empty body) ?

回答1:


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.

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'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>

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).



来源:https://stackoverflow.com/questions/20383007/rest-best-practices-should-you-return-an-entity-on-post-and-put-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!