如何在 RESTful POST 中返回生成的 ID? [英] How to return generated ID in RESTful POST?
问题描述
假设我们有一项添加新酒店的服务:
Let's say we have a service to add a new hotel:
> POST /hotel
> <hotel>
> <a>aaa</a>
> <b>aaa</b>
> <c>aaa.......this is 300K</c>
> </hotel>
然后我们得到了:
> GET /hotel
< HTTP/1.1 200 OK
< <hotel>
< <a>aaa</a>
< <b>aaa</b>
> <c>aaa.......this is 300K</c>
< </hotel>
问题是我们为初始 POST 创建返回什么?我们想返回 ID(在服务器上生成)以作为对新资源的引用",但我们不想返回所有酒店数据,因为在我们的例子中,其中一个数据字段是一个 ~300K 的平面文件.
Question is what do we return for the initial POST creation? We would like to return the ID (generated on the server) for a "reference" to the new resource but we don't want to return all the hotel data as in our case one of the data fields is a flat file of ~300K.
所以你应该返回:
< HTTP/1.1 200 OK
< <hotel>
< <id>123</id>
< </hotel>
或者你应该返回完整的对象:
Or should you return the full object:
< HTTP/1.1 200 OK
< <hotel>
< <id>123</id>
< <a>aaa</a>
< <b>aaa</b>
> <c>aaa.......this is 300K</c>
< </hotel>
??
我对宁静的最佳实践感兴趣.
I'm interested in the restful best practice.
注意:这个相关的帖子更多地讨论了返回什么但不太了解如何退货.
Note: this related post talks more about what to return but less about how to return it.
推荐答案
返回状态代码 201 - Created,并将 URL 放在 Location 标题中.您根本不需要返回正文.
Return the status code 201 - Created, and put the URL in the Location header. You don't need to return a body at all.
这篇关于如何在 RESTful POST 中返回生成的 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!