Chris Mendez in For Developers, Ruby

Rails: Building a RoR 5 API-only app

Rails 5 is finally out and API-only apps appear to now be first class citizens. I'm also excited to see Rails remain relevant in a world of single-page apps (through Turbolinks) and real-time protocols (through Actioncable).

I also appreciate companies like Heroku for creating guides to help you easily deploy your Rails 5 app online. It helps keep us developers focused on the task at hand; building great apps.

Why Rails for API Development?

Many people will argue that Rails is too big of a framework for a simple API but oftentimes, a simple API ends up requiring different dev environments, simplified routing, CRUD generation, authentication, etc. so you're back to square one. The bottom line here is pretty simple, if you know Rails, then rest assured that many hardworking people took it upon themselves to keep your workflow running smoothly.

As for me, there are times when I use rails and times when I prefer NodeJS. The deciding factor for me is ultimately maintenance. If I can't maintain this app, who will and what is their skill set?


Getting Started

Rails 5 requires Ruby 2.2.2 (or above) but I prefer 2.3.1 because there are improvements with performance and memory management. Also, Heroku supports 2.3.1 so and I often try to keep up with the times.

I also suggest installing JSON Formatter for Google Chrome. It will help with JSON readability.

Step 1 - Updating Ruby & Rails

The easiest way to manage different versions of Ruby is to use a version manager such as rbenv or RVM.

Install Ruby using rbenv

rbenv install 2.3.1  

Flush rbenv

rbenv rehash  

Switch to Ruby 2.x.x

rbenv global 2.3.1  

Update gem before you install rails

gem update --system  

Install rails quickly by skipping the documentation

gem install rails --version 5.0 --no-ri --no-rdoc  

Step 2 - Create a new app

Create a new rails api-only app with rails 5.0 and Postgres. Here is a list of available versions.

rails _5.0.0_ new my_api_app --api -d postgresql  

Rails command line options

  • Use -c to skip ActionCable
  • Use -m to skip ActionMailer
  • Use -O to skip ActiveRecord
  • Use -T to skip Unit Testing
  • Use -d to choose a specific database
  • rails help for more commands

Then run bundle update

cd my_api_app  
bundle update  

Create the database (and anything else you need to do).

rails db:create  

Step 3 - Install gems

Even though you've told rails to configure your app for API development, you'll need to configure a few gems to get things working properly.

ACTIVE MODEL SERIALIZERS

Serialization gems are not included in the default Gemfile, so you must first add the Active Model Serializers manually.

If you're not familiar with AMS, it's the tool used to serialize Active Model objects. This is sort of like the secret sauce to Rails API development. Through AMS, the Rails community is essentially trying to standardize JSON API responses.

Add this to Gemfile

gem 'active_model_serializers'  

Then add this initializer by creating the file config/initializers/active_model_serializers.rb

ActiveModel::Serializer.config.adapter = :json_api  

CORS

The --api attribute you used above helps rails strip out all the unecessary stuff but you'll need to manually enable CORS so that your app or other server can make data requests.

gem 'rack-cors' #Enable CORS  

PAGINATION

If you're familiar with will_paginate or some oner pagination tool, kaminari is great for API-type pagination.

Serialization  
gem 'kaminari' #Pagination  

Install gem

bundle install  

Note: Cookies, sessions, and flash messages are not required for API's but you can always go back and add them to config/application.rb.

config.middleware.use ActionDispatch::Cookies  

Step 4 - Business as Usual

Everything else should pretty much work as expected. The only major changes you might notice are the lack of: app/assets, app/helpers, and app/views.

Start Server

rails s  

Scaffold

Scaffold is a great way to get started. It will help you create the necessary models and controllers as well as te serializers you'll be using in replacement of views.

# rails g scaffold [model] [controller] fname:string lname:string email:string

Models

They're pretty much the same.

# rails g model [model_name] [attribute:type] [attr2:type]

rails g model composer fname:string lname:string dob:date dod:date nationality:string birth_city:string biography:string image_uri:string  

Controllers

# rails g controller [controller_name] [action1] [action2]

rails g controller facts age  

Other Tips

Goodbye rake

We no longer use rake for migrations. Instead we keep things simple by using rails.

rails db:migrate  
rails assets:precompile  
rails test  

New Commands

Rails has a few new commands including

Quickly enable or disable the cache while in development.

rails dev:cache  

Initializers lists the set of initializers that are run when your apps starts.

rails initializers  

Update command is useful if you'll pulled someone elses code into your source.

bin/update  

Devise Users

If you use Devise, you can update the gem for Rails 5 by adding this to our Gemfile.

gem 'devise', git: 'https://github.com/plataformatec/devise.git'  

Then run this command.

bundle update devise  

If you'd prefer to install rbenv locally, check out this stackoverflow thread.


Troubleshooting

If you think you've messed up your gem you can always uninstall your way out of the problem.

for i in 'gem list --no-versions'; do gem uninstall -aIx $i; done  

Other Alternatives

If you're doing research on other frameworks that can help you built API-only apps, I suggest you look into: