0
0
Rest-apiHow-ToBeginner ยท 3 min read

Which HTTP Methods Are Idempotent: Quick Guide

The HTTP methods GET, PUT, DELETE, HEAD, OPTIONS, and TRACE are idempotent. This means making the same request multiple times results in the same server state as making it once.
๐Ÿ“

Syntax

Idempotent HTTP methods can be called multiple times without changing the result beyond the initial application.

Here are the common idempotent methods:

  • GET: Retrieve data without side effects.
  • PUT: Update or create a resource at a specific URL.
  • DELETE: Remove a resource.
  • HEAD: Like GET but only retrieves headers.
  • OPTIONS: Describe communication options for the target resource.
  • TRACE: Echo the received request for testing.
http
GET /resource HTTP/1.1
PUT /resource HTTP/1.1
DELETE /resource HTTP/1.1
HEAD /resource HTTP/1.1
OPTIONS /resource HTTP/1.1
TRACE /resource HTTP/1.1
๐Ÿ’ป

Example

This example shows how repeated PUT and DELETE requests behave idempotently on a resource.

python
import requests

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

# PUT request to update resource
put_response1 = requests.put(url, json={'title': 'foo'})
put_response2 = requests.put(url, json={'title': 'foo'})

# DELETE request to remove resource
# First delete
delete_response1 = requests.delete(url)
# Second delete (resource already deleted)
delete_response2 = requests.delete(url)

print('PUT 1 status:', put_response1.status_code)
print('PUT 2 status:', put_response2.status_code)
print('DELETE 1 status:', delete_response1.status_code)
print('DELETE 2 status:', delete_response2.status_code)
Output
PUT 1 status: 200 PUT 2 status: 200 DELETE 1 status: 200 DELETE 2 status: 200
โš ๏ธ

Common Pitfalls

One common mistake is assuming POST is idempotent. It is not, because it usually creates new resources each time.

Another pitfall is using PUT incorrectly by sending partial updates, which can cause unexpected results.

http
### Wrong: Using POST expecting idempotency
POST /resource HTTP/1.1

### Right: Use PUT for idempotent update
PUT /resource HTTP/1.1
{
  "name": "new name"
}
๐Ÿ“Š

Quick Reference

HTTP MethodIdempotent?Description
GETYesRetrieve resource without side effects
PUTYesCreate or replace resource at URL
DELETEYesRemove resource
HEADYesRetrieve headers only
OPTIONSYesDescribe communication options
TRACEYesEcho request for testing
POSTNoCreate resource, not idempotent
โœ…

Key Takeaways

Idempotent HTTP methods produce the same result no matter how many times they are called.
GET, PUT, DELETE, HEAD, OPTIONS, and TRACE are idempotent.
POST is not idempotent because it creates new resources each time.
Use PUT for updates to ensure idempotency, not partial updates.
Understanding idempotency helps design reliable and safe REST APIs.