Building RESTful API using Grape in Rails

Blog Logo

on
26 Mar 2014

read

While developing a rich client side web application or mobile app, we need RESTful JSON API which interacts with the front-end javascript framework. Here you may use backbone.js, ember.js or angular.js on the front-end side of application.

Here we’ll be using Ruby on Rails on the back-end which will serve JSON API consumable by fron-end framework. If you look at the ruby toolbox you’ll see many API Builder gems available but it seems grape can be a good choice.

Grape is a RESTful API microframework built to easily and quickly produce APIs for Ruby-rooted web applications.

Let’s see how we can build RESTful JSON apis using Grape library:

Getting Started

Add grape to your Gemfile and then run bundle install

gem 'grape'

Modularizing API directory structure

Place API files into lib/api. You need to create api folder inside lib directory.
As we are placing api directory inside lib you don’t need to explicitly load it inside application.rb
If you want to place api directory at some other place then add below lines to to application.rb

Accessing API routes

If you do rake routes | grep api then it will list only mount path for api but do not list all the paths.

rake routes | grep api

api_root /api API::Root

So, in-order to list all api paths, you may have to create api routes task:

# lib/tasks/routes.rake

namespace:apido

desc"API Routes"

task:routes=>:environmentdo

API::Root.routes.eachdo|api|

method=api.route_method.ljust(10)

path=api.route_path.gsub(":version",api.route_version)

puts" #{method}#{path}"

end

end

end

Now, run task and it should print routes like this:

rake api:routes

GET /api/v1/posts(.:format)

GET /api/v1/authors(.:format)

Securing API

Now we have got Grape API ready and working properly. Lets see how we can secure API. There are many approaches to authenticate API. Here lets first get it working with simple HTTP Basic authentication.

HTTP Basic authentication

In our case, lets add basic authentication to the API::Root and it will get applied to all versions of API.

# lib/api/root.rb

moduleAPI

classRoot<Grape::API

#...

http_basicdo|email,password|

user=User.find_by_email(email)

user&&user.valid_password?(password)

end

#...

end

end

Requesting API using basic http auth credentials:

curl http://localhost:3000/api/products -u "admin:secret"

Authenticate using email and password

Grape provides us with before block inside that we can add authenctication code.