//

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:

Create an App

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

rails new contacts_api –api

Tests

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:

bundle

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

CORS

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:

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]
      end
    end
 
  end
end

Throttling

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
 
  end
end

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 `Rack::Attack.cache.store` value
  Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
 
  # Allow all local traffic
  whitelist('allow-localhost') do |req|
    '127.0.0.1' == req.ip || '::1' == req.ip
  end
 
  # Allow an IP address to make 5 requests every 5 seconds
  throttle('req/ip', limit: 5, period: 5) do |req|
    req.ip
  end
 
  # Send the following response to throttled clients
  self.throttled_response = ->(env) {
    retry_after = (env['rack.attack.match_data'] || {})[:period]
    [
      429,
      {'Content-Type' => 'application/json', 'Retry-After' => retry_after.to_s},
      [{error: "Throttle limit reached. Retry later."}.to_json]
    ]
  }
end

Conclusion

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