Building a Simple Rails API with Active Model Serializers

BharteeTechRubyOnRails
2 min readNov 7, 2023

--

In this post, we’ll guide you through setting up a basic Rails API and using Active Model Serializers to format JSON responses. This setup will allow you to create and retrieve posts, showcasing how to serialize your data for the API.

Step 1: Creating the Rails API

Let’s start by creating a new Rails API application:

rails new serialized_attributes_002 --api
cd serialized_attributes_002

Step 2: Adding Active Model Serializers

We’ll be using the `active_model_serializers` gem, so add it to your Gemfile:

gem 'active_model_serializers'

Run `bundle install` to install the gem.

Step 3: Generating the Post Model and Controller

Create a `Post` model and a controller for your API:

rails g model Post title content:text subtitle status
rails g controller api/v1/Posts index new show

Step 4: Database Setup

Let’s create the database and run migrations:

rails db:create && rails db:migrate

Step 5: Generating a Serializer

Generate a serializer for the `Post` model:

rails g serializer Post

Define the attributes you want to include in the JSON response in the generated serializer. For example:

# app/serializers/post_serializer.rb
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :content
end

Step 6: Implementing the API Controller

In your API controller, implement actions for listing, creating, and showing posts. Here’s an example of how you can structure the `Api::V1::PostsController`:

# app/controllers/api/v1/posts_controller.rb
class Api::V1::PostsController < ApplicationController
def index
@posts = Post.all
render json: @posts, each_serializer: PostSerializer
end

def create
@post = Post.create(title: params[:title], subtitle: params[:subtitle], status: params[:status], content: params[:content])
if @post.save
render json: @post.as_json, status: :created
else
render json: @post.errors, status: :unprocessable_entity
end
end

def show
@post = Post.find_by(id: params[:id])
if @post.present?
render json: @post, serializer: PostSerializer
else
render json: @post.as_json, status: :not_found
end
end
end

`each_serializer` is used when serializing a collection of objects, and it sets the serializer for each individual item in the collection,

while `serializer` is used when serializing a single object and sets the serializer for that specific object. These options provide flexibility in choosing different serializers for different scenarios within your Rails application.

In this blog, you’ve learned how to set up a basic Rails API and employ Active Model Serializers to customize the JSON responses. You’re now equipped to create, list, and show posts via your API.

Happy Active Model Serializer Gem in Ruby on Rails! 🚀 Please follow for more updates

BharteeSahareTechRoR

--

--