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

(Tuis.) #1

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


HTT Pdefines a handful of methods; the set can be expanded by protocols such as
WebDAV, but the basic set is sufficient for REST. The four most common methods
areGET,PUT,DELETE, andPOST; we will examine each of them and their purpose here.


We can form some linguistic analogies as a simplification of the four common verbs.
Roughly speaking, this is what they mean, using “this” to refer to the request body,
and “there” to refer to the URI acted upon:



  • GET: “Give me whatever is there.”

  • PUT: “Store this there.”

  • DELETE: “Delete whatever is there.”

  • POST: “Hey you there, process this.”


GET


TheGETmethod transfers a representation of a resource from the server to the client.
It is used for read-only access to a resource.GETis by far the most common verb on
the Web; it is often the only method used on static web sites.


A common mistake is to useGETfor an action that updates a resource.GETis defined
as asafemethod (see the upcoming sidebar, “Safe and Idempotent Methods”); it
should be used for retrieval, not updates. UsingGETfor updates causes many prob-
lems because it breaks the assumptions that the client and any proxies may have
about the nature ofGET requests.


This problem came into the Rails public eye in 2005, when the Google Web Accelera-
tor was released. The Web Accelerator is a proxy that uses the time the user is viewing a
page to prefetch the outgoing links from that page, reducing the latency between click-
ing on a link and seeing the resulting page. Because following a link that updates the
server could have catastrophic results (consider prefetching every “Delete” link on a
page full of users), the Accelerator only followed standard web links (which useGET).


However, many popular web applications (including 37signals’ Backpack) were vul-
nerable. Many Rails applications were affected, as the Rails “pretty URL” convention
dictated URLs like/people/delete/123, rather than the conventions of other web
frameworks, which led to URLs like/people.php?action=delete&id=123. The end result
was a scramble among web developers to convert allGETlinks with side effects into
POSTs. Later, the Google team added a feature to the Web Accelerator so that it would
not prefetch links with query strings, but there was a scramble nevertheless.


However, all of this fuss was but a symptom of the real problem. The problem was
not so much thatGETlinks performed actions; it was that HTT Pwas being used
improperly. The contract between clients and servers had been broken. So, when all
of theGET /people/delete/123actions becamePOST /people/delete/123, it was an
improvement, but not by much, asPOSTis not terribly relevant to a “delete person”
action. A more RESTful design would involve an action such asDELETE /people/123.

Free download pdf