Swagger is a popular tool for building, documenting, and testing RESTful APIs. Swagger UI provides a visual representation of the API, making it easier for developers to understand and consume the API.
To enable Swagger in a Spring Boot application, you need to add the following dependencies to your pom.xml
file:
1 2 3 4 5 6 7 8 9 10 11 12 |
<dependency> <groupid>io.springfox</groupid> <artifactid>springfox-swagger2</artifactid> <version>2.9.2</version> </dependency> <dependency> <groupid>io.springfox</groupid> <artifactid>springfox-swagger-ui</artifactid> <version>2.9.2</version> </dependency>  |
Next, create a configuration class for Swagger. For example, SwaggerConfig.java
:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } |
In the configuration class, you specify the type of documentation you want to generate (in this case, SWAGGER_2
), and define which controllers and routes should be included in the documentation using the RequestHandlerSelectors
and PathSelectors
classes.
To test your Swagger configuration, start your Spring Boot application and navigate to http://localhost:8080/swagger-ui.html
in your browser. You should see a UI that allows you to explore your API and test the different endpoints.
Here is an example of a simple car REST API using Swagger:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
@<code>RestController @RequestMapping("/api/cars") public class CarController { @GetMapping public List<Car> getAllCars() { // Implementation goes here } @GetMapping("/{id}") public Car getCarById(@PathVariable long id) { // Implementation goes here } @PostMapping public Car createCar(@RequestBody Car car) { // Implementation goes here } @PutMapping("/{id}") public Car updateCar(@PathVariable long id, @RequestBody Car car) { // Implementation goes here } @DeleteMapping("/{id}") public void deleteCar(@PathVariable long id) { // Implementation goes here } } |
1 2 3 4 5 6 7 8 |
public class Car { private Long id; private String make; private String model; private int year; // Getters and setters } |