In part 1 I covered the basics of REST: the URLs and verbs. In part 2 we’ll cover responses.
Response
A REST web service can return anything, though typically they return either XML or JSON. JSON stands for JavaScript Object Notation, and is pronounced just like the name “Jason”.
It’s JavaScript’s shortcut notation for creating objects, but it’s just a data format and doesn’t require JavaScript at all (just as XML also works in any programming language). JSON is typically terser than XML, and thus uses less bandwidth.
Here’s an example:
{
"id" : 1234,
"firstName" : "Bill",
"lastName" : "Billford",
"hours" : [
{ "day" : "Monday", "start" : "8:00", "end" : "17:00" },
{ "day" : "Tuesday", "start" : "9:00", "end" : "17:00" },
{ "day" : "Wednesday", "start" : "8:00", "end" : "17:00" },
{ "day" : "Thursday", "start" : "8:00", "end" : "17:00" },
{ "day" : "Friday", "start" : "8:00", "end" : "17:00" }
]
}
The curly braces { and } represent an object, which is basically key/value pairs. To the left of the colon is the key, and to the right is the value. When enclosed in quotes the value is a string, or, when quotes are omitted, the value is a number, a boolean, or null.
Key/value pairs can be in any order, as order is only relevant in arrays. Arrays are represented by square braces [ and ], and can contain values or even nested objects.
A typical JSON response is unformatted, so whitespace isn’t transmitted in the response, thus conserving bandwidth:
{"id":1234,"firstName":"Bill","lastName":"Billford","hours":
[{"day":"Monday","start":"8:00","end":"17:00"},{"day":
"Tuesday","start":"9:00","end":"17:00"},{"day":"Wednesday",
"start":"8:00","end":"17:00"},{"day":"Thursday","start":"8:00",
"end":"17:00"},{"day":"Friday","start":"8:00","end":"17:00"}]}
Third-party JSON formatters add the whitespace back, making the second example much easier to read. I recommend one that works offline, such as this one.
Summary
There’s more to REST than we’ve covered in these two posts, but this should be a good introduction. REST is simple, and, as an architectural philosophy, there aren’t many hard-and-fast rules. Something just feels RESTful or it doesn’t. When you get it right, it’s typically much easier for others to determine how your service works, since so many of us are already familiar with the web.
Further Reading and Source Material Used
- http://en.wikipedia.org/wiki/Representational_State_Transfer
- http://jcalcote.wordpress.com/2008/10/16/put-or-post-the-rest-of-the-story/
- http://stackoverflow.com/questions/630453/
- http://www.elharo.com/blog/software-development/web-development/2005/12/08/post-vs-put/
- http://www.markbaker.ca/2002/08/HowContainersWork/
- http://www.artima.com/lejava/articles/why_put_and_delete.html
- http://json.org/