Debate around PUT vs POST for resource update is quite common; I have had my share as well. Debate is NOT un-necessary as the difference is very subtle. One simple line of defence by many people is that if the update is IDEMPOTENT then we should use PUT else we can use POST. This explanation is correct to a good extent; provided we clearly understand if a request is truly Idempotent or not.
Also, lot of content is available online which causes confusion. So, I tried to see what the originators of REST architectural style themselves say. This post might again be opinionated, or have missed few important aspects. I have tried to be as objective as possible. Feel free to post your comments/openions :)
Updating a Resource
For our understanding, let's take a case that we are dealing with an account resource which has three attributes: firstName, lastName and status.
Updating Status field:
Advocates of PUT consider below request to be IDEMPOTENT.
HTTP 1.1 PUT /account/a-123
{
"status":"disabled"
}
Reality is that, above request is NOT idempotent as it's updating a partial document. To make it idempotent you need to send all the attributes. So that line of defence is NOT perfect.
HTTP 1.1 PUT /account/a-123
{
"firstName":"abc",
"lastName":"rai",
"status":"disabled"
}
Below article tells very clearly that, if you want to use PUT to update a resource, you must send all attributes of the resource where as you can use POST for either partial or full update.
So, you can use POST for either full or partial update (until PATCH support becomes universal).
What the originator of REST style says
The master himself suggest that we can use POST if you are modifying part of the resource.
My Final Recommendation
Prefer POST if you are doing partial update of the resource.
If you doing full update of the resource and it's IDEMPOTENT, use PUT else use POST.
If you doing full update of the resource and it's IDEMPOTENT, use PUT else use POST.
No comments:
Post a Comment