CodePark/ questions / Methods, safety & idempotency
START PRACTICINGPRACTICE
Backend question · HTTP & API design › Methods, safety & idempotency

Compare POST, PUT and PATCH for writing data. When would you use each on a /users API?

Use POST to create a user when the server picks the ID. Use PUT to replace a whole user at a known URL. Use PATCH to change only some fields.

POST asks the target resource to process the data in the body by its own rules. On a collection like /users, it usually means "create a new member", and the server picks the ID. For example, POST /users returns 201 with a Location header that holds the new user's URL. POST is not idempotent. Idempotent means that sending the same request many times has the same effect as sending it once. So sending POST twice can create two users.

PUT replaces the whole state of the target resource with the request body. It can also create the resource if the client already knows the URL, for example PUT /users/42. The server should remove or reset any fields the client leaves out. PUT is idempotent, because sending the same full user twice gives the same result.

PATCH applies a partial change that the body describes. For example, send PATCH /users/42 with {"email":"a@b.com"} in JSON Merge Patch format. PATCH is not idempotent by definition. A patch like increment counter changes the result each time it runs. Still, many patches happen to be idempotent.

  • POST lets the server process the data by its own rules, and usually creates a resource with an ID the server chooses.
  • PUT replaces the whole resource at a known URL, and it is idempotent.
  • PATCH makes a partial update using a patch format, and it is not idempotent by definition.
  • With PUT, a missing field means "replace it", not "keep it".