Sobes.tech
Senior

REST HTTP methods: what are they, what is each used for, which are idempotent, which are not?

sobes.tech AI

Answer from AI

Main HTTP methods in REST and their purpose:

  • GET — retrieve a resource. Idempotent and safe method, should not change the server state.
  • POST — create a resource or perform an operation. Not idempotent, repeated calls may create duplicates.
  • PUT — update or replace a resource. Idempotent: repeated calls with the same data will not change the result.
  • PATCH — partial update of a resource. Usually idempotent, but depends on implementation.
  • DELETE — delete a resource. Idempotent: repeated deletion of the same resource will not change the state.
  • HEAD — retrieve only the headers of a resource, without the body. Idempotent and safe.
  • OPTIONS — get the supported methods for a resource from the server.

Idempotent methods: GET, PUT, DELETE, HEAD, OPTIONS, PATCH (usually).

Non-idempotent method: POST.

Example:

  • GET /users/123 — get user with ID 123
  • POST /users — create a new user
  • PUT /users/123 — replace data of user 123
  • PATCH /users/123 — update part of user 123's data
  • DELETE /users/123 — delete user 123

Idempotency is important for reliability: if a request is repeated (for example, due to network failures), the server state will not change unpredictably.