Spring Boot: Spring Doc document generation OpenAPI3.0

1 Overview

The company just recently in finishing the project document, and the document is essential for building a REST API for. In this article, I will describe Spring Doc, based on a OpenAPI 3specification simplifies Spring Boot 1.xand 2.xAPI documentation generation application and tool maintenance.

2. Set springdoc-openapi

If you want springdoc-openapi generation standard for our API OpenAPI 3 documents, just add springdoc-openapi-core depend to pom.xml :

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-core</artifactId>
    <version>1.1.45</version>
</dependency>

After the addition is complete, start the application, you can access the default path /v3/api-docsto view the documents as follows:

http://localhost:8080/v3/api-docs/

If you want to customize the path, can application.properties specified file:

springdoc.api-docs.path=/api-docs

In this way, the access path of the document becomes:

http://localhost:8080/api-docs/

openapi3

OpenAPI is defined as the default JSON format. For yaml format, you can get access to the following path:

http://localhost:8080/api-docs.yaml

3. Integration springdoc-openapi and Swagger UI

In addition to generating its own OpenAPI 3norms, we can also springdoc-openapiwith Swagger UIintegrated, so that you can interact with our API specification and test endpoints.

3.1. Maven relies

To integrate springdoc-openapiand Swagger UIthe only thing to do is add a springdoc-openapi-uidependent to the project pom.xml file.

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.1.45</version>
</dependency>

Access swagger-ui page:

http://localhost:8080/swagger-ui.html

Of course you can as above, custom access path:

springdoc.swagger-ui.path=/swagger-ui-custom.html

3.2. For chestnuts

Suppose there are balls (Orangemen sad, so need a ball ah !!) the controller.

@RestController
@RequestMapping("/api/ball")
public class BallController {
 
    @Autowired
    private BallRepository repository;
 
    @GetMapping("/{id}")
    public Ball findById(@PathVariable long id) {
        return repository.findById(id)
            .orElseThrow(() -> new BallNotFoundException());
    }
 
    @GetMapping("/")
    public Collection<Book> findBooks() {
        return repository.getBooks();
    }
 
    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public Book updateBook(@PathVariable("id") final String id, @RequestBody final Book book) {
        return book;
    }
}

Start the project, visit the address in your browser:

http://localhost:8080/swagger-ui-custom.html

swagger-ui interface:

swagger-ui

4. springdoc-openapi integrated with Spring WebFlux

We can add dependencies in Spring WebFlux project: springdoc-openapi-webflux-uiwith springdoc-openapiand Swagger UIintegration:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-webflux-ui</artifactId>
    <version>1.1.45</version>
</dependency>

Then, access the browser address

http://localhost:8080/swagger-ui.html

Similarly, by adding springdoc.swagger-ui.path configuration items to application.properties file to customize the document access path.

5. Use the springdoc-openapiMaven plugin

springdoc-openapiLibrary provides springdoc-openapi-maven-plugin plug, or used to generate yaml Open API JSON format description.

springdoc-openapi-maven-plugin depends on the spring-boot-maven plugin. Maven run openapi plug-in integration testing phase.

So, how pom.xmlto configure plug it in? Consider the following code:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>2.1.8.RELEASE</version>
    <executions>
        <execution>
            <id>pre-integration-test</id>
            <goals>
                <goal>start</goal>
            </goals>
        </execution>
        <execution>
            <id>post-integration-test</id>
            <goals>
                <goal>stop</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-maven-plugin</artifactId>
    <version>0.2</version>
    <executions>
        <execution>
            <phase>integration-test</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Of course, the values ​​may be custom configured widget:

<plugin>
    <executions>
        .........
    </executions>
    <configuration> 
        <apiDocsUrl>http://localhost:8080/v3/api-docs</apiDocsUrl> 
        <outputFileName>openapi.json</outputFileName> 
        <outputDir>${project.build.directory}</outputDir> 
    </configuration>
</plugin>

A closer look at a few parameters we configured in the plug-in:

  • apiDocsUrl - json format to access the URL of the document, the default path: HTTP: // localhost: 8080 / v3 / API-docs
  • outputFileName - store the path defined by default: openapi.json
  • outputDir - the absolute path of the document storage - default is: $ {} project.build.directory

Automatic generation of documentation 6. Use JSR-303 Bean Validation

When we use JSR-303 bean validation annotations in the model, such as @NotNull , @NotBlank , @Size , @min , @max the like, springdoc-openapi generates corresponding constraint for these bean.

For chestnut:

public class Ball {
 
    private long id;
 
    @NotBlank
    @Size(min = 0, max = 20)
    private String title;
 
    @NotBlank
    @Size(min = 0, max = 30)
    private String author;
 
}

As Ball bean-generated content of the document richer:
schema

7. Use @ControllerAdvice and generate documentation @ResponseStatus

In @RestControllerAdvice annotated classes, used in the method @ResponseStatus automatically generated document with the returned status code. As the @ControllerAdviceannotated classes, @ResponseStatus modified two methods:

@RestControllerAdvice
public class GlobalControllerExceptionHandler {
 
    @ExceptionHandler(ConversionFailedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> handleConnversion(RuntimeException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
    }
     
    @ExceptionHandler(BallNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<String> handleBallNotFound(RuntimeException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}

Now we can see in the document returns a status code of 400 and 404.
not-found

8. Summary

Spring Boot 2.2.x version may not support the current, so it is best to use when using 2.1.x, as used herein, Spring Boot version 2.1.8.RELEASE.

The above code can be found in my github, over ON GitHub .


No public concern: Re translation of the article 666 to receive benefits:
img

Guess you like

Origin www.cnblogs.com/liululee/p/11925987.html