Implement Swagger with Spring Boot

Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-07-10 02:01:26 Viewed : 311

Implement Swagger with Spring Boot:

To implement Swagger with Spring Boot, you can follow these steps:

  1. Add Dependencies: In your pom.xml file, include the necessary dependencies for Swagger:
<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>
  1. Enable Swagger Configuration: Create a configuration class to enable Swagger and configure its properties:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import; import; 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.

  1. Annotate Controllers: Add Swagger annotations to your controller classes and methods to provide additional information:
import 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!"; } }
  1. Run the Application: Run the Spring Boot application. Access the Swagger UI by visiting 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.

Related Articles

Leave a Comment: