When building a RESTful API in Rails application, there are many different options and gems you can use to format your JSON responses. This isn’t a post about how to build an API, but rather about some of the different popular options on how to define and structure JSON.
RABL is a DSL for generating both JSON and XML. In my mind it has a similar feel to Jbuilder, which I’ll discuss below. It’s works by creating a view with the extension .rabl, and defining which attributes, nodes, and relations you wish to include in the JSON response.
Here’s an example:
1 2 3 4
Active Model Serializer
Active Model Serializer is a great way to build JSON responses using an object oriented approach. The objects have a very similar feel to how your ActiveModel object is set up in terms of attributes and relationships. It also allows you to choose your adapter-to decide what type of JSON structure is produced-or to build your own. Popular supported formats are JSON-API and JSON-HAL.
1 2 3 4 5
jbuilder provides a very similar DSL to RABL. Jbuilder is included with Rails, so it is used quite a bit. Rails Casts has a free episode which goes into greater detail about Jbuilder. It’s very easy to use and provides a lot of flexibility in defining exactly what attributes are included in and how the response is formatted and nested.
1 2 3 4 5 6 7 8
Grape Entity was extracted from Grape, which is a popular gem used for building RESTful APIs. Similarly to RABL and Jbuilder, it provides a DSL for defining entities which are the structure of your JSON response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
ROAR allows you to build presenter classes to represent your data. It comes with support for JSON, JSON-HAL, JSON-API, and XML.
1 2 3 4 5 6
ActiveModel or Hash
This may seem like a strange thing to point out, but for very simple cases, you can simply call the to_json method on either an ActiveModel object or a native Ruby Hash.
1 2 3 4 5 6
1 2 3 4 5 6 7 8 9
So far so good, That’s it!!! See ya!!! :)