Swagger documentation for your Spring Boot API with Springfox

If you’d like to provide Swagger documentation for your Spring Boot REST API in a nice way, you’re in the right place.

Today I’m going to show you how you can achieve it in an automated way, without using tons of annotations in your controllers.
Springfox is a nice tool that allows you to do it.

In this text, I’ll be using the REST API built previously in this text using Spring Boot and Kotlin language, as an example.

Add Springfox dependencies

Springfox Swagger 2 dependency

At first, let’s add Springfox Swagger 2 dependency to the project.

If you’re using Gradle add the following line into your dependencies in build.gradle file:

dependencies {

	...

	implementation("io.springfox:springfox-swagger2:2.9.2")

}
build.gradle

If you’re using Maven, then add following lines into dependencies in project’s pom.xml file:

<dependencies>
    ...
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>
pom.xml

Springfox Swagger UI dependency

In order to provide a user interface for the docs, we need to add Springfox Swagger UI dependency as well. But if you don’t want to provide it, you can skip this step.

Gradle dependency:

dependencies {
        ...
	implementation("io.springfox:springfox-swagger-ui:2.9.2")
}
build.gradle

Maven version:

<dependencies>
    ...
	<dependency>
		<groupId>io.springfox</groupId>
		<artifactId>springfox-swagger-ui</artifactId>
		<version>2.9.2</version>
	</dependency>
</dependencies>
pom.xml

Provide configuration class

We need to provide a configuration class in order to instruct Springfox on how to use our code.

Put the following code in your SwaggerConfig class:

@Configuration
@EnableSwagger2
class SwaggerConfig {
    @Bean
    fun api(): Docket {
        return Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("net.mestwin.mongodbrestapidemo.controller"))
                .paths(PathSelectors.any())
                .build()
    }
}
SwaggerConfig.kt

The Docket object and @EnableSwagger2 annotation are the keys here. It provides basic configuration for automated documentation generation.

In this configuration, when Springfox will scan our controller classes, it will be narrowed down to one specific package. Alternatively, we can use RequestHandlerSelector.any() or none() values for filtering all or none endpoints.

It’s possible to filter out some paths in paths() method parameters. For example, if you have some admin-specific paths and you don’t want to include them in the documentation you can use PathSelectors.regex(“/api/.*”) as a parameter.

Run the application

At this point, you’re able to run your application and see your auto-generated documentation.

Run your application and browse on http://localhost:8080/v2/api-docs  (the address may vary, depends on your application configuration).

If you don’t need to have documentation with rich UI you can just copy the JSON output and paste it to online Swagger Editor.

But if you’d like to have UI provided by your application, let’s do it in the next step.

Providing Swagger UI

If you have provided Springfox Swagger UI dependency you’ll be able to see the results on http://localhost:8080/swagger-ui.html (again, the path may vary, depends on your config).

At this point, you’re able to play around with your API.

Documentation improvements

If you’re not happy about auto-generated descriptions, you can still use Swagger annotations in your controller code.

For example, you can use @ApiOperation and @ApiParam annotations to describe endpoints and parameters.

Here’s the example for getOneTask method:

    @GetMapping("/{id}")
    @ApiOperation(value = "Returns task by id")
    fun getOneTask(
            @PathVariable("id")
            @ApiParam(value = "Task id", required = true)
            id: String
    ): ResponseEntity<Task> {
        val task = taskRepository.findOneById(ObjectId(id))
        return ResponseEntity.ok(task)
    }
TaskController.kt

And here’s the result on the UI:

Conclusions

Springfox can be used for Swagger documentation auto-generation. It’s easy to configure and use in the Spring Boot project.

However, please note that in this text I used a very simple REST API application for test purposes. In more complex applications you’ll probably have to customize more details in order to make it work as you expect.

Anyway, try it. Definitely, it’s worth to give it a shot.

Resources

Leave a Reply

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