Add some Swag{ger} to your SpringBoot API

A while back we created a simple API with spring-boot. See here. One of the key thing is that people have to know how to find and use your API. You can have the coolest API in the world but if people can’t find it and don’t know how to use it….it rather useless. There are a few tools which can help us document our API. We can use Swagger, Apiary or RAML. For spring-boot, there is a set of libraries which can help you document your API in a very easy manner using Swagger. Meet SpringFox:

springbootswagger

“Springfox works by examining an application, once, at runtime to infer API semantics based on spring configurations, class structure and various compile time java Annotations.”

In the next section I will show how you can let SpringFox generate Swagger API documentation for you based on your Spring classes.

For the code see https://github.com/hugohendriks1978/climbing-api

Adding dependencies

One of the first things we have to do is add 2 dependencies to your pom.

<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>

Setup

Next up, we will create a bean which creates a Docket. This is the starting point of the configuration for your Swagger documentation. Mine looks like this:

package nl.redrock.climbersapi.swagger;

....

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket climberApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select().apis(RequestHandlerSelectors.basePackage("nl.redrock.climbersapi"))
                .paths(regex("/climber.*"))
                .build());
    }
}

By setting the basePackage to the right location, it will look for RestController classes and generate documentation items based on annotations. That is it. Lets run the application and see what it comes up with.

When you have started your springboot app, browse to http://localhost:8080/swagger-ui.html.

basic

As you can see, it already shows the 3 operations we had defined together with some basic info. From here on we can add extra information as it is not complete yet. Let start with some basic information of the api. We can add this by

                .build()
                .apiInfo(metaData());
        }

private ApiInfo metaData() {
        ApiInfo apiInfo = new ApiInfo(
                "Climber API",
                "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur consequat congue dignissim. Donec non fermentum nunc, quis sagittis nibh. Vestibulum ut ullamcorper ante. Pellentesque porttitor posuere dui, vel fringilla ex maximus vitae. Pellentesque facilisis orci et dictum finibus. Sed quis fermentum ligula, et posuere enim. Nulla ultricies a ex at elementum. Pellentesque tempor sit amet est eget blandit. Sed aliquam neque sed ante commodo, eget commodo turpis interdum. Praesent hendrerit accumsan enim, sed pellentesque dolor sollicitudin hendrerit. Suspendisse posuere libero in lectus egestas, quis imperdiet urna mollis.",
                "1.0",
                "Terms of service",
                new Contact("Hugo Hendriks", "https://redrock-it.nl", "hugo@redrock-it.nl"),
                "Apache License Version 2.0",
                "https://www.apache.org/licenses/LICENSE-2.0"
                );
        return apiInfo;
    }

If we restart the application we can now see that we have added api info.

api-info

Annotations

Next up we can use annotations in the @restcontroller to specify more details. By adding @ApiOperation

    @RequestMapping(value = "", method= RequestMethod.GET, produces = "application/json")
    @ApiOperation(value = "View a list of climbers", response = Iterable.class)
    List<Climber> getClimbers() {
        List<Climber> result;

we set a description of the operation and what kind of response you can expect.

operation-info

One of the thing we are still missing is the information for the data model. We can add this to the climber Entity

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @ApiModelProperty(notes = "The generated climber id", required = true)
    private int id;
    @ApiModelProperty(notes = "The climbers firstname", required = true)
    private String firstname;
    @ApiModelProperty(notes = "The climbers lastname", required = true)
    private String lastname;

After adding this we can see the data definition in the UI.

model-info

In conclusion: SpringFox allows you to very quickly generate Swagger documentation for your SpringBoot REST services. You can also customize a lot and the generated UI let’s you test the service like a proper API development portal. To see all that SpringFox is a capable of, check out http://petstore.swagger.io.

References:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.