对于宁静的POST响应“最佳”实践 [英] 'Best' practice for restful POST response

查看:109
本文介绍了对于宁静的POST响应“最佳”实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以没有什么新在这里我只是想获得一些澄清,似乎无法找到任何其他职位。

So nothing new here I am just trying to get some clarification and cannot seem to find any in other posts.

我restulfully创建一个新的资源,说:

I am creating a new resource restulfully, say:

/books (POST)

与身体:

{
  title: 'The Lion, the Witch and the Wardrobe',
  author: 'C. S. Lewis'
}

我知道我应该返回一个201(创建)新资源的Location头:

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

我已经这样做了几个方面的原因:

I have done this for a couple reasons:


  1. 我已经写API像angularjs前端框架。在我的
    特殊情况下,我采用了棱角分明的资源和我经常只需要
    该资源的ID来找到它。如果我没有返回在id
    响应正文我需要解析出来的位置
    头。

  2. 在所有书籍的GET我通常会返回整个对象不只是
    的ID。在这个意义上我的客户code没有区分
    从哪里得到(Location头或身体)的ID。

现在我现在我真的在这里的灰色地带,但大多数人都在说,返回整个资源是坏的做法。但是,如果该服务器的改变/添加什么样的信息给该资源。这无疑增加了ID,也可以添加其他的东西像一个时间戳。在这种情况下,我不返回整个资源,是不是真的不如做一个POST,返回的ID,然后在客户端执行GET来获得新的资源。

Now I now 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.

我实在看不出任何优势,只返回I​​D后做一个GET请求,让你可以与你的初始后得到的数据。

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,海事组织任何正确的方法。

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.

这篇关于对于宁静的POST响应“最佳”实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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