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

  • 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 the application

Prepare Dockerfile for Java/Spring Boot application


Start your application and infrastructure via Docker Compose. Make sure your local Docker is running and your bash console is at the springboot-examples project root directory.

docker-compose -f docker-compose-restful.yaml up --renew-anon-volumes springboot-swagger

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

That's it! Thanks for joining and have a happy coding. You can find the full source code as below

Source code

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