Tales From The World Of Java Development And Security

REST: What It Is (and What It Isn’t!)

REST (Representational State Transfer) has been bandied around as a term for a long time when it comes to API design, and it’s not hard to see the attraction. It relies on the pre-existing HTTP protocol, which is pretty much what the web already runs on, and if implemented well it can make use of a lot of features of HTTP (such as caching). This is a huge boon to application developers, saving them having to learn/implement a new technology/protocol and implement these features themselves.

However, it is quite common to see REST used to describe any web API that uses HTTP, whether it actually is REST or just some way to invoke methods remotely over HTTP. To use the ever-present coffee-shop example, you could have a method in your API to create a coffee:

GET https://kellykoffee.com/createcoffee?type='latte'&extrashot='hellyeah'

This would invoke some logic on the server side, and five minutes later I get my coffee (via…drone, I guess?).

And there’s nothing wrong with this, this is a perfectly acceptable way to implement this interface and invoke that logic. But it’s not REST.

REST is about invoking business logic via creating and manipulating object-documents, using the core HTTP methods: POST, GET, PUT, DELETE and HEAD. In the above example, however, we are specifying our own server specific method and sending parameters rather than an object definition, a kind of ‘RPC via HTTP’.

So to contrast, a REST based order would look something more like this:

Notice that there is no query string, and that the low level order data object-document is created as part of the request. This object is the key driver behind everything; if the order is cancelled, we would simply DELETE the order object; if it was amended, we would PUT the new version of the order on the server; if it is fulfilled, we could PUT an empty version of the JSON. The key here is that we are only utilising HTTP methods, whereas with the ‘RPC’ way we are invoking application specific methods.

So why would you do this? What advantage would this give you over the other, ‘RPC over HTTP’ way? That’s a topic I’ll follow up on with another post, and there are pluses and minuses for both approaches. In the meantime, here’s a question. Suppose we had a non-RESTful API method to retrieve the order, like this:

GET https://kellykoffee.com/createcoffee?orderId=12345

How easy would the object representing the order be to cached (let’s just imagine that caching and network performance is an issue in this setup.)? Also, what other advantages would having an API that relies on the primary HTTP methods give you? Particularly in a highly fluid, rapidly developing environment with many clients, teams and components constantly in flux?