Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-07-10 02:01:26 Viewed : 604
Implement Swagger with Spring Boot:
To implement Swagger with Spring Boot, you can follow these steps:
pom.xml
file, include the necessary dependencies for Swagger:xml<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Swagger Dependencies -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
javaimport org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
}
Make sure to update the basePackage
value with the package where your controller classes are located.
javaimport io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
@Api(tags = "Sample API")
public class SampleController {
@GetMapping("/hello")
@ApiOperation("Sample Hello API")
public String hello() {
return "Hello, Swagger!";
}
}
http://localhost:8080/swagger-ui.html
in your browser. You should see the Swagger UI interface with documentation for your API endpoints.With Swagger, you can explore and test your API endpoints directly from the Swagger UI interface. It provides a user-friendly way to view and interact with your API documentation.
Note: In newer versions of Swagger (3.x), the @EnableSwagger2
annotation is replaced with @EnableSwagger2WebMvc
.
Remember to customize the Swagger configuration according to your specific requirements. You can add more details, such as descriptions, request/response models, and security configurations, to enhance your API documentation.