Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PATCH is neither safe nor idempotent?

I have trouble understanding why PATCH is not safe where PUT is. Aso the idempotent part - if I update a field of the resource, wouldn't that field return the same value after update?

like image 677
Tony Vincent Avatar asked Dec 30 '16 05:12

Tony Vincent


People also ask

Is PATCH HTTP method idempotent?

The PATCH method is not idempotent. It can be made idempotent by using a conditional request. When a client makes a conditional request to a resource, the request succeeds only if the resource has not been updated since the client last accessed that resource.

Why is POST method not idempotent?

Post method always results in a server state change. If the POST method was idempotent, everything sent and accepted to or from the web server would already have to exist on the server in some form to respond with the same codes and value response. For that reason, POST cannot be idempotent.

Is PATCH RESTful?

It is worth mentioning that PATCH is not really designed for truly REST APIs, as Fielding's dissertation does not define any way to partially modify resources. But, Roy Fielding himself said that PATCH was something [he] created for the initial HTTP/1.1 proposal because partial PUT is never RESTful.


1 Answers

It's not safe because in general you can't safely execute a PATCH request without changing a resource (That's what it's for).

So why is PATCH not idempotent compared to PUT? It's because it matters how you apply your changes. If you'd like to change the name property of a resource, you might send something like {"name": "foo"} as a payload and that would indeed be idempotent since executing this request any number of times would yield the same result: The resources name attribute is now "foo".

But PATCH is much more general in how you can change a resource (check this definition on how to apply a JSON patch). It could also, for example, mean to move the resource and would look something like this: { "op": "move", "from": "/a/b/c", "path": "/a/b/d" }. This operation is obviously not idempotent since calling at a second time would result in an error.

So while most PATCH operations might be idempotent, there are some that aren't.

One remark on the other answers: Idempotence is defined by repeating an operation multiple times in a row. Saying that something is not idempotent because the effect is different if some other operation was executed in between or in parallel just isn't a valid argument (no operation would be idempotent in general if that was the case). Mathematically, an idempotent transformation is one that yields the same result, no matter how often you apply it (like rotating something 360 degrees). Of course two 360 deg rotation might yield different results if you apply any other operation in between.

like image 85
C. Doe Avatar answered Sep 18 '22 22:09

C. Doe