Add swagger to the kotlin spring

Introduction

In this short article we shall see how to configure swagger with spring webflux project. We create a project on spring initializer and then shall configure swagger.

Dependencies

Create a project on the spring boot initializer page with dependency as ‘webflux’ and language as ‘java’

spring initializer

In order to work swagger with kotlin you need to add the following repositories in you pom.xml file.

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-webflux</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
view raw pom.xml hosted with ❤ by GitHub

Since the swagger dependencyis available in another repository you need to add that repository as well in you ‘pom.xml’ file as below-

<repositories>
<repository>
<id>swagger1</id>
<name>swagger-snapshot</name>
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
</repository>
</repositories>
view raw pom.xml hosted with ❤ by GitHub

Setup swagger with kotlin

Create a class called ‘SwaggerCofig’ this class is responsible to configure Docket for our application as below

@Configuration
@EnableSwagger2WebFlux
class SwaggerConfig {
@Bean
fun api(): Docket =
Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("org.personal.finance.personalFinance.web"))
.paths(PathSelectors.any())
.build()
}

at line no# 9 we set the path of the rest controllers, swagger will scan this package to pick the endpoints.

Create a sample response object

Create a simple LoanDetailFacade that will contains the details about the loan.

@Document
data class LoanDetail(var _id: String,
var loanAmount: BigDecimal,
var loanCommencedDate: LocalDate,
var interestRate: Float,
var numberOfEmi: Int,
var emiAmount: BigDecimal)

Create rest controller

It’s the same as we do in spring web create some endpoints as below

@RestController
@RequestMapping("/api/v1/loan")
class LoanDetailController () {
@GetMapping("/detail", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
fun getdata():Mono<LoanDetail> {
return Mono.justOrEmpty(
LoanDetail(_id = "dummy",
loanAmount = BigDecimal.valueOf(100_000L),
emiAmount = BigDecimal.valueOf(1000L),
interestRate = 10.00F,
loanCommencedDate = LocalDate.now(),
numberOfEmi = 180)
)
}
}

Test Application

To run the application use below commn mvn spring-boot:run

go to the url http://localhost:8080/swagger-ui.html

the swagger page should show like this

swagger ui example

Repository

The full source code is available here GitHub.