API Documentation Made Easy

I have been doing a little fun side project for myself on and off for the better part of six months. The end goal is to complete it for it to be useful, but as of late it’s been more of a playground for myself to learn new technologies and step out of my comfort zone.

Currently I have been focused on creating an API for the application utilizing the JSON:API spec backed by a ruby back-end using the JSON API-RB gem. I was breezing through setting it up until I took a break for a month and subsequently tried to get back into it during my sabbatical. This is where I hit snags in re-learning where I left off.

Documentation is key

The main issue I had with getting back to the project was trying to remember what I had done or what was left to do. I had plenty of specs written, but there was something missing. It struck me that I could use some form of documentation — even if it wasn’t to be made public — to outline where the gaps were. I set off trying to figure out the best course of action to get documentation in play.

What to use…what to use…

At my current gig we utilize Grape with Swagger. This works for us because the app is so big and there are many touch points and having an opinionated setup helps streamline things. My app is currently super small, I am the only one working on it, and I was already using serializers to manage my representations. Just glancing through initial setup for Swagger docs I could already tell it would be overkill for what I need.

I looked back at my well documented specs and thought there must be a way to utilize these in some form. A google search landed me on an RSpec API Documentation gem. It was exactly what I needed to keep things simple and utilize what I had at hand. Granted just adding the gem wouldn’t solve it right away without some intervention on my side, but this was another experience to learn something new. I even was able to make a contribution to some open source.

Key findings

Below is an example pulled from one of my specs written, outlining some of the different options provided by the documentation gem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
post "/api/v1/bank_account" do
it_behaves_like "an endpoint with correct errors"

let(:name) { "Sloan" }
let(:family_id) { family.id }
let(:child_id) { child.id }

with_options scope: :data,
required: true,
with_example: true do
parameter :family_id, "The family ID"
parameter :child_id, "The ID of the child bank account associated with"
parameter :name, "The name of the bank account"
end

example_request "POST: Bank Account" do
expect(status).to eq(200)
expect(document["data"]).to have_attribute(:child_id).with_value(child.id)
expect(document["data"]).to have_attribute(:name).with_value("Sloan")
expect(document["data"]).to have_attribute(:family_id).with_value(family.id)
end
end

One of the things I found was how much cleaner my tests had become. Overtime, I was able to refactor the tests down so that they covered only what was needed and they were clear on what they were testing. The documentation provided on the GitHub page was super helpful with clear concise examples.

I ended up creating a few shared examples to for the error cases so that each endpoint could be covered in that direction. Those examples are depicted below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
shared_examples_for "an endpoint with correct errors" do |params|
example "returns a 401 error message", document: false do
if user
header "access-token", nil
header "client", nil
header "token-type", nil
header "expiry", nil
header "uid", nil
do_request
expect(status).to eq 401
expect(JSON.parse(response_body, object_class: OpenStruct)["errors"]).to include I18n.t("devise.failure.unauthenticated")
end
end

example "returns a 422 message", document: false do
do_request(data: { foo: "bar" })
expect(status).to eq 422
end

example "returns a 404 message", document: false do
if params.present?
do_request(params)
expect(status).to eq 404
end
end
end

Being able to outline parameters, required or not, which included the description was very helpful to remind myself visually what was needed to send across the wire. There are plenty of other options provided by the gem I have not used to flesh out the docs, but this was an good start.

A few discoveries and modifications

Since I am using Devise Token Auth and all the logged in endpoints require authentication, I needed to figure it a way to keep things dry in the tests. Instead of typing out the required headers each time, I settled for creating a before each filter to do just that which I included in my rails helper file for the Rspec.config block.

1
2
3
4
5
6
7
config.before(:each, type: :doc) do
unless user.nil?
user.create_new_auth_token.each do |key, value|
header key, value
end
end
end

This will loop through all the keys in the auth token for a user and print them out as headers in the spec before the request is run.

I also found the rake task provided by the gem to generate the docs to be somewhat limiting. By default it is keyed to the acceptance directory for specs. I had opted for doing the Rails 5 convention and putting all my request specs in the features directory.

Since the gem could not look into that directory, I forked their repository to make a modification so that an option string could be passed through to change the directory.

1
rake docs:generate[MYFOLDER] # generate docs from specified folder

Now any directory can be passed through to make sure the specs are generated. Also, it is setup so that if no option passed in, it will default to the original acceptance directory.

The Outcome

One of the settings in the gem initializer file allows the specification of the type of file produced. By default it is set to HTML, but I was not going to serve these up to look at through a server. Instead, I changed the option to generate Markdown and installed a VSCode markdown renderer plugin. As an added benefit, the GitLab repository renders the Markdown pages just like a wiki would, so viewing in browser comes for free!

After this little side jaunt, I can definitely say I have learned some new tools of the trade. I now can look back and see what state my API is in and how visually things are hooked together. Documentation is hard to write sometimes, but when there is a tool to auto generate this, definitely take advantage.

Filed under: Code
bubbles Created with Sketch. CS Icon Created with Sketch.