Create a Rails 5 API Application

Rails 5 ships a new gem rails-api which makes building API only rails apps a breeze.

ActiveRecord is a part of Rails 5 along with a strong asset pipeline, making Rails a great option for creating APIs.

We start by settings up Rails 5.

Setting up Rails 5

Ruby 2.2.2+

Make sure you have Ruby 2.2.2 or above:

ruby -v

If you don’t have the required minimum version, this link will help you to get up to date – Mac install Ruby on Rails for Mac Windows – Rails Installer

Create an App

We need to pass the –api option at the time we create a new app.

rails new contacts_api –api


We are going to use RSpec for testing our API.

Add the following lines in your Gemfile, in the :development, :test area

# Use RSpec for specs
gem 'rspec-rails', '3.1.0'
# Use Factory Girl for generating random test data
gem 'factory_girl_rails'

Now change into the directory, and run following command:


Run the RSpec installer

bin/rails g rspec:install

Specs Not Tests

We will delete the test directory in Rails as we are writing specs instead of tests.

rm -rf test

Scaffolding API

We use the default scaffold geenerators to create API resources.

bin/rails g scaffold user name email

We can create resources just like this. Once you have done that, you can migrate and run the app.

bin/rake db:migrate

Our new API will be up and running on http://localhost:3000


When we are building public APIs, we ned enable Cross-Origin Resource Sharing(CORS).

In the Gemfile add rack-cors gem to enable this for us.

gem ‘rack-cors’

And now we can update the bundle:


To enable GET, POST, or OPTIONS requests from any origin on any source, we will add the code snippet below to config/application.rb

module ContactsApi
  class Application < Rails::Application

    # ...

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]



To stop DDos and brute force attacks we are going to use a Rahe middleware called Rack::Attack.

  gem 'rack-attack'

And update your bundle

gem ‘rack-attack’

And now update your config/application.rb

module ContactsApi
  class Application < Rails::Application

    # ...

    config.middleware.use Rack::Attack


To configure Rack::Attack rules, create a file in config/initializers/rack_attack.rb

class Rack::Attack

  # `Rack::Attack` is configured to use the `Rails.cache` value by default,
  # but you can override that by setting the `` value =

  # Allow all local traffic
  whitelist('allow-localhost') do |req|
    '' == req.ip || '::1' == req.ip

  # Allow an IP address to make 5 requests every 5 seconds
  throttle('req/ip', limit: 5, period: 5) do |req|

  # Send the following response to throttled clients
  self.throttled_response = ->(env) {
    retry_after = (env['rack.attack.match_data'] || {})[:period]
      {'Content-Type' => 'application/json', 'Retry-After' => retry_after.to_s},
      [{error: "Throttle limit reached. Retry later."}.to_json]


This guide will help you kick start your first Rails 5 API application.

Be first to comment

Leave a Reply