Adding Swagger OpenAPI to an existing Spring Boot project is a great way to document and test your RESTful APIs. Here are the steps to integrate Swagger into your Spring Boot application:
1. Add Dependencies in pom.xml:
In your pom.xml , add the following dependencies to enable Swagger:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version> <!-- Use the latest version available -->
</dependency>
2. Configure Swagger:
Create a configuration class to enable Swagger and configure its behavior:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.ashu.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger API Documentation")
.description("Description of your API")
.version("1.0")
.build();
}
}
3. Enable Swagger UI:
Swagger UI is available at /swagger-ui.html in your application's context path. To configure a custom path, you can add the following property to your application.properties:
application.properties:
springfox.documentation.swagger-ui.path=/custom-swagger-ui
4. Run Your Application:
Now, run your Spring Boot application, and you should be able to access the Swagger UI by navigating to http://localhost:8080/swagger-ui.html.