DEV Community

mzakzook
mzakzook

Posted on

Fast JSON & Rails

When designing a backend it is important to consider how data will be constructed when a response is being prepared for a client. As any given schema becomes more complex and intertwined, the data that you will want provided to your frontend will likely necessitate information on more than one object or class per fetch.

Active Model Serializer was released about six years ago and accomplished that specific goal for Ruby & Rails: combine multiple objects/classes in a JSON response to be used for your HTTP requests. Data serialization "is the process of translating data structures or object state into a format that can be stored" Serialization - Wikipedia. While this tool was widely used and did accomplish its goal, new players have entered Ruby's serialization scene and have proven that we've come a long way over the last six years.

Netflix released its Fast JSON API about two and a half years ago, and over that time it has proven to be much faster than Active Model Serializer. According to Netflix's docs, these are the results from benchmark times for 250 records:

$ rspec
Active Model Serializer serialized 250 records in 138.71 ms
Fast JSON API serialized 250 records in 3.01 ms

In addition to being very fast, it is extremely user-friendly. To set up Fast JSON API, simply add the gem to your Gemfile and bundle install:

gem 'fast_jsonapi'
$ bundle install

You're then ready to create your serializers. This can be done from the terminal with the command:

rails g serializer Model-Name attribute attribute attribute

Once your serializers are generated, the next step is to add the appropriate 'belongs_to' and 'has_many' relationships (any modifications you would make to your models without Fast JSON API would be the same with it).

Each serializer can now be called from your controller actions and you can pass it a single instance of a class or many at once. For example:

ModelSerializer.new(model_instance)

I am a big fan of Postman and like to check how my data is formatted there, but feel free to confirm layout is as you intended by performing any valid request to your backend.

Because Fast JSON API recognizes the 'belongs_to'/'has_many' relationships, you are able to see full picture relationships with one fetch. If I created a database of dog owners and dogs (where a dog could only have one owner), one fetch for a specific dog owner could include an array of each of her/his dogs (with all of their data).

Fast JSON API has definitely made my life easier when linking backends and frontends and I hope it does for you too!

Top comments (0)