196 | Chapter 7: REST, Resources, and Web Services
REST maintains that all application state should be kept on the client. This is what is
meant bystatelessness; not that there is no state within the application, but that each
request can stand on its own; the client/server session itself maintains no state.
HTTP state
Let’s examine how state is typically dealt with in web applications. HTT Pprovides
cookies as a method for servers to persist small amounts of data on the client. Like
all protocols in layered systems, HTT Puses lower-level (stateless) primitives to build
higher-level (stateful) abstractions. Here, we’ll examine the mechanics of that
process.
By default, unless sessions are manually disabled, Rails sets up a new session on a
client’s first interaction with the application. At the HTT Plevel, it looks like this
(irrelevant headers elided):
Client➝ Server
GET / HTTP/1.1
Host: http://www.example.com
The HTTPHostrequest header is mandatory in HTT P1.1. It tells the
server which DNS name was used to contact it. This is essential for
name-based virtual hosting. Thousands of sites may share one IP
address, differentiated only by theHost headers sent by clients.
Server➝ Client
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Set-Cookie: _session_id=6cd3556deb0da54bca060b4c39479839; domain=example.com
In this example, the server explicitly sets the cookie domain to
example.com. Without thedomainparameter, the cookie’s scope would
be limited towww.example.com(the domain of the original request) and
its subdomains, for security reasons. But since the server set the cookie
with the more general domain, it will be shared between requests to
example.com,www.example.com,shop.example.com, and the like.
When a client requests a URI from a server, it sends any applicable cookies in the
request headers.
Client➝ Server
GET /protected-resource HTTP/1.1
Host: http://www.example.com
Cookie: _session_id=6cd3556deb0da54bca060b4c39479839
By using HTT Pcookies, application state is made persistent. This can have its advan-
tages. Sometimes it is used for tracking; it is an easy way to watch a visitor as he
progresses through a site. But most often, cookies are used to track user authentica-
tion and/or personalization.