Rails API with FastJSON from Netflix

Let’s build a simple Rails API and use Netflixes FastJSON library to serialize our JSON responses.

Photo by Tomas Anton Escobar on Unsplash

Project setup

First create a new rails project in api mode.

Then in the gem file add the gems:

Now run bundle install and rails db:create to create the database.

Preparing some data

Create a model called Location, we will use these records for serialization.

And run rails db:migrate to apply the changes to the database. Now we need some sample data. For that we will update db/seeds.rb. This is where Faker gem comes in handy.

Run rails db:seed so it populates the database.

Controllers

Api controller

We will introduce some helper methods to our API base controller. These helper methods will put pagination info when we have a collection of records for example.

Locations controller

With the help of the methods defined in application controller, our locations controller looks very simple.

Serializer

Creating a serializer is super easy. Just type:

and it will create a location_serializer.rb file in app/serializers folder.

That’s it

Don’t forget to update your routes.rb

Now run the server. Path /locations should now display a list of location data together with pagination data and all serialized with FastJSON.

developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store