Build a basic API in a Rails 3 application
22 Jul 2011
Knowledge
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.
Installation
In your Gemfile, add thisgem 'grape', '~> 0.1.5'then
$ bundle install
Usage
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#lib/api.rb
module Journal
class API < Grape::API
prefix 'api'
resource 'entries' do
get do
Entry.all
end
get ':id' do
Entry.find(params[:id])
end
end
end
end
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 middlewareYou should see
... run Journal::Application.routesRestart your application and try out your new API service at /api/entries and /api/entries/1.
