Safety, Idempotence, and the Resource-Oriented Architecture - Safety and Idempotence (Page 2 of 5 )
If you expose HTTPís uniform interface as it was designed, you get two useful properties for free. When correctly used, GET and HEAD requests are safe. GET, HEAD, PUT and DELETE requests are idempotent.
A GET or HEAD request is a request to read some data, not a request to change any server state. The client can make a GET or HEAD request 10 times and itís the same as making it once, or never making it at all. When you GET http://www.google.com/search?q=jellyfish, you arenít changing anything about the directory of jellyfish resources. Youíre just retrieving a representation of it. A client should be able to send a GET or HEAD request to an unknown URI and feel safe that nothing disastrous will happen.
This is not to say that GET and HEAD requests canít have side effects. Some resources are hit counters that increment every time a client GETs them. Most web servers log every incoming request to a log file. These are side effects: the server state, and even the resource state, is changing in response to a GET request. But the client didnít ask for the side effects, and itís not responsible for them. A client should never make a GET or HEAD request just for the side effects, and the side effects should never be so big that the client might wish it hadnít made the request.
Idempotence is a slightly tricker notion. The idea comes from math, and if youíre not familiar with idempotence, a math example might help. An idempotent operation in math is one that has the same effect whether you apply it once, or more than once. Multiplying a number by zero is idempotent: 4 ◊0 ◊0 ◊0 is the same as 4 ◊0.# By analogy, an operation on a resource is idempotent if making one request is the same as making a series of identical requests. The second and subsequent requests leave the resource state in exactly the same state as the first request did.
PUT and DELETE operations are idempotent. If you DELETE a resource, itís gone. If you DELETE it again, itís still gone. If you create a new resource with PUT, and then resend the PUT request, the resource is still there and it has the same properties you gave it when you created it. If you use PUT to change the state of a resource, you can resend the PUT request and the resource state wonít change again.
The practical upshot of this is that you shouldnít allow your clients to PUT representations that change a resourceís state in relative terms. If a resource keeps a numeric value as part of its resource state, a client might use PUT to set that value to 4, or 0, or 50, but not to increment that value by 1. If the initial value is 0, sending two PUT requests that say ďset the value to 4Ē leaves the value at 4. If the initial value is 0, sending two PUT requests that say ďincrement the value by 1Ē leaves the value not at 1, but at 2. Thatís not idempotent.