Adding Swagger to your Spring Rest API written in Kotlin
After creating a new Spring Rest API written in Kotlin I wanted to add Swagger2 to it. By adding Swagger you keep your api documentation up to date with almost no effort at all.
Before starting this tutorial, please create a Spring Rest API following this guide (https://spring.io/blog/2016/02/15/developing-spring-boot-applications-with-kotlin) or open an existing one from Github.
If you do not know Swagger you can have a look at their website http://www.swagger.io
Step 1 : Adding the Gradle dependency.
I’m using Swagger version 2.7.0 for this project. So we need to add this Dependency to our Gradle build file.
Step 2: Adding the Swagger config class
After adding the dependency to our Gradle Build file we only need to create a Swagger configuration file. This file can reside anywhere in you project. Because I like to keep my code tidy I have created a new package for this.
In this class Swagger is enabled with the “@EnableSwagger2” annotation.
Within our Configuration class we have created a Docket Bean. The select method in the Docket returns the Swagger instance of the ApiSelectorBuilder, this selector provides a way to control the endpoints exposed by Swagger.
By using the “RequestHandlerSelectors.any()” and “PathSelectors.any()” Swagger build the complete documentation for your api.
Step 3: Build and run
After adding the Gradle dependency and the Swagger Configuration Class everything worked right away. Build your project and run it locally to see if you have output.
In my case I simply had to go to the following URL to test:
You can find the complete repo at https://github.com/GuyHeylens/kotlinmyrestapi