Rest api - update single field of resource
Solution 1
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.
Solution 2
Use PATCH Http metod to update one field
PATCH myapi/drivers/{id}/enable
user1321466
Updated on July 09, 2022Comments
-
user1321466 almost 2 years
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?
-
Eugene over 6 yearsagreed! lots of people think
GET
andPOST
only... plus one -
Kamil Latosinski over 5 years@Synch what do you think about
myapi/drivers/{id}/is_enabled
and PATCH is_enabled? I would like to communicate to my API users that PATCH is only designed to "toggle" some status in the context of drivers resource. If they want to update any other fields just PUT tomyapi/drivers/{id}
. Does it make sense? -
Sync over 5 yearsThere are two things you can do. You can create a PATCH endpoint and limit it to only
status
. If the client tries to update anything else, you throw a406
. In the documentation, you'd need to explain the endpoint is only suitable for one attribute. The other approach is to create a "sub-resource"myapi/drivers/{id}/status
. See link for a much more detailed answer. -
user1354825 over 3 yearsNot good design. RFC mentions patch should contain a request body.