Autodocumenting with Swagger
This suite uses DSLs to specify inputs (strong_resources
, filters, etc), and outputs (jsonapi-rb
serializers).
We can introspect that DSL to provide automatic documentation. Not only
does this save a lot of time, it ensures your code and documentation are
never out of sync.
Here we’ll be using swagger, a popular open-source
documentation framework.
To get this UI, we need to install two things: a controller that
generates a schema (swagger.json
), and a static website
in public
. Our generator installs these dependencies:
Note: here we’re moving jsonapi_spec_helpers
out of the
test-specific bundle group. Introspecting spec helpers is part of
autodocumenting, so we’ll require
them manually when our documentation
controller is loaded.
The generator also installs a Swagger UI in your Rails app’s public
directory. If you haven’t already done so:
Our documentation will be accessible at /api/docs
, so we put the files
in public/api/docs
. You may want a different directory depending on
your own routing rules. In either case, our next step is to edit
index.html
: make sure any javascript and css has the correct URL.
There are also a few configuration options, such as providing a link to
Github.
This static website will make a request to /api/swagger.json
. Again,
if not using the generator you’ll have to add that endpoint:
Our DocsController
uses swagger-blocks to generate
the swagger schema. Here’s the minimal setup needed to configure
swagger:
That’s it. Now, every time we add an endpoint, we can autodocument with
one line of code (below the swagger_root
block):
This endpoint will be introspected for all RESTful actions, outputting the full configuration. There are a few customization options:
If you want additional attribute-level documentation, you can add this to your spec payloads:
Will give you an output similar to:
Authentication
Your site may require authentication - for instance, sending a
Authorization
header in every request. We suggest using something like
Request.ly to modify headers for every request to a given URL.