Sobes.tech
Senior

What is idempotency in the context of HTTP methods?

sobes.tech AI

Answer from AI

Idempotency in the context of HTTP methods means that performing the same request multiple times will not change the server's state after the first execution.

That is, if you send the same idempotent request multiple times, the result will be the same as if you sent it once.

Examples of idempotent methods:

  • GET — retrieves a resource, does not change the state.
  • PUT — updates a resource, repeated requests with the same data will not change the result.
  • DELETE — deletes a resource, repeated requests will delete the resource once, subsequent ones will not change the state.

Example:

import requests

url = 'https://api.example.com/resource/1'

# PUT request updates the resource
response1 = requests.put(url, json={'name': 'new name'})
response2 = requests.put(url, json={'name': 'new name'})

# Both requests will lead to the same state of the resource

Thus, idempotency is important for the reliability and predictability of APIs, especially when repeated requests are made due to network failures.