Introduction to Active Model Serializers for Configuring Custom API Responses in Rails

Feature thumb snip20170911 1

If you want to build out an API in Rails, at some point you will need to configure what the responses will look like to the 3rd party services connecting to the API (mobile applications, other sites, etc). There are a number of options for setting this up in Rails, but my favorite is Active Model Serializer (AMS). I used AMS to build out the API for DailySmarty and this guide will provide an introduction for how you can use it in your own APIs.

Step 1: Install the Gem and Set it Up

In the resource section of this guide I've provided a link to the Gem that you can add to your Gemfile, such as:

After running bundle install we can add the initializer. Create a new file at the path: config/initializers/active_model_serializer.rb and add the following code to the file:

This will let the application know that we want to use Active Model Serializer to craft the JSON responses instead of the default setup (which simply shows all of the data).

Step 2: Build the Serializer

Next, create a new directory called 'serializers' in the app directory. For this guide we're going to use a model, called Recommendation, so the serializer file needs to be called: app/serializers/recommendation_serializer.rb. And I've placed the following code into it:

Step 3: Build the Serializer

With this in place, we're ready to update the controller and it will now only use the attributes from inside the serializer instead of all of the columns. So in this case it's going to ignore the created_at and updated_at columns, however this can be customized based on your application requirements. The controller call will look like this:

Now if we go to localhost:3000/recommendations in the browser, it will render our data based on the serializer configuration, as shown here:

Next Steps

This was a basic introduction for how to install and configure Active Model Serializer. If building APIs is a skill you want to learn, I highly recommend you go through the gem's documentation to learn about its more advanced capabilities, such as: nesting, working with custom attributes and methods, etc.