Rails: Building a Ruby on Rails API-only app

Rails 5 is out and API-only apps appear to now be first class citizens. I'm 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 quickly 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. Still, 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 only versions greater than 2.5.x are currently supported.

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.6.0

Add this to ~/.bash_profile.

eval "$(rbenv init -)"

Flush rbenv

rbenv rehash

Switch to Ruby 2.x.x

rbenv global 2.6.0

Update gem before you install rails

gem update --system

Using this precise version of Ruby, install this precise version of Rails and skip the documentation.

RBENV_VERSION=2.6.0 rbenv exec gem install rails --version 5.2.3 --no-document

Step 2 - Create a new app

Create a new rails API-only app with rails 5.2.x and Postgres. Here is a list of available versions.

RBENV_VERSION=2.6.0 rbenv exec rails _5.2.3_ 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 set a few gems to get things working correctly.

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. It's the secret sauce to Rails API development. Through AMS, the Rails community is mostly 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 unnecessary stuff, but you'll need to manually enable CORS so that your app or another 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 APIs, 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 significant 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 the 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 includes 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 executed when your apps start.

rails initializers

Update command is useful if you're merging code.

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 researching other frameworks that can help you build API-only apps, I suggest reviewing: