Serialize with Fast_jsonapi

Clark Johnson
2 min readApr 27, 2020

--

So you’ve created a great API using Ruby on Rails, and now its time to prepare the data object (probably a hash) to be consumed by your frontend. Your frontend expects JSON, and that means the data has to be converted to a string, or serialized. The render method has a json: option to handle this easily.

Render with to_json

If we’re working with a User model, maybe the show method of the users_controller.rb has a line that looks like this:

render json: @user.to_json(only: [:id, :email, :name, :registered_at], methods: :average_rating)

Here’s what /users/1 will produce with sample a little included sample data:

{
"id": 1,
"email": "clovis@example.net",
"name": "John Justice Wheeler",
"registered_at": "2017-09-22T12:13:05.000Z",
"average_rating": 4
}

Render with fast_jsonapi

I recently discovered a set of specifications for building APIs in JSON, located at (you guessed it) https://jsonapi.org/. I decided to rely on a handy gem, fast_jsonapito help me satisfy this specification easily. It’s designed to be fast and get the job done easily. To make that happen, some flexibility is sacrificed.

Let’s add the gem to our project

gem "fast_jsonapi", "~> 1.5"

and install it.

bundle install

We’ll take advantage of a generator to create a boilerplate.

rails g serializer User id email name registered_at

This creates app/serializers/user_serializer.rb

class UserSerializer
include FastJsonapi::ObjectSerializer
attributes :id, :email, :name, :registered_at
end

Now we make use of this class in the controller and render the output.

render json: UserSerializer.new(@user).serializable_hash

Here’s the serialized output:

{
"data": {
"id": "1",
"type": "user",
"attributes": {
"id": 1,
"email": "clovis@example.net",
"name": "John Justice Wheeler",
"registered_at": "2017-09-22T12:13:05.000Z"
}
}
}

It should be noted that the Serializer can return either a hash

hash = UserSerializer.new(@user).serializable_hash

or serialized JSON

json_string = UserSerializer.new(@user).serialized_json

The fast_jsonapi does a great job of formatting Ruby hashes to conform with the JSON API specification. Of course, it may not be right for every situation, so be sure to keep your options open if your project requires a different format.

Happy coding!

--

--

Clark Johnson

Full stack software engineer seeking projects using React, Ruby on Rails, Javascript, when I’m not at a baseball game