Rest api - update single field of resource

25,007

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
Share:
25,007
user1321466
Author by

user1321466

Updated on July 09, 2022

Comments

  • user1321466
    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
    Eugene over 6 years
    agreed! lots of people think GET and POST only... plus one
  • Kamil Latosinski
    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 to myapi/drivers/{id}. Does it make sense?
  • Sync
    Sync over 5 years
    There 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 a 406. 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
    user1354825 over 3 years
    Not good design. RFC mentions patch should contain a request body.