为了尊重 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/