问题描述
所以这里没有什么新鲜事,我只是想澄清一下,似乎在其他帖子中找不到任何内容.
So nothing new here I am just trying to get some clarification and cannot seem to find any in other posts.
我正在轻松地创建一个新资源,例如:
I am creating a new resource restulfully, say:
/books (POST)
有一个身体:
{
title: 'The Lion, the Witch and the Wardrobe',
author: 'C. S. Lewis'
}
我知道我应该返回一个带有新资源的 Location 标头的 201(已创建):
I know that I should return a 201 (Created) with a Location header of the new resource:
Location: /books/12345
我自己似乎无法回答的问题是服务器应该在正文中返回什么.
The question I cannot seem to answer for myself is what should the server return in the body.
我经常做这种类型的回复:
I have often done this type of response:
{
id: 12345,
title: 'The Lion, the Witch and the Wardrobe',
author: 'C. S. Lewis'
}
我这样做有几个原因:
- 我为 angularjs 等前端框架编写了 api.在我的特殊情况下我使用的是角度资源,我经常只需要用于定位它的资源的 id.如果我没有返回 id我需要从 Location 中解析它的响应正文标题.
- 在所有书籍的 GET 中,我通常返回整个对象,而不仅仅是身份证.从这个意义上说,我的客户端代码不必区分从何处获取 ID(位置标头或正文).
现在我知道我真的处于灰色地带,但大多数人都说返回整个资源是不好的"做法.但是如果服务器更改/向资源添加信息怎么办.它肯定会添加 id,但也可能会添加其他内容,例如时间戳.在我不返回整个资源的情况下,是否最好进行POST,返回id,然后让客户端执行GET以获取新资源.
Now I know I am really in the grey area here, but most people are saying that returning the entire resource is 'bad' practice. But what if the server changes/adds information to the resource. It definitely adds the id, but might also add other things like a timestamp. In the case that I do not return the entire resource, is it really better to do a POST, return the id, then have the client perform a GET to get the new resource.
推荐答案
在更新时返回整个对象似乎不太相关,但我很难理解为什么在创建时返回整个对象在一个正常的用例.这至少对于轻松获取 ID 并在相关时获取时间戳很有用.这实际上是使用 Rails 搭建脚手架时的默认行为.
Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant.This is actually the default behavior got when scaffolding with Rails.
我真的不认为只返回 ID 并在之后执行 GET 请求以获取您可以通过初始 POST 获得的数据有任何优势.
I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.
无论如何,只要您的 API 是一致的,我认为您应该选择最适合您需求的模式.没有任何关于如何构建 REST API 的正确方法,imo.
Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.
这篇关于RESTful POST 响应的“最佳"实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!