Using Rails as your API(Application Programming Interface) is a very popular choice. Rails provides a set of defaults that allows developers to get their app up and running quickly. To get started, run the following command:
rails new my_api --api -T
This will generate a new project. The API argument tells Rails that we are building an API application. The -T removes the default testing framework if you want to add a different one such as RSpec.
In order to make cross-origin AJAX calls possible, we need to uncomment the following gem in the GemFile.
#Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
gem ‘rack-cors’, :require => ‘rack/cors’
We also need to uncomment the following code in the config/initializers/Cors.rb file. Origins can be specified as a string, a regular expression, or as ‘*’ to allow all origins. The same goes for the resource path.
Lets start by making a User Model. We’ve included the model attributes in the model generation command. This way we don’t have to edit the migration file.
rails g model User username:string password:string
After the models have been generated we can go ahead and run:
Which will create the following schema.
Rails is a perfect framework for building websites, and it is designed keeping the best programming practices in mind. It is wonderful to use as an API, but it doesn’t render very nicely. To render Rails in a prettier way, it is best to use a serializer such as Active Model Serializer, which is especially useful when you only want to display certain attributes. Add the following gem and run bundle install.
This gem will give to the ability to add a serializer to each model.
rails g serializer user
Using a serializer gives you the ability to customize which attributes you want displayed. It also gives you the ability to add relationships directly in the serializer class.
Now its time to set up the controllers. The problem is that people using your API expect certain results to stay constant and that’s not always possible with updates. So to keep it that way we need to add versioning!
rails g controller api/v1/Users
Time to build out the actions.
Now since we versioned our controller, we need to namespace the routes so that we have access to them.
The last thing to do is seed some test data to see if the API displays the data properly.
oliver = User.create( username: ‘Oliver’, password: ‘password’ )
Which should display the following: