0
0
Rest APIprogramming~5 mins

Idempotency of methods in Rest API

Choose your learning style9 modes available
Introduction

Idempotency means doing the same action many times has the same effect as doing it once. This helps avoid mistakes when requests are repeated.

When a user clicks a button multiple times but you want only one action to happen.
When a network error causes a request to be sent again and you want to avoid duplicate changes.
When updating or deleting data and you want to make sure the result is stable no matter how many times the request runs.
Syntax
Rest API
HTTP methods like GET, PUT, DELETE are idempotent by design.
POST is usually not idempotent.

Example:
PUT /items/123 {"name": "book"}

This request can be sent many times and the item will be the same after each call.

GET requests only read data and never change it, so they are always idempotent.

PUT replaces or updates a resource fully, so repeating it does not change the result after the first time.

Examples
GET is safe and idempotent because it only reads data.
Rest API
GET /users/1

// This just fetches user data. No matter how many times you do it, the user data stays the same.
PUT is idempotent because the resource ends up the same after each request.
Rest API
PUT /users/1 {"name": "Alice"}

// This updates user 1's name to Alice. Sending this many times keeps the name as Alice.
DELETE is idempotent because deleting something that is already deleted has no extra effect.
Rest API
DELETE /users/1

// This deletes user 1. Doing it once or multiple times results in user 1 being gone.
POST is not idempotent because it creates new resources each time.
Rest API
POST /users {"name": "Bob"}

// This creates a new user. Sending this multiple times creates multiple users, so POST is not idempotent.
Sample Program

This program sends GET and PUT requests twice to the same URL. The GET requests return the same data both times. The PUT requests update the resource with the same data twice, so the result is the same after each call.

Rest API
import requests

url = 'https://jsonplaceholder.typicode.com/posts/1'

# GET request - idempotent
response1 = requests.get(url)
response2 = requests.get(url)

print('GET request repeated:')
print(response1.json())
print(response2.json())

# PUT request - idempotent
put_data = {"title": "foo", "body": "bar", "userId": 1}
response3 = requests.put(url, json=put_data)
response4 = requests.put(url, json=put_data)

print('\nPUT request repeated:')
print(response3.json())
print(response4.json())
OutputSuccess
Important Notes

Idempotency helps make APIs reliable and safe to retry.

Not all HTTP methods are idempotent; know which ones are to avoid bugs.

Sometimes APIs add special headers or tokens to make POST requests idempotent.

Summary

Idempotent methods produce the same result no matter how many times they run.

GET, PUT, DELETE are idempotent; POST usually is not.

Using idempotent methods helps avoid duplicate changes and errors.