We’re currently implementing a REST API based on JSON for our Debitoor application. We’re using the following HTTP methods:
POST: Creates a new resource
PUT: Updates an existing resource, with the entire resource being overwritten by the PUT content
DELETE: Deletes a resource
GET: Retrieves a resource
Since we’re using MongoDB, we have as a matter of course collected all the settings of a user in a single URI (web resource). Over time, these URIs have grown to hold a lot of settings. To make things easier for our web client and mobile app, we realized that we needed to be able to update only some of these settings.
We could have chosen to add a new set of URIs to target certain parts of the settings. However, to prevent burdening our API with a long list of URIs, we have decided to use the PATCH method.
The PATCH specifications state that:
A new method is necessary to improve interoperability and prevent
errors. The PUT method is already defined to overwrite a resource
with a complete new body, and cannot be reused to do partial changes.
The PATCH method requests that a set of changes described in the
request entity be applied to the resource identified by the Request-
URI. The set of changes is represented in a format called a “patch
document” identified by a media type.
So, the PATCH method allows you to only partially update settings. In other words, you can change one or a few of the settings, without having to specify the complete list of settings each time.
Since our API is based on JSON, we initially turned to the JSON patch specification. However, doing updates this way is not as easy as it might have been:
Personally, I find this specification a bit clumsy.
Then we came across a discussion on the PATCH implementation in Backbone. Based on that, we have chosen a PATCH implementation where you simply PATCH with the same JSON as you would use for PUT or POST, except that you can PATCH using an incomplete document.
The convention goes that what you PATCH will be updated, while attributes set to null will be deleted. Everything else remains unchanged.
To give an example using the following document:
When you PATCH it with this document:
The resource will be updated to this:
There is actually a specification for this kind of PATCH, with media-type: application/json-merge-patch.
I would love to hear what experiences others have with PATCH. Have you considered PATCH for your REST API? Have you chosen a different way of partially updating a resource?