Sobes.tech
Junior — Middle

When is it preferable to use PUT, and when POST in REST API?

sobes.tech AI

Answer from AI

The PUT method in REST API is preferred when you need to completely replace or create a resource at a known URI. PUT is idempotent — repeated requests with the same data will not change the result.

The POST method is used for creating new resources or performing operations that are not idempotent. Usually, POST is sent to a collection, and the server generates the URI of the new resource.

Example:

  • PUT /users/123 — update or create a user with ID 123.
  • POST /users — create a new user, the server will assign an ID.

In summary:

  • Use PUT to update/create a resource at a known address.
  • Use POST to create a resource with a server-generated identifier or for actions not directly related to resources.