Documenting Ruby on Rails APIs Using rswag Gem | by Iyadi Cyril Osita | Mar, 2022

Documentation is among the most essential components of software program growth. Though the computer systems run the code, we discover that we additionally write code for individuals to learn. Swagger is a very fashionable device for API documentation. In Ruby on Rails, it may be added utilizing the rswag gem.

As an example I will likely be utilizing a Rails API software. You’ll be able to create one utilizing the command:

rails new project-name --api --database=postgresql

I have already got one arrange, I need a Automotive mannequin with identify and mannequin properties, and a controller scaffolded with the required endpoints. This may be accomplished simply utilizing:

rails g scaffold automobile identify:string mannequin:string

For now, my cars_controller seems like this…

class CarsController < ApplicationController before_action :set_car, solely: [:show, :update, :destroy] # GET /vehicles def index
@vehicles = Automotive.all
render json: @vehicles
finish
# GET /vehicles/1 def present
render json: @automobile
finish
# POST /vehicles def create
@automobile = Automotive.new(car_params)
if @automobile.save
render json: @automobile, standing: :created, location: @automobile
else
render json: @automobile.errors, standing: :unprocessable_entity
finish
finish
# PATCH/PUT /vehicles/1 def replace
if @automobile.replace(car_params)
render json: @automobile
else
render json: @automobile.errors, standing: :unprocessable_entity
finish
finish
# DELETE /vehicles/1 def destroy
@automobile.destroy
finish
non-public # Use callbacks to share widespread setup between actions. def set_car
@automobile = Automotive.discover(params[:id])
finish
# Solely enable a listing of trusted parameters via. def car_params
params.require(:automobile).allow(:identify, :mannequin)
finish
finish

please notice that the arrange above will not be obligatory for the swagger docs to work. It’s intuitive sufficient to arrange the required recordsdata based mostly in your controller actions

Subsequent, we arrange the swagger docs.

To start we want the gems, so add the next to your gem file:

gem 'rspec-rails' # ignore if already arrange in challenge

gem 'rswag'

Subsequent, run the next instructions:

bundle set up
rails g rspec:set up # ignore if already arrange in challenge
rails g rswag:set up

It’s best to have the next recordsdata added to your repository, together with new routes added to the routes.rb file.

Now we generate the swagger exams recordsdata for our controllers, in my case that might be the cars_controller, so I run:

rails generate rspec:swagger vehicles

When you’ve got submodules construction in your controllers you should utilize the listing construction so Swaager generates the recordsdata based mostly on the appropriate controller. For instance, if vehicles had been within the V1 module that’s nested within the API modulewe’d run:

rails generate rspec:swagger API::V1::vehicles

The rails generate rspec:swagger vehicles command provides the suitable spec file, cars_spec.rbwhich is nested in spec/requests listing. The file seems like this…

Don’t get confused we’ve got respective motion verbs for every path grouped (GET, POST, PUT, and so on).

Earlier than we proceed let’s generate the precise swagger docs that will likely be used for the swagger UI. Keep in mind to create all obligatory databases and run your pending migration.

Run the command under:

rake rswag:specs:swaggerize

As soon as profitable it is best to have a swagger.yaml file, run your rails server rails s and go to the URL and add /api-docs and behold the Swagger UI documentation of all endpoints for the automobile controller.

Now we start customizations, first, we edit the servers subject, proper now it reads https://defaultHostit can’t be edited from the UI, we are able to edit the default host subject and add the area identify, in my case it’s localhost

Navigate to swagger_helper.rb within the spec folder and edit the URL attribute in servers array to no matter suits your state of affairs, I’m working on my localhost so that is what I want:

servers: [

url: 'http://defaultHost',
variables:
defaultHost:
default: '127.0.0.1:3000/'



]

To see your new modifications mirrored run rake rswag:specs:swaggerize after which refresh the web page.

Now we are able to run exams, by default swagger doesn’t generate docs that eat JSON, so there aren’t any our bodies within the requests for anyACTION VERB.

To check and correctly doc the endpoint for creating vehicles for instance we’ve got to inform swagger the type of object and the properties wanted. Navigate to the spec folder for the controller and add one thing like this:

consumes 'software/json'        
parameter identify: :automobile, in: :physique, schema:
sort: :object,
properties:
identify: sort: :string ,
mannequin: sort: :string
,
required: %w[name model]

My submit part finally ends up wanting like this…

Line 3 tells swagger to make room to ship a physique as a part of the request, Traces 4–11 defines the article that will likely be despatched together with its parameters and the fields which can be required. The identical might be repeated for put and patch sections. For extra information varieties you possibly can examine this article for the suitable alternative.

To see your new modifications mirrored run rake rswag:specs:swaggerize after which refresh the web page. After we collapse submit we see our physique ready for us.

Click on Strive it out enter the suitable fields and hit ship. As you possibly can see it was created efficiently.

You’ll be able to check different endpoints accordingly, not that GET and DELETE want no physique, DELETE PUT and PATCH want the ID, and lastly, POST PUT and PATCH want a physique.

With this, you possibly can share an interactive atmosphere to your purchasers and colleagues to get conversant in all of your endpoints.

Glad coding.

Wish to Join?Be happy to run some extra exams with totally different situations, in case you get caught be at liberty to succeed in out on Twitter or LinkedIn and I might be very completely happy to assist out.

More Posts