How to use Swagger Open API for API documentation in Spring Boot.

Manoj Ahirwar
Geek Culture
Published in
2 min readJan 1, 2023
Photo by Douglas Lopes on Unsplash

Swagger is a popular open-source tool that can be used to generate documentation for REST APIs. It uses the OpenAPI specification to describe the APIs and provides a user interface that allows users to interact with the APIs and view the documentation.

Here’s how to use Swagger OpenAPI for API documentation in a Spring Boot application:

Add the Swagger dependency

The first step is to add the Swagger dependency to your Spring Boot project. You can do this by adding the following dependency to your pom.xml file:

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>

Enable Swagger in your application

To enable Swagger in your application, you’ll need to create a configuration class that enables the Swagger 2 plugin. Here’s an example of how to do this:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}

}

Document your APIs

To document your APIs, you’ll need to use Swagger’s annotations to describe the different endpoints and their parameters. Here’s an example of how to do this:

@RestController
@RequestMapping("/users")
public class UserController {

@GetMapping
@ApiOperation(value = "Get a list of users")
public List<User> getUsers() {
// implementation omitted
}

@PostMapping
@ApiOperation(value = "Create a new user")
@ApiImplicitParams({
@ApiImplicitParam(name = "user", value = "The user to create", required = true, dataType = "User")
})
public User createUser(@RequestBody User user) {
// implementation omitted
}

}

Access the documentation

Once you’ve enabled Swagger and documented your APIs, you can access the documentation by going to the following URL in your browser: http://localhost:8080/swagger-ui.html. You should see a list of your APIs and the documentation for each one.

--

--