1. An overview of the

The company has just been working on documentation for the project, and documentation is critical to building REST apis. In this article, I’ll introduce Spring Doc, a tool based on the OpenAPI 3 specification that simplifies the generation and maintenance of API documentation for Spring Boot 1.x and 2.x applications.

2. Set springdoc – openapi

If you want springdoc-OpenAPI to generate standard OpenAPI 3 documentation for our API, just add the Springdoc-OpenAPI-core dependency to pom.xml:

< the dependency > < groupId > org. Springdoc < / groupId > < artifactId > springdoc openapi - core < / artifactId > < version > 1.1.45 < / version > </dependency>Copy the code

After adding, start the application and access the default path /v3/api-docs to view the document, as shown below:

http://localhost:8080/v3/api-docs/Copy the code

If you want to customize the path, you can specify it in the application.properties file:

springdoc.api-docs.path=/api-docsCopy the code

Thus, the document access path becomes:

http://localhost:8080/api-docs/Copy the code

OpenAPI is defined in JSON format by default. For YAML format, access the following path:

http://localhost:8080/api-docs.yamlCopy the code

3. Integrate SpringDoc-OpenAPI with Swagger UI

In addition to generating the OpenAPI 3 specification ourselves, we can integrate SpringDoc-OpenAPI with Swagger UI so that we can interact with our API specification and test endpoints.

3.1. The Maven dependencies

To integrate SpringDoc-OpenAPI with Swagger UI, the only thing to do is to add springDoc-OpenAPI-UI dependencies to the project pom.xml file.

< the dependency > < groupId > org. Springdoc < / groupId > < artifactId > springdoc openapi - UI < / artifactId > < version > 1.1.45 < / version > </dependency>Copy the code

Visit swagger- UI page:

http://localhost:8080/swagger-ui.htmlCopy the code

You can also customize the access path as above:

springdoc.swagger-ui.path=/swagger-ui-custom.htmlCopy the code

3.2. For example

Suppose there is a ball (Chinese football is sad, so need a ball!!) 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; }}Copy the code

To start the project, access the address in your browser:

http://localhost:8080/swagger-ui-custom.htmlCopy the code

Swagger – UI interface:

! [swagger-ui](https://www.baeldung.com/wp-content/uploads/2019/11/1-swagger-ui.png)

4. Springdoc – OpenAPI integration with Spring WebFlux

We can integrate springDoc-OpenAPI and Swagger UI in the Spring WebFlux project by adding dependencies: SpringDoc-OpenAPI-webflux-UI with SpringDoc-OpenAPI and Swagger UI:

<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-webflux-ui</artifactId> The < version > 1.1.45 < / version > < / dependency >Copy the code

The browser then accesses the address

http://localhost:8080/swagger-ui.htmlCopy the code

Similarly, you can customize the document access path by adding the SpringDoc.Swagger-ui. path configuration item to the application.properties file.

5. Usespringdoc-openapiMaven plug-in

The SpringDoc-OpenAPI library provides the Springdoc-Openapi-Maven-plugin plugin for generating Open API descriptions in JSON or YAML format.

The springdoc-Openapi-maven-plugin relies on the spring-boot-Maven plugin. Maven runs the OpenAPI plug-in during the integration test phase.

So how do you configure the plug-in in POM.xml? Take a look at the following code:

<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.1.8.RELEASE</version> <executions> <id>pre-integration-test</id> <goals> 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>Copy the code

Of course, plugins can also be configured with custom values:

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

Take a closer look at some of the parameters we configured in the plug-in:

  • apiDocsUrl– URL to access a JSON document. The default path is:http://localhost:8080/v3/api-docs
  • outputFileName– The default path for saving definitions is:openapi.json
  • outputDir– Absolute file path – The default value is:${project.build.directory}

6. Use jSR-303 Bean Validation to automatically generate documents

When we use jSR-303 bean Validation annotations in the model, such as @notnull, @NotBlank, @size, @min, @max, etc., SpringDoc-Open API generates constraints for these beans.

Here’s an example:

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

forBallThe document generated by the bean is much richer:

7. Use @controllerAdvice and @responseStatus to generate documentation

In a class annotated with @RestControllerAdvice, using @responseStatus on a method automatically generates a document with a return status code. As in the following class annotated by @controllerAdvice, @responseStatus modifies 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);
    }
}Copy the code

Now we can see in the document that the return status codes are 400 and 404.

Nodule 8.

The Spring Boot version 2.2.x may not be supported at this time, so it is best to use 2.1.x, and Spring Boot version 2.1.8.RELEASE is used in this article.

The above code can be found on my Github, over on Github.

Follow the public account: reply 666