Saturday, 20 December 2014

12 Tips of Christmas - 10 Building an API with Grape

12 Tips of Christmas - 10 Building API's with Grape

As I work more and more with Ember, grasping onto well structured API's becomes increasingly valuable. Thanks to Grape, building an API out of your Rails application is very easy.
To start, add grape to your Gemfile, like so and run bundle install

gem "grape"

As we're ultimately serving up a response to requests from the client, we're going to house our API in our controllers directory. As Grape supports versioned API's we're going to keep that structure in place when we begin to create our API. So, first things first, let's create a base.rb file to mount our versioned API's

This makes our users and posts API available at http://localhost:3000/api/v1/users.json and http://localhost:3000/api/v1/posts.json respectively (assuming you're exporting out JSON).
So let's take a look at what our API's might look like:

module API
module V1
class Posts < Grape::API
version 'v1'
format :json
resource :posts do
desc "Return 10 most recent posts"
get do
Post.most_recent.limit(10)
end
desc 'Find a specific post'
params do
requires :id, type: Integer, desc: "The ID of the post"
end
get ':id' do
Post.find(params[:id)
end
end
end
end
end

In this very simple example, we declare the version and the format in which we will return.
We also declare the resource we're going to work with, along with our two GET requests we accept, one that returns the 10 most recent posts and one that will return a post determined by the id parameter supplied.
You'll notice that this is starting to look alot like our regular controllers, as well it should. We can also expand on this to start allowing users to make POST and PATCH requests as well.
With our params block , we can specify what parameters we accept as well as in what format they should come, much like Rails' strong parameters.
We also have the ability to document our API as we go with our description methods, this is far far easier to do as you're building up the API so I highly encourage you to do it as you go.
In the next post we'll take a look at restricting the data coming back out of our API