API Documentation with Grape and Swagger

TL;DR Use Swagger and Grape to create self-documenting APIs that automatically update themselves from metadata in the code. It also provides an API explorer to play around with.

During the AngelHack KL event, I (being the backend developer of the team) had to create an API to facilitate communication between the iPhone app and Twilio. Since it was a hackathon, there was not a lot of time to completely hash out API protocols (as well as explaining to my team mates how RESTful APIs work).

I was able to solve this by using Grape and Swagger. I can develop the API at my own time. When a particular endpoint was finished, I can push to production and my team mate is immediately able to see the documentation. He was also able to make use of the API explorer to test out the API’s responses to his queries.

We were able to quickly develop the whole project quickly and easily because of this, and here’s a quick look at using Swagger with Grape.


Github Sample Application

I’ve made a sample application which you can refer to here: https://github.com/parasquid/grape-swagger-sample-project. It was based off from another grape tutorial with modifications; see his page for a bit more information.

A few changes I’ve made are:


Grape

The self-documenting ability of Grape with Swagger actually consists of three separate gems that work together to provide an endpoint for a UI to consume. The first of these is Grape:

Grape is a REST-like API micro-framework for Ruby. It’s designed to run on Rack or complement existing web application frameworks such as Rails and Sinatra by providing a simple DSL to easily develop RESTful APIs. It has built-in support for common conventions, including multiple formats, subdomain/prefix restriction, content negotiation, versioning and much more.

There was a lightning talk at Red Dot Ruby Conf 2014 as well:


Grape Swagger

The grape-swagger project has comprehensive instructions on enabling swagger for your Grape API; it’s really a no-brainer.

The grape-swagger gem provides an autogenerated documentation for your Grape API. The generated documentation is Swagger-compliant, meaning it can easily be discovered in Swagger UI.


Swagger UI

Swagger UI Screenshot

After making sure that Grape has a swagger json endpoint, Swagger UI gives you two awesome abilities:

It was the API explorer that hooked me into investing time and effort into experimenting with grape and swagger, and it’s been really helpful with team communication.


Further Reading

Comments

comments powered by Disqus