In BlogPost, Rails, Ruby

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:

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

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.

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.

Step 4 – Add an offer model

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

Step 5 – Add a user model

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

Step 6 – setup clearance with the user model

I also used the clearance gem for authentication.

In your Gemfile add:

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

Step 7 – Create a factor model with the following schema

Step 8 – Organize your routes.rb file

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

Summary

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

Recent Posts