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

(Tuis.) #1

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


<body id="order-124">
<h1>Order #124</h1>
<p>Items:</p>
<ul id="order-124-items">
<li><a href="/orders/124/items/1">Office Chair, Medium</a></li>
<li><a href="/orders/124/items/2">Ergonomic Keyboard</a></li>
</ul>
</body>
</html>

But a request to the same resource with a different URI, at/orders/124.xml, might
result in a more easily machine-readable XML version:


<Order id="124">
<Items>
<Item id="1" href="/orders/124/items/1">Office Chair, Medium</Item>
<Item id="2" href="/orders/124/items/2">Ergonomic Keyboard</Item>
</Items>
</Order>

The JavaScript representation at/orders/124.js might use JSON:


{"order": {
"id": 124,
"items": [
{"id": 1, "href": "/orders/124/items/1",
"description": "Office Chair, Medium"},
{"id": 2, "href": "/orders/124/items/2",
"description": "Ergonomic Keyboard"}]
}}

Changing content types based on URI extensions is nice and easy, and it plays well
with the way we traditionally expect the Web to work. Among other things, it makes
the URIs look like filenames again, and behave somewhat like filesystem paths.
However, this is not always optimal within the REST model.


All of these are clearly different representations of the same resource, and yet they
have different URIs. Many argue that the URI should name only the resource, and
not the representation. How would it be possible to use the same name to refer to all
of these resources?


The answer iscontent negotiation. This is a part of the HTT Prequest and response
where the client and server negotiate some common parameters so that they can
communicate.


As a whole, HTT Pcontent negotiation is very flexible; it can negotiate a representa-
tion based on language (through theAccept-Languagerequest header), character
encoding (through theAccept-Charsetheader), content coding (Accept-Encoding), or
content type (Accept). It is the latter that we are most concerned with.


Rather than specifying the content type explicitly in the URI, we specify anAccept
header in the HTT Prequest. This header lists the content types we are willing to

Free download pdf