I introduced OpenAPI (Swagger) to Spring Boot (gradle) and tried various settings

Introduction

Last year, I created Personal development application called Settlement-kun, but I didn't create the backend API specification, so let's quickly create it using OpenAPI (Swagger). I came to use it. I will touch on the introduction method at that time and the settings that I personally care about.

environment

What is OpenAPI (Swagger)?

The OpenAPI Specification, originally known as the Swagger Specification, is a specification for machine-readable interface files for describing, producing, consuming, and visualizing RESTful web services.

(Translation) The OpenAPI Specification is a specification of machine-readable interface files for describing, generating, consuming, and visualizing RESTful web services.

From wikipedia

So, to put it simply, OpenAPI is an interface for creating specifications for RESTful Web services (API, etc.). Originally the name was Swagger, but it seems that the name has changed to Open API because it was donated to OAI (Open API Initiative) established by Microsoft/Google/IBM on December 31, 2015. SmartBear Software, the creator of Swagger, also participated in OAI, and it seems that it was donated. However, since OpenAPI has not yet become popular as a name, there are still people and articles that call it Swagger.

Introduced OpenAPI (Swagger) to Spring Boot

There are several ways to introduce OpenAPI into Spring Boot. Among them, this time we will introduce using SpringFox. SpringFox is a library of Spring Framework that can create OpenAPI-based specification documents. https://github.com/springfox/springfox

Defined in gradle

Describe the following description in build.gradle.

build.gradle


~abridgement~
dependencies {
        compile("io.springfox:springfox-swagger2:${Version of your choice}")
        compile("io.springfox:springfox-swagger-ui:${Version of your choice}")
~abridgement~
}

For $ {your favorite version}, specify the version you want to use. The version that can be specified in the link below and its usage rate are described.

springfox-swagger2 springfox-swagger-ui

Create Configure class

Use the AutoConfigure function of SpringBoot to load the settings. Create the following Configure class.

SwaggerConf.java


package com.dededesignworkshop.seisankun_api.config;

import 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 SwaggerConf {

    @Bean
    public Docket swaggerPlugin() {
        return new Docket(DocumentationType.SWAGGER_2) // SWAGGER_12, SWAGGER_2, SWAGGER_I have a WEB but I don't really know which one is better
                .select() //Generate ApiSelectorBuilder
                .apis(RequestHandlerSelectors.any()) //Set the RequestHandler that is the target of the document
                .paths(PathSelectors.regex("/v1.*")) //Set the target path of the document
                .build();
    }

}

A class called Docket is defined as a bean. The official document is here, so please take a look at the other setting items as well.

Browser display

When you access the path of /swagger-ui.html, the following will be displayed. スクリーンショット 2021-01-01 23.41.59.png

Various settings

There is no problem with the above Bean definition as the minimum setting, but there are many other customizations, so I tried it.

API basic information setting

You can set basic API information with apiInfo () of Docket. This is the red frame part of the image. スクリーンショット 2021-01-02 0.08.43.png

Add the following to the Configure class above.

SwaggerConf.java


~abridgement~

@Configuration
@EnableSwagger2
public class SwaggerConf {

    @Bean
    public Docket swaggerPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("/v1.*"))
                .build()
                .apiInfo(getApiInfo()); //API basic information setting with ApiInfo type
    }

    private ApiInfo getApiInfo() {
        return new ApiInfoBuilder()
                .title("Seisankun-api")
                .description("Travel split calculation app\"Liquidation\"API")
                .version("1.0.0")
                .contact(new Contact("nooboolean","webSiteUrl","email"))
                .build();
    }
}

The official document is here, so please see other setting items as well.

Advanced settings for each endpoint

By defining a bean that returns the UiConfiguration class in UiConfigurationBuilder, detailed settings for each endpoint can be made. You can set the following screens. スクリーンショット 2021-01-02 0.42.10.png

Add the following to the Configure class above.

SwaggerConf.java


~abridgement~

@Configuration
@EnableSwagger2
public class SwaggerConf {

~abridgement~

    @Bean
    public UiConfiguration swaggerUiConf() {
        return UiConfigurationBuilder.builder()
                .displayRequestDuration(true)
                .defaultModelExpandDepth(3)
                .defaultModelRendering(ModelRendering.EXAMPLE)
                .filter(true)
                .operationsSorter(OperationsSorter.METHOD)
                .validatorUrl("")
                .docExpansion(DocExpansion.LIST)
                .build();
    }
}

Details of the items set this time.

Setting items Explanation
displayRequestDuration RequestDuration when API is executed on OpenAPI(Response time)You can set whether or not to display.
defaultModelExpandDepth The structure of the specific value of the response described in the details of Responses(Model)When writing, you can set up to what level you want to keep it open without folding.
defaultModelRendering The default notation of the specific value of the response described in the details of Responses should be "Example of value" or "Structure".(Model)You can choose whether to set it to.
filter You can set the need for filter fields that allow you to filter endpoints.
operationsSorter You can set the order of the endpoints. This time, the order of methods is used.
docExpansion You can set how far the hierarchical endpoint display opens by default.
validatorUrl You can set validationUrl. By disablinglike thisYou can avoid the problem.

The official document is here, so please take a look at the other setting items as well.

Setting a description for each endpoint

You can write a description of what role each endpoint plays. This is possible by annotating the method of each endpoint with ApiOperation.

UserController.java



    @ApiOperation(value = "Refer to the user list associated with travel", notes = "Refers to the user list associated with the travel ID specified in the parameter")
    public List<User> findByTravelId(@PathVariable("travel_id") Integer travel_id) {
        return this.userService.findByTravelId(travel_id);
    }

The display results are as follows. スクリーンショット 2021-01-02 1.24.43.png

There seems to be more customization, so I will add it each time I customize it additionally! !!

Recommended Posts

I introduced OpenAPI (Swagger) to Spring Boot (gradle) and tried various settings
I tried to get started with Swagger using Spring Boot
Add spring boot and gradle to eclipse
I tried to link JavaFX and Spring Framework.
I wanted to gradle spring boot with multi-project
05. I tried to stub the source of Spring Boot
I tried to verify this and that of Spring @ Transactional
I tried GraphQL with Spring Boot
I tried Flyway with Spring Boot
I tried printing a form with Spring MVC and JasperReports 1/3 (JasperReports settings)
I introduced WSL2 + Ubuntu to Window10 and tried using GDC, DMD, LDC
I tried to link grafana and postgres [docker-compose]
Various correspondence table of Spring Framework and Spring Boot
I tried Spring.
I tried to clone a web application full of bugs with Spring Boot
I tried to create a shopping site administrator function / screen with Java and Spring
Plans to support JDK 11 for Eclipse and Spring Boot
Settings for connecting to MySQL with Spring Boot + Spring JDBC
I tried to implement file upload with Spring MVC
I tried to read and output CSV with Outsystems
I started MySQL 5.7 with docker-compose and tried to connect
I tried to integrate AWS I oT button and Slack
Spring Boot with Spring Security Filter settings and addictive points
I tried to get started with Spring Data JPA
I tried to summarize various link_to used this time
Attempt to SSR Vue.js with Spring Boot and GraalJS
Connect Spring Boot and Angular type-safely with OpenAPI Generator
I tried to chew C # (reading and writing files)
[I tried] Spring tutorial
I tried Spring Batch
How to change application.properties settings at boot time in Spring boot
What I fixed when updating to Spring Boot 1.5.12 ・ What I was addicted to
I tried to collect and solve Ruby's "class" related problems.
I tried to summarize the basics of kotlin and java
Spring Boot Introductory Guide I tried [Accessing Data with JPA]
I tried to make Java Optional and guard clause coexist
How to call and use API in Java (Spring Boot)
Connect to database with spring boot + spring jpa and CRUD operation
I tried to summarize personally useful apps and development tools (development tools)
I tried to summarize personally useful apps and development tools (Apps)
I want to implement various functions with kotlin and java!
8 things to insert into DB using Spring Boot and JPA
Try Spring Boot from 0 to 100.
Gradle to touch and remember
Spring Boot 2 multi-project in Gradle
I tried Spring State machine
Spring Boot Hot Swapping settings
Introduction to Spring Boot ① ~ DI ~
Introduction to Spring Boot ② ~ AOP ~
Spring Boot performance related settings
Introduction to Spring Boot Part 1
I tried to verify yum-cron
I tried Spring Boot introductory guide [Building a RESTful Web Service]
I tried printing a form with Spring MVC and JasperReports 3/3 (Spring MVC control)
Introduction to Spring Boot x OpenAPI ~ OpenAPI made with Generation gap pattern ~
I tried to integrate Docker and Maven / Netbean nicely using Jib
02. I made an API to connect to MySQL (MyBatis) from Spring Boot
I tried connecting to MySQL using JDBC Template with Spring MVC
I tried to create a Spring MVC development environment on Mac
What I did in the migration from Spring Boot 1.4 series to 2.0 series
How to make CsrfRequestDataValueProcessor and original RequestDataValueProcessor coexist on Spring Boot