Conventional wisdom says that REST APIs should be implemented as follows:
GET
– readPOST
– addPUT
/PATCH
– modifyDELETE
– remove
This mostly works well. Query parameters can be used to supply arguments for GET
and DELETE
operations. POST
s can use either URL-encoded or multipart form data, standard encodings supported by nearly all HTTP clients.
However, it doesn’t work quite as well for PUT
or PATCH
. PUT
has no standard encoding, and requires the entire resource to be sent in the payload. PATCH
was introduced as a workaround to this limitation, but it also lacks a standard encoding, and is not supported by all clients (notably Java).
However, the POST
method can also be used to modify resources. The semantics of POST
are less strict than PUT
, so it can support partial updates, like PATCH
. Further, the same encoding used for creating resources (URL-encoded or multipart) can also be used for updates.
For example:
POST /products
– add a new resource to the “products” collection using the data specified in the request bodyPOST /products/101
– update the existing resource with ID 101 in the products collection using the (possibly partial) data specified in the request body
This approach works particularly well when resources are backed by relational database tables. An “add” POST
maps directly to a SQL INSERT
operation, and a “modify” POST
translates to a SQL UPDATE
. The key/value pairs in the body (whether URL-encoded or multipart) can be mapped directly to the table columns.
The approach also supports bulk inserts and updates. POST
ing a URL-encoded payload works well for individual records, but JSON, CSV, or XML could easily be used to add or update multiple records at a time.
So, do you really need PUT
and PATCH
? Given that POST
is more flexible, better supported, and can handle both create and update operations, I’d say no. Please share your thoughts in the comments!
FWIW, HTTP verbs are just intents and how each intent is processed is left to the involving parties. Having said that, from conventional wisdom, you are probably right. However, undermining PUT/PATCH from languages, (en/de)coders point of view might be flawed way to look at them.
some content to back my thoughts:
https://www.w3.org/blog/2008/10/understanding-http-put/
LikeLike
Thanks for the feedback – I will check out the link.
LikeLike