PATCH vs PUT and the PATCH JSON syntax war

Article

Dec 12, 2016
EquiValent - Tomas Valent

There are several articles/discussions on parallels of PUT vs PATCH and
when to use one before other.
Also the main struggle recent years seems to be how to translate the RFC proposal
for PATCH JSON format.
I’ve decided to spam the internet with one more opinionated article on this topic
trying to explain everything one more time.

First of all I’m a Ruby on Rails developer so I will reference some
sources from RoR world, but everything I say in this article apply to any programming language / web-app
framework. So please read the entire article before you start judging :)

You own a cow, you want to have more cows. So you hire sire service to impregnate your cow.
Now that the cow is pregnant, you want even more cows. Should you re-hire sire service to re-impregnate your
already pregnant cow even more ?

Can your cow get more pregnant ? Well, no! Cow impregnation is “Idempotent”.

The bottom point is that if you send one request changing User email from “A”
to “B”, and at the same time you request change from “A” to “C” second
requests should fail! And this way your PATCH it is non-idempotent.

This is due to the fact that you are not describing a change
therefore if you trigger them at the same time you would just say
“change User email to B”, “change User email to C” and nothing would stop the second change.
Therefore this way your PATCH is technically idempotent.

Should we use PUT instead ?

Well, no! …or maybe if it fits the definition.

PUT can be used not only for updating resources, but also for creating resources
too. Good example is AWS S3 API.
There you will use PUT to add the document to your bucket, and it still
properly RESTful !

I would even argue that PUT has nothing to do with
“update” at all, but it represent “replace”.

To truly comply witch RFC when you want to update user email with
PUT you would have to send all resource attributes (username, password,
address …), not only the email (as you are “replacing” the resource with a new one)

So with PUT you are replacing or creating resource.
PATCH is for update.

Conclusion

So that doesn’t solve the fact that some developer will say that this
{"user":{ "email": "[email protected]" }} PATCH style is wrong.

My opinion is that this is not really a problem. Lets be pragmatic, most of the time your
applications don’t deal with such large number of request that suddenly
every endpoint would be updated at the same time.

When this day comes and you actually have
this kind of scenario on some endpoints you can pass & store version number
of a last request. So for example both requests will send header with same
“version” but along with the email change we would store the
version number (e.g. in Redis) and
therefore second request would still point to the old version,
therefore this request would be non-idempotent even with that JSON syntax.