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
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
First, Let’s create API::Root class that will mount available api versions.
Now, create a API::V1::Root class that will mount resources for version 1
Now, add resource Posts available for api access in json format
Now, lets add one more resource Authors
to version v1
Mounting API under rails routes
Mount API::Root under routes pointing to rails root
Customize JSON API Errors
We can control the api raised errors and customize them so that response is in our own format whenever there are exceptions.
Now, you can plug this module inside API::Root
You can override error formatter for particular api version. Let’s customize errors for API::v1::Root:
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.
So, in-order to list all api paths, you may have to create api routes task:
Now, run task and it should print routes like this:
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.
Requesting API using basic http auth credentials:
Authenticate using email and password
Grape provides us with before block inside that we can add authenctication code.