How to document REST APIs with Swagger and Ruby on Rails

Planning to expose REST API’s to external world? Swagger can help you to make them easy to understand, easy to test for both humans and machines.

Why Swagger?

  • Swagger framework can solve Server-Client documentation problem.
  • With language agnostic declarative specification clients can understand and consume services without knowledge of server implementation or access to the server code backed by plenty of open sourced resources available online.
  • Applications implemented based on OpenAPI interface (fka Swagger Specification) can automatically generate documentation of methods, parameters and models.
  • This helps keep the documentation, client libraries, and source code to be in sync.
  • Provides sandbox UI (swagger-ui) to allow developer and non developer to interact with APIs.
  • Comes with a tool (Swagger-Codegen) which contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing the OpenAPI definition.

Today we are not going into the details what & how of swagger but integrating swagger with Rails application with rswag, a open-sourced ruby gem which makes it easy to add swagger to your Rails application. Good thing about rswag is it keeps your code separate from swagger annotation.

Rails API only

Let’s create minimal application structure to generate well known (in Swagger ecosystem) minimal Pet store example.

  1. Create Rails application skeleton

2. Create a Pet model with name, photo_url and status fields

3. Create a CRUD pets controller using scaffold_controller generator

This will generate a scaffold controller with few tweaks,

Setup rswag gem

  1. Add rswag and rspec-rails gems to Gemfile

2. Install with bundler

3. Run generator

4. Create an integration spec to describe and test your API

5. Generate the Swagger JSON file(s)

6. Spin up your app and check out the awesome, auto-generated docs at

http://localhost:3000/api-docs

Find working code example at https://github.com/mximos/swagger-demo

Full Stack