Cowboy Swagger

In a previous post about Swagger in Erlang, we had seen how to add a nice documentation to our RESTful APIs with Swagger, but following the long/tedious path:

Well, forget about all that. Cowboy Swagger is an open source project built on top of Trails that integrates Swagger, so you can have a really nice Web documentation for your RESTful APIs in only a few simple steps.

Now, let’s see how simple and fast it is.

1. Document each Cowboy Handler

Because cowboy_swagger runs on top of trails, the first thing that you have to do is document all about your handler within the trails metadata. Keep in mind that all fields defined within each method into the metadata must be compliant with the Swagger specification.

For example, suppose that you have example_echo_handler, so it must implement the trails/0 callback from trails_handler behaviour:

trails() ->
  Metadata =
    #{get =>
      #{tags => ["echo"],
        description => "Gets echo var",
        produces => ["text/plain"]
      },
      put =>
      #{tags => ["echo"],
        description => "Sets echo var",
        produces => ["text/plain"],
        parameters => [
          #{name => <<"echo">>,
            description => <<"Echo message">>,
            in => <<"path">>,
            required => false,
            type => <<"string">>}
        ]
      }
    },
  [trails:trail("/message/[:echo]",
                example_echo_handler,
                [], Metadata)].

2. Include cowboy_swagger in your app

First, you need to include cowboy_swagger_handler module in your list of trails to be compiled.

% Include cowboy_swagger_handler in the trails list
Trails =
  trails:trails([example_echo_handler,
                 example_description_handler,
                 cowboy_swagger_handler]),
% store them
trails:store(Trails),
% and then compile them
Dispatch = trails:single_host_compile(Trails),

The snippet of code above is usually placed when you start cowboy.

Then add cowboy_swagger to the list of apps to be loaded in your *.app.src file.

{application, example,
 [
  {description, "Cowboy Swagger Example."},
  {vsn, "0.1"},
  {applications,
   [kernel,
    stdlib,
    jiffy,
    cowboy,
    trails,
    cowboy_swagger
   ]},
  {modules, []},
  {mod, {example, []}},
  {registered, []},
  {start_phases, [{start_trails_http, []}]}
 ]
}.

And that’s it, you got it. Now start your application and then you will have access to the API docs under the path /api-docs. Supposing that you’re running the app on localhost:8080, that will be http://localhost:8080/api-docs.

Finally, you’re welcome to check cowboy_swagger sources and a full demonstrative example here.