Tuesday 11 April 2017

How to Implement Safe and Idempotent Methods on the Server?


Implementing safe methods
In HTTP, safe methods are not expected to cause side effects. Clients can send requests with safe methods without worrying about causing unintended side effects. To provide this guarantee, implement safe methods as read-only operations.

Safety does not mean that the server must return the same response every time. It just means that the client can make a request knowing that it is not going to change the state of the resource.
Example, both the following requests may be safe:

# First request
GET /emp?symb=rajesh HTTP/1.1
Host: www.comviva.org

HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8

15.96

# Second request after 5 minutes
GET /emp?symb=rajesh HTTP/1.1
Host:  www.comviva.org

HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8

16.10

Implementing idempotent methods
Idempotency matters most in the case of network or software failures. Clients can repeat such requests and expect the same outcome.
Idempotency guarantees clients that repeating a request have the same effect as making a request just once.

Idempotency of PUT
Example, consider the case of a client updating the price of a book.

# Request
PUT /books/poor-dad-rich-dad/price/us HTTP/1.1
Host: www.flipkart.com
Content-Type: application/x-www-form-urlencoded

val=14.95
Now assume that because of a network failure, the client is unable to read the response. Since HTTP says that PUT is idempotent, the client can repeat the request.

# Request
PUT /books/poor-dad-rich-dad/price/us HTTP/1.1
Host: www.flipkart.com
Content-Type: application/x-www-form-urlencoded

val=14.95

# Response
HTTP/1.1 200 OK
Content-Type: application/xml;charset=UTF-8

<value>14.95</value>

Idempotency of DELETE
The DELETE method is idempotent. This implies that the server must return response code 200 (OK) even if the server deleted the resource in a previous request.
However in practice, implementing DELETE as an idempotent operation requires the server to keep track of all deleted resources. Otherwise, it can return a 404 (Not Found).

# First request
DELETE /book/poor-dad-rich-dad/ HTTP/1.1
Host: www.flipkart.com

# Response
HTTP/1.1 200 OK

# Second request
DELETE /book/poor-dad-rich-dad/ HTTP/1.1
Host: www.flipkart.com

# Response
HTTP/1.1 404 Not Found
Content-Type: text/html;charset=UTF-8

<html>
  ...
</html>

Even when the server has a record of all the deleted resources, security policies may require the server to return a 404 (Not Found) response code for any resource that does not currently exist.

1 comment:

Related Posts Plugin for WordPress, Blogger...