Create Grape API from scratch

  1. Create empty project
  2. Add grape gem
  3. Create base file
  4. Run application
  5. Get a response in a browser

First of all we should create empty directory and put it in it a file with ruby version and gemset name.

$ mkdir api
$ cd api
$ echo ‘ruby-2.4.1@api’ > .ruby-version$ cd .
$ cd .

# =>

After type cd . and press Enter we will see gemset name/version

Next step: Creating Gemfile

Go to http://bundler.io/ and see an instructions or just type in terminal:

$ gem install bundler --no-ri --no-rdoc # (add some "no" keys as we dont want to install additional documentation)

# =>

Install bundler and init new Gemfile file

Add to Gemfile gem ‘grape’

# gemfile
gem 'grape'

Now a quick bundle install will give us what we need to start coding.

$ bundle install

So our Gemfile looks like

source "https://rubygems.org"
gem 'grape'

and our app structure

~/repos/api$ ls -la
total 20
drwxrwxr-x 2 s s 4096 Sep 25 18:02 .
drwxrwxr-x 10 s s 4096 Sep 25 17:21 ..
-rw-r--r-- 1 s s 43 Sep 25 18:02 Gemfile
-rw-rw-r-- 1 s s 1139 Sep 25 16:40 Gemfile.lock
-rw-rw-r-- 1 s s 15 Sep 25 16:19 .ruby-version
~/repos/api$

Our application is going to look a bit like a Rails application with an app/ folder containing models/ and api/. It will basically look like this:

app/
api/
v1/
config/
application.rb
config.ru
Gemfile
Gemfile.lock

We need an entry point for our application. For this, we’re going to create a file named application.rb where we will require stuff, define the base Grape API object and tell Rack how to mount our application.

Note: This file is located at the root of our application folder.

Here is the code:

# application.rb
require 'grape'

# Load files from the models and api folders
Dir["#{File.dirname(__FILE__)}/app/api/**/*.rb"].each { |f| require f }

# Grape API class. We will inherit from it in our future controllers.
module API
class Root < Grape::API
format :json
prefix :api

# Simple endpoint to get the current status of our API.
get :status do
{ status: 'ok' }
end
end
end

# Mounting the Grape application
Application = Rack::Builder.new do
map "/" do
run API::Root
end
end

Finally, we need to create a file named config.ru so Rack will know how to start the application.

Note: This file is located at the root of our application folder.

# config.ru
require File.expand_path('../application', __FILE__)

run Application

We are ready to run our server for the first time. Run the server with rackup and access http://localhost:9292/api/status.

You should see this beautiful json:

{ status: 'ok' }

Thats all, in next chapters we are covering next themes:

  1. Versioning APIs
  2. Less Is More: Always Paginate Your ResultsKnock, Knock: Authentication
  3. Rate Limiting
  4. HTTP Caching: Conditional GET
  5. CORS Requests
  6. Hypermedia
  7. Respond Handling
  8. Provide Awesome Documentation