Differences Between PUT and PATCH Methods in Real-World REST API Applications

Definitions:

  • PUT: This method asks for the enclosed data to be stored at the specified Request-URI. If that URI indicates an existing resource, the data should be seen as a modified version of what is currently stored. If the URI does not point to any resource, the server may create a new one at that location.

  • PATCH: This method requests that a specific set of updates be applied to the resource identified by the Request-URI.

Real-Life Example:

Consider a scenario where I POST to /accounts with payload {name: 'johnDoe', email: '[email protected]'}. The server then creates a resource and responds with a 201 status code and location /accounts/1. Subsequently, a GET request to /accounts/1 retrieves {id: 1, name: 'johnDoe', email: '[email protected]'}.

If I want to update my email address, this modification involves a set of changes, so I’d issue a PATCH request to /accounts/1 with the JSON {email: '[email protected]'}. The server acknowledges this with a 200 status code.

Questions:

  1. If PATCH is supposed to be non-idempotent and issuing the same PATCH request yields the same result (with my email updated), how is PATCH considered non-idempotent?

  2. What fundamentally distinguishes PUT from PATCH? I’ve learned that PUT is meant for replacing an entire entity at a specific resource, necessitating the full entity data. What practical scenarios require replacing or overwriting an entity using PUT, and why is this operation categorized differently from updating or patching the entity? After the introduction of PATCH, using PUT for a single entity seems redundant. Am I mistaken?

In real-world terms, think of the PUT method as telling the server to “take this whole new document and replace whatever’s there,” almost like overwriting a file with a complete new version. This approach is useful in cases where the entire resource has to be rebuilt from scratch, such as during synchronization of resources in systems that require the entire updated state, ensuring consistency across distributed systems. PATCH, on the other hand, is akin to saying “just tweak these few lines,” which is more efficient when you’re only making minor changes. For instance, in version-controlled environments or collaborative projects, PATCH is very beneficial to ensure efficiency and reduce network payload when dealing with minor updates. Meanwhile, PUT’s necessity remains in scenarios needing reliability in replicating identical resources independently across multiple instances. Thus, redundancy is not the issue but rather serves as a tool for different requirements.