How to Autodocument with Swagger
You can follow the steps below, or view the diff on github
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
. Let’s start by adding 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.
Our web UI is a Glimmer App,
but we’ll only deal with the already-compiled static files glimmer builds.
Let’s copy those files and expose them to the web by putting them in
public
:
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
. Let’s
build that endpoint now:
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: