Using RABL in Rails JSON Web API
Let’s use an event management app as the example.
The app has a simple feature: a user can add some events, then invite other users to attend the event. Its data are represented in 3 models: User, Event, and Event Guest.
Let say, we are going to add a read-only JSON web API for clients to browse data records from the app.
Problems
Model is not view
When working on a non-trivial web API, you will soon realize that, model often cannot be serialized directly in web API.
Within the same app, one API may need to render a summary view of the model, while another needs a detail view of the same model. You want to serialize a view or view object, not a model.
RABL (Ruby API Builder Language) gem is designed for this purpose.
Define once, reuse everywhere
Let say, we need to render these user attributes: id
, username
, email
, display_name
, except password
.
In RABL, we can define the attribute whitelist in a RABL template.
To show individual user, we can now reuse the template through RABL extends
.
Here’s another example to show a list of users.
The template can be reused in nested child as well, through RABL child
.
Join table rendered as subclass
I notice a recurring pattern in two recent projects. For instance, in this example, from client’s point of view, Event Guest is basically a User with an additional attribute: RSVP status.
When query database, usually we need to query the join table: event_guests
.
But when rendering, the result set needs to be rendered as a list of Users. RABL allows you to do that easily, using its glue
feature (a weird name though :).
I think I will use RABL for the next Rails web API project.
The complete Rails example code is available at github.com/teohm/tryrabl.