[JAVA] I tried to get started with Swagger using Spring Boot

You will be in charge of the back end and front end within the team, I will be in charge of the front side.

I wanted you to prepare only the API first, so when I tried using Swagger, it was a lot easier.

After investigating how to use it, it seems that there are many ways to do it. I decided to write it down, including the arrangement. This time, I will use Spring Boot to transcribe the design document with a bottom-up approach.

Bottom-up approach: transcribing from source code

The bottom-up approach is to create a Swagger based on the source code. The following two points are good about the bottom-up approach.

--Since the design document is completed based on the source code, it becomes difficult for the document and the code to deviate from each other. --Eliminate the hassle of writing the source code after creating the design document

There is a story like "Isn't it a problem if a rework occurs?" Since only the API mouth is defined first, I think that the work time is not much different from making it as a document.

When I checked this time, it seems that most things can be done with Spring Boot and Swagger, so I wanted to use it positively in the future.

The code created this time can be found at here.

Spring Boot settings

Introducing Spring Fox

By using Spring Fox, the API design document is transcribed from the source code.

To install Spring Fox, it is OK if you solve the following dependencies.

build.gradle


repositories {
  jcenter()
}

dependencies {
    compile "io.springfox:springfox-swagger2:2.9.2"
    compile 'io.springfox:springfox-swagger-ui:2.9.2'  //To use Swagger UI
}

Enable Spring Fox in Spring Boot

SpringBootSwaggerApplication.java


package com.example.springbootswagger;

//import statement omitted

@SpringBootApplication
@EnableSwagger2
public class SpringBootSwaggerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootSwaggerApplication.class, args);
    }

    //Docket is an API provided by Spring Fox. Requires settings to transcribe with Swagger
    @Bean
    public Docket petApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select() // ApiSelector :Select the API to transcribe with Swagger.
                    .paths(PathSelectors.ant("/pets/**")) //Swagger will only wake up anything that matches the specified path
                    .build() //Create ApiSelector
                .useDefaultResponseMessages(false) //It automatically assigns an undefined status code. This time, turn off automatic grant
                .host("springbootswagger.example.com")
                .apiInfo(apiInfo()); //Set API information
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Pet Service")
                .description("This is a pet service api")
                .version("1.0.0")
                .build();
    }
}

If you look at the official guide, here are other settings that return a common response message, You can make security-related settings. This time, the volume will be large, so I will omit it.

When making it into production, it is necessary to set viewing restrictions. How do you do it? Let's check it out next time.

Annotate

Now that the settings for Spring Boot and Spring Fox have been completed, let Swagger actually transcribe them. Annotate various resources.

If you write as follows in the simplest state, you can see the specifications for the time being.

PetResource.java


package com.example.springbootswagger;
//import statement omitted

@RestController
@RequestMapping("/pets")
public class PetResource {

    @GetMapping
    public List<Map<String, String>> pets() {
        return new ArrayList<>();
    }

    @GetMapping("{id}")
    public Map<String, String> pet(@PathVariable String id) {
        return new HashMap<>();
    }

    @PutMapping("{id}")
    public void updatePet(@PathVariable String id) {
        return;
    }

    @PostMapping
    public int insertPet() {
        return 1;
    }

    @DeleteMapping
    public void deletePet() {
        return;
    }
}


Normally, if you add annotations to each resource of the API, It just transcribes it into Swagger. It's amazing.

How to check Swagger UI

When you start the application and access http: //localhost:8080/swagger-ui.html The following screen will be displayed.

swagger-ui_list.png

By the way, even if you don't define swagger-ui.html If gradle resolves the dependency of ʻio.springfox: springfox-swagger-ui: 2.9.2` It seems that it will be generated without permission.

Define Swagger in more detail

If it is the annotation of the Controller layer provided by Spring, It will be reflected in Swagger accordingly. For example, if you add @PathVariable, it will be reflected as follows.

swagger-ui_path-variable.png

There are also essential items. In addition, if you add an annotation provided by Swagger instead of Spring, You will have a more friendly API design document.

Give an overview of each resource

PetResource.java


//import statement omitted

@RestController
@RequestMapping("/pets")
public class PetResource {

    // @Set resource overview with ApiOperation
    @ApiOperation(value = "This Resource fetch all reserved pets")
    @GetMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<PetDto> pets() {
        return new ArrayList<>();
    }
}

swagger-ui_description.png

Add a response pattern

PetResource.java


//import statement omitted

@RestController
@RequestMapping("/pets")
public class PetResource {

    @ApiOperation(value = "This Resource fetch a pet by id")
    //You can define multiple responses with ApiResponses. Required items for code and message.
    @ApiResponses(value = {@ApiResponse(code = 400, message = "Invalid Id supplied", response = ErrorDto.class), @ApiResponse(code = 404, message = "Pet not found")})
    @GetMapping(value = "{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public PetDto pet(@PathVariable String id) {
        return new PetDto();
    }
}

swagger-ui_response.png

Afterword

This time, I omitted the security related items due to the volume. I think I'll summarize it in another article. After that, as I wrote in the middle, it is necessary to devise something that can not be shown in production. I'm curious about how to do it.

I'm using SpringBoot, so should I do something with Spring Security?

References

** Click here for various settings when installing. ** ** http://springfox.github.io/springfox/docs/current/#getting-started

** Click here for Swagger annotations. ** ** https://github.com/swagger-api/swagger-core/wiki/annotations

Recommended Posts

I tried to get started with Swagger using Spring Boot
I tried to get started with Spring Data JPA
I tried to get started with WebAssembly
Get started with Spring boot
I tried GraphQL with Spring Boot
I tried Lazy Initialization with Spring Boot 2.2.0
I tried connecting to MySQL using JDBC Template with Spring MVC
Rails beginners tried to get started with RSpec
I wanted to gradle spring boot with multi-project
I introduced OpenAPI (Swagger) to Spring Boot (gradle) and tried various settings
Getting Started with Spring Boot
I tried to implement file upload with Spring MVC
05. I tried to stub the source of Spring Boot
I started MySQL 5.7 with docker-compose and tried to connect
I tried to reduce the capacity of Spring Boot
I tried to clone a web application full of bugs with Spring Boot
How to get started with slim
I tried using Spring + Mybatis + DbUnit
I tried using JOOQ with Gradle
I tried to interact with Java
How to get started with JDBC using PostgresSQL on MacOS
Message cooperation started with Spring Boot
I tried using Realm with Swift UI
[Note] How to get started with Rspec
Try using Spring Boot with VS Code
I tried using OnlineConverter with SpringBoot + JODConverter
I tried using OpenCV with Java + Tomcat
Asynchronous processing with Spring Boot using @Async
I tried to implement ModanShogi with Kinx
I tried Spring.
[Spring Boot] I want to add my own property file and get the value with env.getProperty ().
Java beginner tried to make a simple web application using Spring Boot
[Note] I want to get in reverse order using afterLast with JdbcTemplate
I used Docker to solidify the template to be developed with spring boot.
I tried to verify AdoptOpenJDK 11 (11.0.2) with Docker image
I tried to make Basic authentication with Java
I tried to manage struts configuration with Coggle
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
I tried to manage login information with JMX
How to use built-in h2db with spring boot
I made blackjack with Ruby (I tried using minitest)
Try to implement login function with Spring Boot
I tried to link JavaFX and Spring Framework.
Try to automate migration with Spring Boot Flyway
[Java] Article to add validation with Spring Boot 2.3.1.
Apply Twitter Bootstrap 4 to Spring Boot 2 using Webjars
I tried to implement a server using Netty
I tried to break a block with java (1)
[Introduction to Spring Boot] Authentication function with Spring Security
I tried Getting Started with Gradle on Heroku
[Java] I tried to connect using a connection pool with Servlet (tomcat) & MySQL & Java
I tried to get the distance from the address string to the nearest station with ruby
Part2 Part II. How to proceed with Getting Started Spring Boot Reference Guide Note ①
[I tried] Spring tutorial
I tried using Gson
I tried using TestNG
I tried Spring Batch
I tried using Galasa
Get started with Gradle
Download with Spring Boot
Settings for connecting to MySQL with Spring Boot + Spring JDBC