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

(Tuis.) #1
What Is REST? | 195

accept, in decreasing order of priority. Under content negotiation on the preceding
service, this request would return the HTML version:


GET /orders/124 HTTP/1.1
Host: http://www.example.com
Accept: text/html, application/xhtml+xml, text/*, image/png, image/*, */*

Clients can vary their Acceptheader to request different representations of the
requested resource, and the server will try to satisfy the request with any representa-
tions it can serve.


Basing the choice of representation on either URI extensions orAcceptheader con-
tent negotiation is a valid decision. They each have their benefits and drawbacks, and
Rails supports both.


Statelessness


At the network level, HTT Pis a stateless protocol. Each client/server interaction
repeats some information on each connection to the server. This costs some redun-
dancy, but it pays off in other areas such as scalability. By definition, Fielding’s REST
is always stateless. The interaction between client and server carries no state at lower
or higher levels.


However, there is a difference between resource state and application state.
Resource stateis the internal state that all nontrivial resources carry, and it is essen-
tial to a web application. Examples of resource state would include the changes
made to a hosted document or the content of a to-do list; without this state, there
would be no application.


On the other hand,application state(also calledsession state) is the state of the cli-
ent’s interaction with the server. Application state tracks a user or client’s progress
through an application. Keeping this state on the server violates REST principles as it
breaks addressability. An implication of REST is that the representation retrieved
from a resource should depend only on that resource’s state and the client’s request.
If the server presents a different representation for the same URI based on the path
that the client took to get to that URI, then the URI loses its addressability. It cannot
be shared or bookmarked.


At the lower levels, application state includes HTT Pcookies, which can break REST
in lesser or greater amounts. At the higher levels, web application frameworks (Rails
included) often expose a session persistence mechanism. Typically, a repository of
session state is kept on the server, indexed by a key that is given in an HTT Pcookie
to the client.* This is much more self-evidently an application state repository.



  • Newer versions of Rails default to a cookie-based session store, which stores the entire session, not just an
    index, in the cookie. This has several advantages, but also some security concerns. I discuss the trade-offs in
    Chapter 5.

Free download pdf