Sobes.tech
Middle+

How to make a POST request idempotent?

sobes.tech AI

Answer from AI

POST requests are not idempotent by default, as each call can create new resources or change the server's state. To make POST requests idempotent, the following approaches can be used:

  • Idempotency Key: the client generates a unique identifier for each request and sends it in the header or body. The server stores this key and the result of the request, and upon receiving the same key again, it returns the same response without creating duplicates.

  • Using unique identifiers in the request body: for example, if an order is created with a unique number, a repeated request with the same number will not create a new order.

Example with Idempotency Key in HTTP:

POST /orders HTTP/1.1
Idempotency-Key: 123e4567-e89b-12d3-a456-426614174000
Content-Type: application/json

{
  "product_id": "abc123",
  "quantity": 1
}

The server, upon receiving a repeated request with the same key, will return the result of the first request, preventing duplication.

How to make a POST request idempotent? — System Analyst - sobes.tech