A Rails API Example With Grape and Airborne

August 01, 2017

A Rails API Example With Grape and Airborne

This post is meant to serve as a light introduction to a Rails API example usin g Grape and Airborne.

API Learning Design

Grape is a ruby gem to help you create REST-like APIs in Ruby.

Airborne

Step 1 – Install Grape and Airborne

First, install the appropriate gems. You don't need grape_on_rails_routes but I like it because it gives you a handy rake task to let you see what your API routes look like.

grape-entity is useful for helping you more easily construct a JSON response from your API.

Here are the relevant gems:

gem 'grape'
gem 'grape_on_rails_routes' # rake task to expose grape api routes
gem 'grape-entity'

group :test do
  gem 'airborne'
end

In config/airborne.rb, set it up as follows:

Airborne.configure do |config|
  config.rack_app = API
end

The great thing about the airborne setup is that it enables you to test your API application without having the server running.

Step 2- Organize your API setup

Create an app/api/job_offer directory and create a job_offer.rb file inside.

module JobOffer
  class V1 < Grape::API
    version 'v1'
    format :json
    desc 'System for tracking job offers'

    namespace :users do
      get '/' do
        users = User.all
      end

      desc "Retrieve a user's offers w/factors"
      params do
        requires :id, type: Integer, desc: 'user id'
        requires :offer_id, type: Integer, desc: 'offer id'
      end


      get ':id/offers/:offer_id/factors' do
        user = User.find(params[:id])
        offer = user.offers.find_by(id: params[:offer_id])
        factors = offer.factors
      end
    end
  end
end

Step 3 - Add a Factor model with the following schema

The below schema is generated using the annotate gem.

It’s really a reflection of what is found in your schema.rb file in a Rails application, but it sits at the top your model file.

You can generate a Factor model below using a rails migration.

# == Schema Information
#
# Table name: factors
#
#  id          :integer          not null, primary key
#  name        :string
#  value       :decimal(, )
#  repeat_type :string
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#  offer_id    :integer
#

Step 4 - Add an offer model

You can generate an Offer model below using a rails migration.

# == Schema Information
#
# Table name: offers
#
#  id             :integer          not null, primary key
#  name           :string
#  active         :boolean
#  ongoing_total  :decimal(, )
#  one_time_total :decimal(, )
#  created_at     :datetime         not null
#  updated_at     :datetime         not null
#  user_id        :integer
#

Step 5 - Add a user model

You can generate a User model below using a rails migration.

# == Schema Information
#
# Table name: users
#
#  id                 :integer          not null, primary key
#  first_name         :string
#  last_name          :string
#  email              :string
#  created_at         :datetime         not null
#  updated_at         :datetime         not null
#  encrypted_password :string(128)
#  confirmation_token :string(128)
#  remember_token     :string(128)
#

Step 6 - setup clearance with the user model

I also used the clearance gem for authentication.

In your Gemfile add:

gem "clearance"

Then run the following generator task (assuming you already setup a User model).

$ rails generate clearance:install

Step 7 - Create a factor model with the following schema

# == Schema Information
#
# Table name: factors
#
#  id          :integer          not null, primary key
#  name        :string
#  value       :decimal(, )
#  repeat_type :string
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#  offer_id    :integer
#

Step 8 - Organize your routes.rb file

Rails.application.routes.draw do
# routes file shortened for clarity

mount API => '/'

Step 9 - Add the following to config/application.rb

# config/application.rb

#for grape
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

Summary

Setting up a Rails API with Grape is pretty straightforward. In the future, I plan to have a GitHub repository.


Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.