Resources, Not Data


Summary

We need to stop trying to understand REST in terms of data-centric programming paradigms. The result will be better-designed APIs.

Rest Area?

You'll often hear people explain the mainstay HTTP verbs, GET, POST, PUT, and DELETE, in terms of the venerable CRUD (create, retrieve, update, and delete) functions of persistent storage systems. Heck, I do it myself. We need to stop.

In a RESTful API, the HTTP verbs are roughly analogous to the CRUD functions, but what they're acting on is quite different. CRUD functions act on data...static, stupid data. In REST, on the other hand, the verbs act on resources. While there are cases where a resource is just static data, that case is much less interesting than the general case.

To see how, let's pull out the old standby bank account example. In this example, I have a resource called /accounts and in a CRUD world, you could imagine deposits and withdrawals to an account with identifier :id being PUTs on the /accounts/:id resource.

Of course, we'd never expose an API where you could update an account balance with a PUT. In fact, I can't imagine anything you'd do with the account balance in such an API except GET it. There are too many necessary checks and balances (what we call "model invariants") that need to be maintained by the system.

Instead, what we'd do is design an account transfer resource. When we wanted to transfer $100.00 from /accounts/A to /accounts/B, we'd do this:

POST /transfers

{
  source: /accounts/A,
  destination: /accounts/B,
  amount: 100.00
}

This creates a new transfers resource and while it's true that data will be recorded to establish that a new transfer was created, that's not why we're doing it. We're doing it to effect the transfer of money between two accounts. Underneath this resource creation is a whole host of processes to maintain the transactional integrity and consistency of the bank's books.

Interesting resources have workflow rather than just being a collection of data. So stop focusing on the HTTP verbs and think about the resources instead. REST is resource-oriented and that doesn't just nicely map to objects, relational databases, and remote procedure calls. Most bad APIs are a result of this mistaken attempt to understand it in terms of old programming paradigms.


Please leave comments using the Hypothes.is sidebar.

Last modified: Thu Oct 10 12:47:18 2019.