0

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?

New contributor
Mr. Mars is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • 1
  • PATCH specifically deals with partial data. I.e. only update the fields specified. see developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH . The same resource also adds that PUT is designed for whole resource replacement. – Berin Loritsch Feb 13 at 0:00
  • 1
    PATCH is NOT idempotent, whereas PUT is. – Berin Loritsch Feb 13 at 0:01
  • 1
    If that same path does partial and total updates, then you should be able to continue to use PATCH. You don't really gain a whole lot by switching PATCH to PUT. – Berin Loritsch Feb 13 at 16:00
  • 1
    Think of it this way: PATCH allows you to work on a subset of information. That subset can be as little as an empty JSON object (no change) or as large as every field in the JSON object. The bottom line is only the data specified in the uploaded object is modified. The purpose is to allow partial updates to an object, and I don't see any cause to force PATCH to limit to subsets that are less than 100% of the object. – Berin Loritsch Feb 13 at 16:41
2

My answer depends on what the intent behind the update is.

  • If the intent is to always replace the whole object: use PUT
  • If the intent is to update a part of the object: use PATCH

The fact that in this particular case, "part of the object" happens to be 100% of the object shouldn't matter. If the call you are making will be doing partial updates as well as full updates, then having a consistent endpoint simplifies the code you have to write.

However, if the call you are making will always update the entire object use PUT. That is clearer as to your intentions, and if new fields are ever added to the object you will have an appropriate error message in the client code.

PATCH makes no guarantee of being idempotent, and since the intent is to allow partial updates to an object that makes sense. It should return the whole object with the changes applied after completion though.

PUT does have a guarantee of being idempotent, and as such requires the whole object to be replaced every time. Think of PUT as an UPSERT (Update or Insert if it doesn't exist). There typically is no body in the response. (201 for create, 204 for updates, and appropriate 400 series for errors)

Your Answer

Mr. Mars is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.