William Notowidagdo Kiranatama Staff

In this post we will show you how easy to add basic API feature to an existing Rails application using Grape. Grape built to complement existing web application frameworks such as Rails and Sinatra by providing a simple DSL to easily provide APIs. By using Grape, we cut those heavy lifting works while building an API feature such as multiple formats response, subdomain/prefix restriction, and versioning.


In your Gemfile, add this
gem 'grape', '~> 0.1.5'
$ bundle install


In this example, I want to add couple API service to an existing application called Journal. In Journal, user add entries they want to keep. The API will provide GET /api/entries which should return all entries and GET /api/entries/1 which should return entry with id=1. Create a file named api.rb di lib directory
module Journal
  class API < Grape::API
    prefix 'api'
    resource 'entries' do
      get do

      get ':id' do
Grape APIs are Rack applications that are created by subclassing Grape::API. In Rails 3, you can easily mount any Rack application. Just add the following line to your config/routes.rb file
mount Journal::API => "/"
You will need to this following too at the top of config/routes.rb file
require 'api'
Check your configuration by running
$ rake middleware
You should see
run Journal::Application.routes
Restart your application and try out your new API service at /api/entries and /api/entries/1.