Update a single property in a REST API

2020-02-26 15:02发布

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!

标签: api rest
2条回答
Explosion°爆炸
2楼-- · 2020-02-26 15:36

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.

查看更多
SAY GOODBYE
3楼-- · 2020-02-26 15:52

As you have mentioned which is :

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.

That is true, so for this kind of scenarios i will suggest the following approach :

The URI should be something like this :

POST /api/cars/C1234

Request Body: {"for_sale":false} As not all web servers (and forget about clients) support PATCH so people have been supporting both partial updates with POST:

This is again not perfect RESTful API design, but i have seen and followed this one as best practice.

查看更多
登录 后发表回答