You are previewing RESTful Web Services.

RESTful Web Services

Cover of RESTful Web Services by Leonard Richardson... Published by O'Reilly Media, Inc.
  1. RESTful Web Services
    1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
    2. A Note Regarding Supplemental Files
    3. Foreword
    4. Preface
      1. The Web Is Simple
      2. Big Web Services Are Not Simple
      3. The Story of the REST
      4. Reuniting the Webs
      5. What’s in This Book?
      6. Administrative Notes
      7. Conventions Used in This Book
      8. Using Code Examples
      9. Safari® Enabled
      10. How to Contact Us
      11. Acknowledgments
    5. 1. The Programmable Web and Its Inhabitants
      1. Kinds of Things on the Programmable Web
      2. HTTP: Documents in Envelopes
      3. Method Information
      4. Scoping Information
      5. The Competing Architectures
      6. Technologies on the Programmable Web
      7. Leftover Terminology
    6. 2. Writing Web Service Clients
      1. Web Services Are Web Sites
      2. The Sample Application
      3. Making the Request: HTTP Libraries
      4. Processing the Response: XML Parsers
      5. JSON Parsers: Handling Serialized Data
      6. Clients Made Easy with WADL
    7. 3. What Makes RESTful Services Different?
      1. Introducing the Simple Storage Service
      2. Object-Oriented Design of S3
      3. Resources
      4. HTTP Response Codes
      5. An S3 Client
      6. Request Signing and Access Control
      7. Using the S3 Client Library
      8. Clients Made Transparent with ActiveResource
      9. Parting Words
    8. 4. The Resource-Oriented Architecture
      1. Resource-Oriented What Now?
      2. What’s a Resource?
      3. URIs
      4. Addressability
      5. Statelessness
      6. Representations
      7. Links and Connectedness
      8. The Uniform Interface
      9. That’s It!
    9. 5. Designing Read-Only Resource-Oriented Services
      1. Resource Design
      2. Turning Requirements Into Read-Only Resources
      3. Figure Out the Data Set
      4. Split the Data Set into Resources
      5. Name the Resources
      6. Design Your Representations
      7. Link the Resources to Each Other
      8. The HTTP Response
      9. Conclusion
    10. 6. Designing Read/Write Resource-Oriented Services
      1. User Accounts as Resources
      2. Custom Places
      3. A Look Back at the Map Service
    11. 7. A Service Implementation
      1. A Social Bookmarking Web Service
      2. Figuring Out the Data Set
      3. Resource Design
      4. Design the Representation(s) Accepted from the Client
      5. Design the Representation(s) Served to the Client
      6. Connect Resources to Each Other
      7. What’s Supposed to Happen?
      8. What Might Go Wrong?
      9. Controller Code
      10. Model Code
      11. What Does the Client Need to Know?
    12. 8. REST and ROA Best Practices
      1. Resource-Oriented Basics
      2. The Generic ROA Procedure
      3. Addressability
      4. State and Statelessness
      5. Connectedness
      6. The Uniform Interface
      7. This Stuff Matters
      8. Resource Design
      9. URI Design
      10. Outgoing Representations
      11. Incoming Representations
      12. Service Versioning
      13. Permanent URIs Versus Readable URIs
      14. Standard Features of HTTP
      15. Faking PUT and DELETE
      16. The Trouble with Cookies
      17. Why Should a User Trust the HTTP Client?
    13. 9. The Building Blocks of Services
      1. Representation Formats
      2. Prepackaged Control Flows
      3. Hypermedia Technologies
    14. 10. The Resource-Oriented Architecture Versus Big Web Services
      1. What Problems Are Big Web Services Trying to Solve?
      2. SOAP
      3. WSDL
      4. UDDI
      5. Security
      6. Reliable Messaging
      7. Transactions
      8. BPEL, ESB, and SOA
      9. Conclusion
    15. 11. Ajax Applications as REST Clients
      1. From AJAX to Ajax
      2. The Ajax Architecture
      3. A Example
      4. The Advantages of Ajax
      5. The Disadvantages of Ajax
      6. REST Goes Better
      7. Making the Request
      8. Handling the Response
      9. JSON
      10. Don’t Bogart the Benefits of REST
      11. Cross-Browser Issues and Ajax Libraries
      12. Subverting the Browser Security Model
    16. 12. Frameworks for RESTful Services
      1. Ruby on Rails
      2. Restlet
      3. Django
    17. A. Some Resources for REST and Some RESTful Resources
      1. Standards and Guides
      2. Services You Can Use
    18. B. The HTTP Response Code Top 42
      1. Three to Seven Status Codes: The Bare Minimum
      2. 1xx: Meta
      3. 2xx: Success
      4. 3xx: Redirection
      5. 4xx: Client-Side Error
      6. 5xx: Server-Side Error
    19. C. The HTTP Header Top Infinity
      1. Standard Headers
      2. Nonstandard Headers
    20. Index
    21. About the Authors
    22. Colophon
    23. SPECIAL OFFER: Upgrade this ebook with O’Reilly
O'Reilly logo

A Example

Back in Chapter 2 I showed clients in various languages for a REST-RPC hybrid service: the API for the social bookmarking application. Though I implemented my own, fully RESTful version of that service in Chapter 7, I’m going to bring the original service out one more time to demonstrate a client written in JavaScript. Like most JavaScript programs, this one runs in a web browser, and since it’s a web service client, that makes it an Ajax application. Although simple, this program brings up almost all of the advantages of and problems with Ajax that I discuss in this chapter.

The first part of the application is the user interface, implemented in plain HTML. This is quite different from my other clients, which ran on the command line and wrote their data to standard output (see Example 11-1).

Example 11-1. An Ajax client to the web service

 Transitional//EN" "">
<!--An Ajax application that uses the web service. This
     application will probably only work when saved as a local
     file. Even then, your browser's security policy might prevent it
     from running.-->

  <h1>JavaScript example</h1>

  <p>Enter your account information, and I'll fetch and
  display your most recent bookmarks.</p>

  <form onsubmit="callDelicious(); return false;"> 
    Username: <input id="username" type="text" /><br /> 
    Password: <input id="password" type="password" /><br /> 
    <input type="submit" value="Fetch bookmarks"/>

  <div id="message"></div>
  <ul id="links"></ul>

My user interface is an HTML form that doesn’t point anywhere, and some tags (div and ul) that don’t contain anything. I’m going to manipulate these tags with JavaScript functions. The first is setMessage, which puts a given string into the div tag (see Example 11-2).

Example 11-2. Ajax client continued: definition of setMessage

  <script type="text/javascript">      
   function setMessage(newValue) { 
     message = document.getElementById("message"); 
     message.firstChild.textContent = newValue;

And it’s not quite fair to say that the HTML form doesn’t point anywhere. Sure, it doesn’t have an “action” attribute like a normal HTML form, but it does have an onsubmit event handler. This means the web browser will call the JavaScript function callDelicious whenever the end user clicks the submit button. Instead of going through the page request loop of a web browser, I’m using the GUI-like event loop of a JavaScript program.

The callDelicious function uses the JavaScript library XMLHttpRequest to fetch data from This is the URI used throughout Chapter 2 to fetch a user’s most recent bookmarks. First we need to do some housekeeping: get permission from the browser to send the request, and gather whatever data the user entered into the HTML form (see Example 11-3).

Example 11-3. Ajax client continued: definition of callDelicious

   function callDelicious() { // Get permission from the browser to send the request. 
     try {
       if ("UniversalBrowserRead");
     } catch (e) { 
       alert("Sorry, browser security settings won't let this program run."); 

     // Fetch the user-entered account information 
     var username = document.getElementById("username").value; 
     var password = document.getElementById("password").value;

     // Remove any old links from the list. 
     var links = document.getElementById("links"); 
     while (links.firstChild) 
     setMessage("Please wait...");

Now we’re ready to send the HTTP request, as shown in Example 11-4.

Example 11-4. callDelicious definition continued

     // Send the request. 
     // See "Working Around the Corner Cases" for a cross-browser 
     // "createXMLHttpRequest" implementation. 
     request = new XMLHttpRequest();"GET", "", true, 
                  username, password);
     request.onreadystatechange = populateLinkList; 

The third JavaScript function I’ll define is populateLinkList. I’ve already referenced this function, in the line request.onreadystatechange = populateLinkList. That line sets up populateLinkList as a callback function. The idea is that while is processing the request, the user can go about her business, surfing the web in another browser window. Once the request completes, the browser calls populateLinkList, which handles the response. You can do JavaScript programming without these callback functions, but it’s a bad idea. Without callbacks, the web browser will go nonresponsive while the XMLHttpRequest object is making an HTTP request. Not very asynchronous.

The job of populateLinkList is to parse the XML document from the web service. The representation in Example 11-5 represents a list of bookmarks, and populateLinkList turns each bookmark into a list item of the formerly empty ul list tag.

Example 11-5. Ajax client concluded: definition of populateLinkList

     // Called when the HTTP request has completed. 
     function populateLinkList() { 
       if (request.readyState != 4) // Request has not yet completed

      setMessage("Request complete."); 
      if ("UniversalBrowserRead");
      // Find the "post" tags in the representation
      posts = request.responseXML.getElementsByTagName("post");

      setMessage(posts.length + " link(s) found:"); 
      // For every "post" tag in the XML document...
      for (var i = 0; i < posts.length; i++) { 
        post = posts[i]; 
        // ...create a link that links to the appropriate URI.
        var link = document.createElement("a"); 
        var description = post.getAttribute('description'); 
        link.setAttribute("href", post.getAttribute('href'));

        // Stick the link in an "li" tag...
        var listItem = document.createElement("li");
        // ...and make the "li" tag a child of the "ul" tag.
        listItem.appendChild(link); links.appendChild(listItem)

The best content for your career. Discover unlimited learning on demand for around $1/day.