[Guide] Using Swagger for documenting your Spring boot REST API

What is Swagger?

Well, it's a *must resist* ...
... a SWAG way of documenting your APIs.
(in this dictionary SWAG refers to something being cool)

Okay, with that out of the way. The guys at Swagger.io defines it to be a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. Swagger is a formal specification that is surrounded by a large ecosystem of tools. Among these are code-generation tools, user-interfaces etc.

In this post we will only be looking at Swagger as an easy way to document your Spring Boot application. We will be extending the project described in a previous post and the source code for getting started can be found at GitHub.

To get started, clone the project and open it in your favourite IDE. The first thing we need to do, is to add some new dependencies to our pom.xml file.

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
            <scope>compile</scope>
        </dependency>

The next thing we need to do is to enable Swagger in the main application. This is easily done with the @EnableSwagger2 annotation.

@SpringBootApplication
@EnableSwagger2
public class SpringBootRestExampleApplication {

    private final Faker faker = new Faker();

    public static void main(String[] args) {
        SpringApplication.run(SpringBootRestExampleApplication.class, args);
    }

    @Bean
    public CommandLineRunner initializeDb(PieRepository repository){
        return (args) -> {
            repository.deleteAll();
            //Insert some random pies
            for(int i = 0; i < 20; i++) {
                repository.save(new Pie(faker.lorem().word(), faker.lorem().sentence()));
            }
        };
    }

}

One last thing is needed before being able to use the documentation provided by Swagger and that is to configure how and what we want Swagger to work with.

@SpringBootApplication
@EnableSwagger2
public class SpringBootRestExampleApplication {

    private final Faker faker = new Faker();

    public static void main(String[] args) {
        SpringApplication.run(SpringBootRestExampleApplication.class, args);
    }

    @Bean
    public CommandLineRunner initializeDb(PieRepository repository){
        return (args) -> {
            repository.deleteAll();
            //Insert some random pies
            for(int i = 0; i < 20; i++) {
                repository.save(new Pie(faker.lorem().word(), faker.lorem().sentence()));
            }
        };
    }

    @Bean
    public Docket swaggerSettings() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/");
    }
}

Okay, a lot of things added here, let's go through them at a slower pace. We have to add a new @Bean to our project, instead of it being a CommandLineRunner its now a Docket instead. A Docket is a builder intended to be the primary interface into the swagger-springmvc framework and it provides defaults and convenience methods for configuration. In the Docket constructor we specify that we want to use the Swagger2 documentation type. Moreover we specify that we want all paths shown in the documentation. You could easily limit this with a RegEx.

Build and run the application, either through your IDE or by entering mvn spring-boot:run in the commandline and enter the following address in your favourite browser.

http://localhost:8080/swagger-ui.html  

If everything worked, you should see a screendump similar to the one below

and if you point your browser to

http://localhost:8080/v2/api-docs  

You should see the Swagger definitions file or the 'formal specification' of you api!

So far, we have covered how you can easily setup Swagger in a way to document your Spring Boot Rest APIs. This is just one way of using Swagger, however Swagger can be used with a 'definition first' approach instead of 'endpoints first' approach. For more information on Swagger and the tools that they provide, go visit Swagger.io.

Download the complete code for this tutorial here.

Happy hacking - over and out!