In this tutorial, you will learn using Swagger and SpringFox to create REST API Documentation in Spring Boot. Let's reuse the code base of Mapping JPA/Hibernate Entity and DTO with MapStruct

What you'll need

  • JDK 8+ or OpenJDK 8+
  • Maven 3+
  • MySQL Server 5+ or Docker CE 18+

Project structure

Setting up Swagger with SpringFox

Add Swagger and Swagger UI dependency into pom.xml .

<properties>  
    <io.springfox.version>2.7.0</io.springfox.version>
</properties>

...

<dependency>  
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${io.springfox.version}</version>
</dependency>

<dependency>  
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${io.springfox.version}</version>
</dependency>

...

Configure Swagger

To use Swagger you have to inject @EnableSwagger2 annotation and declare a Docket bean

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

Run with Docker

Prepare Dockerfile for Java/Spring Boot application and docker-compose.yml for MySQL Server



Type the below command at the project root directory, make sure your local Docker is running

docker-compose up  

Run with JDK/OpenJDK, Maven and MySQL Server local

Update hk-mysql on application.properties to localhost and type the below command at the project root directory

mvn clean spring-boot:run  

Testing tine

Access to http://localhost:8080/swagger-ui.html to see REST API Documentation by Swagger UI

Try to make a POST to /api/v1/products to create a new product

Try a GET request to /api/v1/products to get product list

Source code

https://github.com/hellokoding/hellokoding-courses/tree/master/springboot-examples/restful-api/springboot-swagger