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

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

Representations and Content Types


Resources on the Web “live” and hold their state at the server, but they are only ever
accessed through the representations that they expose. Like Plato’s cave, we never
see the resource itself; all that we see are the shadows on the wall—the representa-
tions of that resource.


Different representations of a resource vary based on their content types. The same
resource might be available at/users/1.html,/users/1.xml, and/users/1.js. The
formats of these names imply that they are representations of the same resource
(again, even if the names are treated as opaque and the client cannot rely on this
knowledge, it is a valuable convention).


Selecting a representation


One detail unspecified by REST is how a client requests a particular content type. As
many representations may be available from the same resource, how does the server
know which one to send?


In practice, the answer is either URI extensions or content negotiation. Extensions
are easy to understand and implement: the URI is examined for a filename extension
(such as.js,.html,or.xml). The most suitable representation is then selected based
on atype map(a structure that maps filename extensions to content types). For
example, fetching the URI/orders/124.html might return:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Viewing Order #124</title>
</head>

Hypermedia Drives Application State
An oft-repeated mantra (originally from Fielding’s thesis) is that of “hypermedia as the
engine of application state.” In other words, given an entry point to a RESTful appli-
cation, hypermedia links can be used to navigate through all necessary application
state. This makes applications more resilient to name changes, as the only URI the cli-
ent must know is that of the entry point. In addition, URIs can be treated as opaque if
desired. This is obviously a desirable architectural quality, as it enables more options.
However, there are not many true implementations of this in the wild. A primary
obstacle to adoption is the dearth of ways to represent semantic metadata in hyper-
media at the moment. RDF is gaining currency in this field, but there are still few well-
known best practices as to how to encode relationships between resources within their
representations.
Free download pdf