Search code examples
restpatchput

REST - PUT or PATCH when updating all properties of an entity


In a REST API, when I want to update all the properties of an entity, what is better to use in terms of good practices? PUT or PATCH? If it is better to use PATCH, why is PUT necessary? What would be the difference between the two?

If all fields are updated, in that case both operations are idempotent, right? So, what is the difference?


Solution

  • PUT is idempotent, PATCH is not. The fact that PUT is idempotent means that general purpose components can repeat a single request as many times as is necessary to produce a response.

    PATCH, like POST, doesn't not promise idempotent semantics; so general purpose components are more tightly constrained in terms of what actions they can take on their own.

    If all fields are updated, in that case both operations are idempotent, right?

    A general-purpose component will have no understanding of whether or not all fields are updated. A high level heuristic is this: general purpose components understand the semantics of the HTTP headers, but not necessarily the semantics of the message bodies.

    And, In this case, why is the PATCH of a complete resource not idempotent?

    The implementation of PATCH can, indeed, be idempotent. But it doesn't have to be -- the semantics of PATCH requests don't promise idempotent handling, and therefore general-purpose components must not assume.

    An analogy that might help: we prefer to use GET for queries, because GET is safe. However, sometimes other things (like de facto URI length limits) get in the way, and we are forced to use POST. There's absolutely no reason why we cannot produce a POST handler that is effectively read only.

    But what we don't have is any mechanism that allows us to tell a general-purpose client that this particular use of POST happens to be safe.

    GET is defined to be safe, and therefore every resource in the world is expected to handle it safely. POST is not defined to be safe; only some resources in the world handle a POST safely. And therefore general-purpose components cannot assume that any particular resource handles a POST request safely.

    The same holds for idempotent semantics, and PUT vs POST/PATCH.