What Is REST? | 189
PUT
ThePUTmethod updates a resource with the representation provided in the body of
thePUTrequest. If the resource did not exist before thePUTrequest, the request cre-
ates a new one with the given representation.
A common point of confusion is how resource names (URIs) apply toPUTversusPOST
requests. APUTrequest must always be directed toward the URI of the resource in
question; even if creating a new resource, the URI must be that of the resource to be
created. If the client does not know the URI of the resource (for example, if it is
derived from a server-generated ID), aPOST request should be used.
Safe and Idempotent Methods
One purpose of the HTT Pstandard is to define the implicit meanings of the various
HTT Pmethods. This is the mental working model that many developers use when
working on web applications:GETretrieves a representation,PUTupdates a resource,
and so on.
But another, more important, purpose of the HTT Pspecification is to form an explicit
contract between the server, the client, and any proxies or caches along the way. This
tells each principal what they can and cannot assume about the data they work with.
The concepts of safe and idempotent methods fall under this category.
Safe methodsare used for retrieval; the purpose of a safe request should never be to per-
form an update. The HTT Psafe methods areGETandHEAD.(HEADis functionally equiv-
alent toGET, but only returns the response headers, not the body.)
Safety is usually defined at the application level, and the definition of a safe method can
change based on application semantics. AGEToperation may incur incidental side
effects, such as loading query results into a cache or updating a hit counter; the action
would still be described as safe. The distinction drawn by the HTT Pspecification is
that safe requests should not incur an obligation on the user’s behalf (such as an online
payment or creation of a user account). In other words, it must always be the server
that decides to perform an update based on a safe request.
GET,HEAD,PUT, andDELETEareidempotent methods. The result (response as well as
resource state) of an idempotent action is the same, no matter how many times that
action is performed (assuming each action is identical and there is otherwise no change
to resource state). Idempotent methods may change resource state, but they are not
required to (all safe methods are by definition idempotent).
The result of this definition is resiliency; if a client initiates aPUTrequest and is not
sure whether it completed successfully, it can retry the same request with no negative
consequences.