Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use PATCH or PUT in my REST API?

I want to design my rest endpoint with the appropriate method for the following scenario.

There is a group. Each group has a status. The group can be activated or inactivated by the admin.

Should I design my end point as

PUT /groups/api/v1/groups/{group id}/status/activate 

OR

PATCH /groups/api/v1/groups/{group id}  with request body like  {action:activate|deactivate} 
like image 721
java_geek Avatar asked Jun 16 '14 10:06

java_geek


People also ask

When should I use an API PATCH?

When a client needs to replace an existing Resource entirely, they can use PUT. When they're doing a partial update, they can use HTTP PATCH. For instance, when updating a single field of the Resource, sending the complete Resource representation can be cumbersome and uses a lot of unnecessary bandwidth.

Why PATCH is used in REST API?

This capability allows a new HTTP method when exposing REST APIs, adding to the already available GET, POST, PUT, and DELETE methods. By definition, the PATCH method applies partial modifications to a resource, making it a lightweight option to PUT.

What is the difference between put and PATCH method in REST API?

PUT is a method of modifying resource where the client sends data that updates the entire resource . PATCH is a method of modifying resources where the client sends partial data that is to be updated without modifying the entire data.

Should I use put to update?

In a nutshell: use PUT if and only if you know both the URL where the resource will live, and the entirety of the contents of the resource. Otherwise, use POST.


1 Answers

The PATCH method is the correct choice here as you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety.

Further information on partial resource modification is available in RFC 5789. Specifically, the PUT method is described as follows:

Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

like image 153
Luke Peterson Avatar answered Sep 23 '22 18:09

Luke Peterson