Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

190 | Chapter 7: REST, Resources, and Web Services


DELETE


As its name implies, theDELETEmethod deletes the resource identified by its URI. If
the deletion is carried out (the server may not allow a deletion), subsequentGETque-
ries to the same URI should return a status code of 410 (Gone) or 404 (Not Found).


POST


We listPOSTlast because it is the method of last resort. It is neither safe nor idempo-
tent, so there are few technical restrictions to its power. As such, it is abused for
many operations that could better be represented by another verb. Theoretically,
POSTcould be used for every action on the Web without violating the letter of the
RFC.


ThoughPOSTis powerful, it should not be used whereGET,PUT,orDELETEwould suf-
fice. The semantics of those three methods are much simpler, and the constraints put
on them allow easier caching and scalability.POSTcan, in theory, be cached via the
Cache-Control andExpires headers, but in practice this is rarely implemented.


POSTis primarily used in one of two ways: creation of new objects and annotation of
existing objects. In either case, the URI of thePOSTis that of the object’s container or
parent. The RFC draws an analogy of a directory structure; to create or update an
object, youPOST to its containing “directory.”


To create a resource, its representation is sent viaPOSTto a URI responsible for creat-
ing resources of that type. If the request for creation succeeds, the server issues a
redirect via theLocation header pointing to the URI of the created resource.


When annotating a resource, thePOSTURI is that of the resource to be annotated
(the “parent” of the entity being sent). This is different from aPUTrequest in that the
resource beingPOSTed to is not being updated with a new representation, but rather
annotated with additional information.


Resources


The most foundational concept of REST is theresource. The most general definition
of a resource issomething with identity. It really is as simple as that. In popular usage,
the term “resource” usually means something that is network-addressable on the
Internet, and it is with these types of resources that we will concern ourselves. But a
resource can really be anything, tangible or intangible, that can be named. As RFC
2396 explains:*


A resource can be anything that has identity. Familiar examples include an electronic
document, an image, a service (e.g., “today’s weather report for Los Angeles”), and a
collection of other resources. Not all resources are network “retrievable”; e.g., human
beings, corporations, and bound books in a library can also be considered resources.

*http://tools.ietf.org/html/rfc2396

Free download pdf