Let’s build a simple Rails API and use Netflixes FastJSON library to serialize our JSON responses.
First create a new rails project in api mode.
rails new fjsonrail --api --skip-tests -d mysql
Then in the gem file add the gems:
gem 'faker', '~> 1.9', '>= 1.9.3'
gem 'kaminari', '~> 0.17.0'
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.
rails g model Location name
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.
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.
With the help of the methods defined in application controller, our locations controller looks very simple.
Creating a serializer is super easy. Just type:
rails g serializer Location name
and it will create a location_serializer.rb file in app/serializers folder.
Don’t forget to update your routes.rb
resources :locations, only: [:index, :show]
Now run the server. Path /locations should now display a list of location data together with pagination data and all serialized with FastJSON.