How to document REST APIs with Swagger and Ruby on Rails

Image for post
Image for post

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
rails new swagger-demo --api

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

rails generate model Pet name photo_url status

3. Create a CRUD pets controller using scaffold_controller generator

rails generate scaffold_controller api/v1/pets

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

bundle install

3. Run generator

rails generate rspec:install
rails g rswag:install

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

5. Generate the Swagger JSON file(s)

rake rswag:specs:swaggerize

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

http://localhost:3000/api-docs

Image for post
Image for post

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

Written by

Full Stack

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store