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.
- 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.
- 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
- Add rswag and rspec-rails gems to Gemfile
2. Install with bundler
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)
6. Spin up your app and check out the awesome, auto-generated docs at
Find working code example at https://github.com/mximos/swagger-demo