在REST API中更新单个属性 [英] Update a single property in a REST API

查看:176
本文介绍了在REST API中更新单个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设计新的API时,我们将尽最大努力遵循REST建立的模式.我遇到的问题是尝试更新单个属性时要遵循的最佳方法.例如:

想象一下,您有一个简单的Car资源:

{
   "make": "Chevrolet",
   "model": "Chevelle",
   "year": 1966,
   "color": "black",
   "for_sale": true
}

让我们假设属性for_sale是您预期将由用户定期更新的内容.我有几个选择:

  1. PUTfor_sale设置为false的整个资源.对于一个相对较小的资源,这似乎很好,但是,在大多数情况下,我们的资源非常大,因此在发送整个资源以更新单个经常更改的属性时会浪费很多.

  2. POST并通过仅包含要更新的元素来进行部分更新,例如: {"for_sale":false}这样更好,因为它需要更少的开销.

但是我似乎以某种方式寻求更简单的方法,但是我似乎没有找到正确的方法.向URL提供一个简单的PUT(不需要任何请求主体)来更新此属性将非常方便.我看到了Google在其API中为实现此目的正在做的事情,但是尽管我很喜欢简单性,但感觉有点像RPC.

POST /blogs/blogId/posts/postId/comments/commentId/approve (将评论标记为不是垃圾邮件)

POST /blogs/blogId/posts/postId/comments/commentId/spam(将评论标记为垃圾邮件)

有人可以就遵循REST原则(最好是轻量级的方式)更新资源中单个属性的最佳方法提供一些建议吗?谢谢!

解决方案

实际上,我认为PATCH方法是专门为此目的而设计的.您应该使用它为对象提供部分更新,而不是完全更新. 此处是博客条目,对此进行了详细说明.

In designing a new API, we are doing our best to follow the patterns established by REST. The question I have is the best method to follow when trying to update a single property. For example:

Imagine you have a simple Car resource:

{
   "make": "Chevrolet",
   "model": "Chevelle",
   "year": 1966,
   "color": "black",
   "for_sale": true
}

Let's assume that the property for_sale is something that you anticipate will be updated regularly by the user. I have a couple options:

  1. PUT the entire resource with for_sale set to false. For a reasonably small resource, this seems fine, however, in most cases our resources are quite large so a lot of waste in sending the entire resource to update a single, often changed property.

  2. POST and do a partial update by only including the element to update, such as: {"for_sale":false} This is better as it requires a lot less overhead.

But I somehow seem to be reaching for something even more simple, but I don't seem to find the right approach. It would be quite convenient to offer a simple PUT to a URL (that doesn't require any request body) to update this property. I see what Google is doing in their API to accomplish this, but it feels just a bit RPC-ish, although I like the simplicity.

POST /blogs/blogId/posts/postId/comments/commentId/approve (marks a comment as not spam)

POST /blogs/blogId/posts/postId/comments/commentId/spam (marks a comment as spam)

Can someone offer some some advice on the best way to approach updating a single property within a resource (in a preferably lightweight manner) that followed REST principles? Thank you!

解决方案

Actually, I think that the PATCH method is designed specifically for this purpose. You should use it to provide a partial update to the object, rather than a full update. Here is a blog entry that explains this in more detail.

这篇关于在REST API中更新单个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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