Quick and dirty intro to REST within HTTP

RESTful web design in terms of the HTTP protocol breaks down quite simply. It all boils down to how the URI is formed. Many systems handle this in different ways on the server, but it's simply about following the basic URI pattern:

(action) http://(host)/(resource(s))
Request Body: (description)

Action: Verb based CRUD, where GET is Retrieve, POST is create, PUT is update and DELETE is delete.
Resource: Noun based object. Usually found in value pairs (object/id) when not creating a new resource.
Description: POST and PUT have request bodies. This should describe details about what you want the object to have, or what you want to change.

Several examples of each type of action:

  • GET http://host.com/book/123abc789
  • POST http://host.com/book
    Request Body: {book: {name: "the super duper", contents: "once upon a midnight dreary..."}}
  • DELETE http://host.com/book/987bca123
  • PUT http://host.com/book/123abc789
    Request Body: {book: {name: "new super"}}

Here are a couple examples of nested objects, where a shelf has rows, and a row has books:

  • GET http://host.com/shelf/23a/row/5/book/21
  • DELETE http://host.com/shelf23a/row/4

It becomes pretty darn obvious exactly what you're doing when you look at URIs in this manner. The retrieved representation should have some kind of default, but you also should be able to specify a particular representation (if it makes sense for your implementation). For example:

  • GET http://host.com/shelf/23a/row/5/book/21.pdf
  • GET http://host.com/shelf/23a/row/5/book/21.html

Common REST pitfalls:

  • REST does not support any kind of API listing, so it needs to be published clearly somewhere for people to use.
  • You may not update more than one resource/object at a time, with one call to the server.

While this is a very basic primer, if you follow these rules on both client and server, and you should fall successfully in to the pit of resource oriented architecture. Don't be afraid to just try it out. It's a new way of organizing all of your URIs, and you're bound to have to try things a few different ways before finding the most optimized pattern. Everything else in REST terms is just expanding on the concepts introduced here, either on server code or client code.

No comments:

Post a Comment