Tuesday, July 23, 2013

Symmetry in REST Considered Harmful

When building web applications, it is often tempting to look for symmetry in the APIs for the creation and the retrieval of data. We are also nudged in that direction by the popularity of REST and its emphasis on treating data as resources. And by ORMs that encourage a single representation of an entity (the model) for CRUD operations.

Don't be tricked. That symmetry may exist on desktop (or device) applications where APIs are local, but isn't truly there for web applications. Give it up.

We are better off building APIs that are tailored to the specific act being performed. This goes back to the practice of making remote APIs coarse-grained (minimize chattiness, messages are expensive because of latency) and local APIs fine-grained (messages are cheap).

When we create/update entities, we need one representation that contains attributes (strings/numbers/etc) and references to other entities (ids). On the other hand, retrieval usually involves offering different shapes depending on what the needs of the client are (rendering a list, a show page), and responses usually embed a lot more data about related entities to prevent extra queries later (eager-fetching).

Naive ORMs that map tables to models are unsuitable for the task of serving data this way. We need tools that let you map data from the DB to the response in an more ad hoc way.

I see this capability in libraries like Anorm (even it has other issues), Play JSON (json-coast-to-coast), subset (mongodb library), etc. This was one of the guiding principles behind scoop (sql toolkit) and dynasty (dynamodb toolkit). Incidentally, a lot of it is powered by the concept of typeclasses.

No comments:

Post a Comment