pbojinov
5/29/2014 - 11:15 PM

HTTP Patch for APIs - https://willnorris.com/2014/05/go-rest-apis-and-pointers

Understanding PATCH

As its name implies, a REST-based API involves passing around the representation of the state of a resource. This is most commonly applied to HTTP, which is very straightforward: to read the current state of a resource, perform a GET operation on the resource’s URI. To update a resource, pass the new representation of the resource to its URI in a PUT operation. The PUT method is defined as a complete replacement of the resource at a given URI, meaning you must always provide the full representation that you want to set. But what if you only want to update a few fields in the resource? That’s done with the PATCH method.

The exact semantics of how the body of a PATCH request is applied to the requested resource are determined by the media type of the request. The way GitHub (and many other JSON APIs) handles PATCH requests is that you provide the JSON representation of the resource to update, omitting any fields that should be left unchanged. So for example, to update only the description of a repository, the HTTP request might look something like:

PATCH /repos/google/go-github HTTP/1.1
Host: api.github.com

{"description": "new description"}
To delete the description entirely, simply set it to an empty string:

PATCH /repos/google/go-github HTTP/1.1
Host: api.github.com

{"description": ""}
What if you were to perform a PATCH request with every field specified? That would actually be semantically equivalent to a PUT request with the same request body. In fact, because of this, all resource updates in the GitHub API are done using PATCH. They don’t even support (or at least, don’t document) using PUT at all for these types of requests.