Best Practices

Swagger for REST Documentation

Swagger, now the Open API Initiative

A while ago, I attended an external event that sparked some great conversation around RESTful web services, specifically the JSON kind. It became apparent that there are still many people who hadn’t heard of this great tool to automatically document your REST API, named Swagger.

Swagger (nowadays, more formally, the OpenAPI specification) was originally developed by Reverb Technologies (since then acquired) and, although not supported by one of the usual standards bodies, Swagger aims to be the standard way of describing a REST API, and it is quickly becoming much of a de-facto standard in its field.

The most typical way of using Swagger is where it nestles itself within your REST server as just another resource/endpoint which describes your API in a standard JSON format.

There are a lot of relevant Swagger implementations, depending on the REST implementation that you’re using, such as for JAX-RS (Jersey, Resteasy, …), Spring MVC and Spring Web (some of these are independent open source projects.) There are also implementations that can export static versions.

Each of these implementations (as said above) spits out the same standard JSON format, which can be consumed by any REST client. But there is also a Swagger UI which supports the Swagger JSON format and offers a great way to have people explore your API, make test calls to it (even parameterized).

For the Java domain there are standardized annotations (example available) to decorate your resources to further document your API, such as exception information and humanly-readable descriptions.

It is hugely beneficial that Swagger gets its information from the source code/source of truth. It improves the reliability of the documentation and allows for quick prototyping. Client-side developers (QA) can easily explore, exercise and thus learn (test) your API.

The only ‘gotcha’ that I’ve come across is that Swagger might have a performance penalty on startup of your application, as it goes and introspect your API. This drawback might decrease as Swagger implementations mature further.