Serializers

Serializers are used to format business data into JSON entities. In our Rails applications, we use them to send data to the front-end. They are usually called by controllers. Every serializer is related to a specific model.

In our applications, we usually have two APIs: one is public, the other is private.

The public API, as its name states, is to allow developers from other companies to have a restricted access to our backend. This API uses the ActiveRecord Serializer gem to serialize data.

The private API is used exclusively by our front-end and our extensions. For this API, we use a gem called fast_jsonapi. This gem is more efficient and presents the data differently (still on a JSON though).

Check out this link if you want more informations about it: https://github.com/Netflix/fast_jsonapi

Private API

As we said before, every serializer is related to a model class. For example, our User model will have a corresponding UserSerializer. Let's see how this works for our private API.

Each custom serializer inherits our custom parent class ApplicationSerializer, which include the FastJsonapi::ObjectSerializer.

In the serializer, you will put every attribute you want to transmit to the front-end, and you can even add some custom attributes. Let's see that with an example:

module Api
  module Private
    class UserSerializer < Api::Private::ApplicationSerializer
      belongs_to :company
      attributes :email, :first_name

      attribute :does_he_make_movies do |obj|
        obj.name == 'Tarantino' ? true : false
      end
    end
  end
end

First, we mention the relation to the company. If we don't, it won't be serialized.

Then, we decide which attribute we want to send to the front-end. In this case, we decided not to include the :last_name for privacy matters. This means that the front-end will only receive the :email and the :first_name.

Finally, we added a custom attributes called :does_he_make_movies which is a boolean. To determine the value of this attribute, we implemented a block where obj is the model instance. We then check if its name is Tarantino to determine if he makes movies or not. This attribute doesn't exist on the model class, but it will be serialized to the front-end because we declared it in the serializer. Stanley Kubrick could argue that it is kind of stupid, but you get the picture.

Last updated