Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest api - update single field of resource

Lets say I have rest endpoint for my Driver resource. I have PUT method like this

myapi/drivers/{id}  {body of put method} 

I need to add functionality which will allow to 'enable' and 'disable' driver

Is it good idea to create new endpoint for that like this?

PUT myapi/drivers/{id}/enable/false 

or it is better to use existing endpoint ? One problem with using existing endpoint is that driver has lot's of fields(almost 30) and sending all those fields just for updating only 'enabled' or 'disable' driver is something overkill.

What do you think?

like image 550
user1321466 Avatar asked Dec 21 '17 09:12

user1321466


People also ask

How do you update a field in REST API?

It is used in cases where the resource has many fields but you only want to update a few. Just like with PUT , you send a request to myapi/drivers/{id} . However, unlike with PUT , you only send the fields you want to change in the request body.

Does PUT method applies a partial update to an existing resource?

PUT. The HTTP PATCH method should be used whenever you would like to change or update just a small part of the state of the resource. You should use the PUT method only when you would like to replace the resource in its entirety.

Which REST method will you use to update a current resource?

When building RESTful APIs over HTTP the PUT method is typically used for updating, while POST is used for creating resources.


1 Answers

This is exactly what the HTTP method PATCH is made for. It is used in cases where the resource has many fields but you only want to update a few.

Just like with PUT, you send a request to myapi/drivers/{id}. However, unlike with PUT, you only send the fields you want to change in the request body.

Creating endpoints like myapi/drivers/{id}/enable is not very RESTful, as "enable" can't really be called a resource on its own.

For an example implementation of a Spring PATCH endpoint, please see this link.

like image 145
Sync Avatar answered Oct 06 '22 21:10

Sync