How to use swagger to document REST API: Code first approach

Posted by Java developer blog on November 11, 2018

Code first approach

The approach is to implement all endpoints and models in a code and then expose REST API to a client or a developer in a company.

In the previous post I described API first approach.

It much easier to implement the code first approach for an existing project compare to the API first approach, because you simply need to add a couple of dependencies and a configuration class. That’s it!

However, code first approach is very useful because a frontend team will be able to get the current version of a backend API at any moment without bothering anyone from a backend team.

Add the following dependencies to a pom file:

1
2
3
4
5
6
7
8
9
10
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

springfox-swagger2 - it makes API avaliable in a JSON format.

springfox-swagger-ui - it makes API avaliable in a Swagger UI format.

Then add SwaggerConfig class to configure swagger. You could read more about it here.

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
@EnableSwagger2
public class SwaggerConfig {                                    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                           
    }
}

@EnableSwagger2 - it enables springfox-swagger2.

new Docket - it initialized springfox with SWAGGER_2 format.

select() - it returns an instance of ApiSelectorBuilder.

apis() - it allows to select a RequestHandler.

paths() - it allows to select a Path.

build() - it builds the selector after an api and a path configuraion.

Then open the following url to check the REST API in a JSON format:

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

or in a Swagger UI format:

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

Caution: you may need to change the default port.

You could use additional annotations like @Api, @ApiOperation, @ApiResponses, @ApiResponse to make you REST API more readable with help of Swagger Annotations.