API Heaven with Grape and Swagger

There comes a time when you need to add an API to your little Startup. Either to let your iOS or Android app communicate with your page and/or to please your users. Luckily it’s very easy in Rails to create a nice API with a beautifull documentation like this:

Swagger UI

On that screenshot you are seeing Swagger. A little collection of HTML and Javscript to create a beautifull and interactive API documentation. If you combine that with Grape, a micro framework for REST-like APIS, you can start writing your API within minutes.

The first step for this is to add the following gems to your Gemfile:

gem 'grape', '~> 0.6.1'
gem 'grape-entity', '~> 0.4.0'
gem 'rack-contrib', '~> 1.1.0'
gem 'grape-swagger', '~> 0.7.2'
gem 'grape-swagger-rails',  '~> 0.0.8'

The grape and the grape-entity gems are the API DSL, the rack-contrib is used to be able to use JSONP callbacks, the grape-swagger creates the Swagger description file and grape-swagger-rails embeds Swagger into your app.

Now you need to configure where the Swagger UI can find your API description file. For this add the file config/initializers/grape_swagger_rails.rb and add the following code to it:

GrapeSwaggerRails.options.url      = "/api/swagger_doc.json"
GrapeSwaggerRails.options.app_name = 'Example'
GrapeSwaggerRails.options.app_url  = '/'

Now you need to wire your API into the routes of your app. Add the following Files to the routes.rb of your Rails project:

# API+API Documentation
mount API::Base => '/api'
mount GrapeSwaggerRails::Engine => '/apidoc'

This adds the API into /api and the documentation to /apidoc.

The only thing missing now is the actual API. For example something like this:

module API
  class Base < Grape::API
    default_format :json

    # Separate the api into smaller
    # modules like this
    mount API::HighScores => '/high_scores'

    # Adds the swagger documentation to your
    # api. You only need this once, not in
    # every sub module
      base_path: "/api",
      hide_documentation_path: true

I created a little project as a starting point for your experiments with this setup.

Grape is a very powerful API framework and should have everything you need from an API. There are tons of plugins for caching, Hypermedia style APIs and much more. The very extensive documentation is a good start to get into it.

If you need to tweak the Swagger UI you should read the documentation of Grape-Swagger-Rails and Grape-Swagger.

Portrait photo of Bodo Tasche
Bodo Tasche
Polyglot Developer

I am a freelance polyglot developer and love HTML5, testing, JavaScript, Ruby and Elixir. In the last 20 years I have been in lots of different roles, from Java to Elixir, from backend developer at a 3 people team in an early phase startup to the CTO of a web agency.

Need help developing your MVP or to add new features into your current app? Need a CTO or a front/backend developer for hire? Send me an email.