REST

You’ve heard of REST APIs. What are they? What is REST?

Definition

REST, or Representational State Transfer, is an architectural style for distributed systems defining certain constraints that provide efficiency, scalabilty, and other desirable attributes.

REST was introduced by Roy Fielding. The constraints he identified were:

REST is an architectural style, NOT a product, NOT an API.

The World Wide Web is an example of a RESTful system.

Principles of REST

A RESTful system is characterized by seven principles.

  1. Addressable Resources
    • Every resource has a (unique) identifier (e.g., a URI)
    • Resources are generally nouns, so name your resources accordingly:
      • Example: http://www.yourcompany.com/products/2443
      • Non-example: http://www.yourcompany.com/getProduct?id=2443
    • Resources are separate from their representations
  2. Representation-Orientation
    • Requests for resources return representations
    • The representation contains the state of the resource
    • The client can update or delete resources through their representations
  3. Uniform, Constrained Interface
    • Small, fixed number of verbs
    • Example: HTTP has GET, PUT, POST, PATCH, DELETE, HEAD, OPTIONS, TRACE
    • Non-example: Any RPC-based protocol such as SOAP or CORBA
  4. Self-Descriptive Messages
    • Messages include all the information necessary to be processed
    • Example: Internet Media Types
  5. Stateless Server
    • With no shared context on the server, client requests are independent
    • Servers can be simpler, multithreaded, easier to monitor, reliable, scalable, etc.
  6. Cacheability
    • Responses indicate whether the client can cache the data or not
    • Reduces network traffic if the client knows it doesn't have to ask for the same data again
  7. HATEOAS
    • Hypermedia as the engine of application state
    • Representations should include links to related resources
    • Reduces the need for versioning by making most resources discoverable only from other resources

Writing RESTful Web Services

Hopefully you will get the chance to write a REST API yourself!

Here are four guidelines that can help you do a good job.

1. Think RESTfully

Remember when OOP was new? You had to shift your thinking from procedures to objects (from verbs to nouns): QueryOptimizer, ImageMapper, SiteInitializer, StringTokenizer, Enumerator, StreamReader, StreamWriter, Factory. Transitioning from RPC to REST is the same thing!

So ask yourself the question:

What are my resources?

Example answers: products, campaigns, customers, listings, profiles, lists, reviews, ads.

Resources do not have to be finely-grained. They do not have to correspond exactly to database tables.

Finally, you will have do deal with limited number of verbs. Hpw do you map your actions to these verbs?

2. Understand RESTful and non-RESTful URIs

Think in terms of nouns. It’s that simple.

RESTful:

  http://example.com/profiles
  http://example.com/profiles?what=pizza&where=90069&page=4&rpp=20
  http://example.com/profiles/2734
  http://example.com//twitter-handles/jp
  http://example.com/providers/2345/budgets/4567

Non-RESTful:

  http://example.com/order-system?op=deleteCustomer&id=2
  http://example.com/find-events?where=90069&after=2010-05-20
  http://example.com/api/products/update?id=3&name=mouse

3. Use a Framework

If you are writing a webapp back-end, you most certainly are using some kind of server-side product like Node for JavaScript, Flask for Python, Spring for Java, Rails for Ruby, or plain old PHP. Many of these products have a mechanism for making REST APIs easily. For Java, you can use a JAX-RS implementation such as Jersey or RestEasy.

4. Use HTTP Methods RESTfully

Let’s learn with an example.

RequestMeaning
GET /thingsGet all, or some of, the things. Use query parameters to restrict the set (i.e., do a search!), or to paginate.
PUT /thingsReplace the set of all things. Put entire set in payload.
POST /thingsCreate a new thing. Server sets id. Put representation of new thing in payload.
DELETE /thingsDelete all of the things.
GET /things/8Get thing 8.
PUT /things/8Replace thing 8 with new thing, but id stays 8. Put representation in payload. Or create a new thing with id 8.
PATCH /things/8Edit a part of thing 8. Payload can have a description of what to change, or maybe just the fields needing changing.
DELETE /things/8Delete thing 8.

You can implement OPTIONS yourself, too. HEAD will pretty much be handled by a framework.

Respect method constraints:

5. Know Your HTTP Request Headers

Request headers further refine the request. See Wikipedia’s list of headers for more information.

6. Know Your HTTP Responses

Use response codes as they were intended to be used. The ones you should be aware of (that is, that you may set yourself as part of your application) are:

CodeMeaning
400Bad Request
401Authorization Required
403Forbidden
404Not Found
405Method Not Allowed (service doesn't support the requested method at that URI)
406Not Acceptable (server can't give back a representation in a requested format)
415Unsupported Media Type (server can't process the request body)
200OK
201Created (usually you should set the Location header for this)
202Accepted (used for asynch requests)
204No Content
301Moved Permanently
409Conflict
410Gone

7. Know Your HTTP Response Headers

Response headers contain additional information about the response. See Wikipedia’s list of headers for more information.

Learning More

Start with these if you are new:

Ready for something more hardcore?

Here’s an old but good presentation:

How RESTful Is Your REST? from Abdelmonaim Remani

Recall Practice

Here are some questions useful for your spaced repetition learning. Many of the answers are not found on this page. Some will have popped up in lecture. Others will require you to do your own research.

  1. What does REST stand for?
    Representational State Transfer
  2. REST isn’t a programming language, nor an API, nor a library. What is the best way to describe it?
    An architectural style
  3. Who introduced the term REST and first described it?
    Roy Fielding
  4. What are the six constraints of REST identified Fielding?
    Client-Server, Stateless Server, Client Cache, Uniform Interface, Layered System, Code-on-Demand
  5. There are seven principles characterizing REST. Name five.
    Addressable Resources, Representation-Orientation, Uniform, Constrained Interface, Self-Descriptive Messages, Stateless Server, Cacheability, HATEOAS
  6. One of the characteristics of REST is the uniform, constrained interface. How is this manifested?
    A small, fixed number of verbs
  7. HTTP is RESTful. What are its verbs?
    GET, PUT, POST, PATCH, DELETE, HEAD, OPTIONS, TRACE
  8. Of the many aspects of REST that make it so scalable, which ones stand out?
    Stateless Server, Cacheability
  9. Why is HATEOAS so amazing?
    It reduces the need for versioning by making most resources discoverable only from other resources
  10. What is the primary thing to consider when determining addresses of resources?
    Think in terms of nouns
  11. What is the most conventional URI for getting employee number 8?
    GET /employees/8
  12. What URI would be used for adding a new employee whose id we did not know?
    POST /employees
  13. What is the most conventional URI for adding or updating employee number 8?
    PUT /employees/8
  14. What is the difference between the HTTP response codes 404 and 410?
    404 means the resource is not found, 410 means the resource is gone and will never be back

Summary

We’ve covered:

  • What REST is and is not
  • The architectural principles of REST
  • Things to know when writing a REST API