Swagger generated JavaDoc

In daily work, especially in the present front and back end separation mode, the provision of interface has caused a large increase in the communication cost of our front and back end developers, because the communication is not in place, the timely [coin tearing] events have become daily work. Especially a lot of developers are not good at communication, resulting in the result will make their own special pain, but also let the partners hate the root of the tooth itch. Swagger was born to end the war and improve developer satisfaction.

What is a Swagger

Swagger for Everyone

Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset.

Swagger open source and pro tools have helped millions of API developers, teams, and organizations deliver great APIs.

In short, this means using a toolset to simplify API development for users, teams, and enterprises.

  • Official portal
  • Source code portal
  • Swagger – UI portal
  • Extension component Swagger-spring-boot-starter portal
  • Extended UI component Swagger-Bootstrap-UI portal

Integrated Swagger

In the system, I choose swagger-spring-boot-starter.

This project mainly uses the automatic configuration feature of Spring Boot to realize the rapid introduction of Swagger2 into Spring Boot application to generate API documents and simplify the integration code of using Swagger2 native. I can see that I am teaching everyone to use is lazy oh, this is not a good sign…

Add the dependent

<! Swagger2--> <dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> < version > 1.9.0. RELEASE < / version > < / dependency >Copy the code

Click on the version number into the swagger – spring – the boot – starter / 1.9.0 RELEASE/swagger – spring – the boot – starter – 1.9.0. The pom, can see that it depends on the version information.

< the properties > < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > < version. Java > 1.8 < / version. Java > < version swagger > 2.9.2 < / version. The swagger > < version. The spring - the boot > 1.5.10. RELEASE < / version. The spring - the boot > < version lombok > 1.18.6 < / version. Lombok > < / properties >Copy the code

Enable the function

Add the @enablesWagger2doc annotation to our startup class ApiApplication

@SpringBootApplication @MapperScan(basePackages = "com.liferunner.mapper") @ComponentScan(basePackages = {"com.liferunner", "Org.n3r.idworker "}) @enablesWagger2doc public Class ApiApplication {public static void main(String[] args)  { new SpringApplicationBuilder() .sources(ApiApplication.class) .run(args); } @Autowired private CORSConfig corsConfig; /** * Register cross-domain configuration information ** @return {@link CorsFilter} */ @bean public CorsFilter CorsFilter () {val corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin(this.corsConfig.getAllowOrigin()); corsConfiguration.addAllowedMethod(this.corsConfig.getAllowedMethod()); corsConfiguration.addAllowedHeader(this.corsConfig.getAllowedHeader()); corsConfiguration.setAllowCredentials(this.corsConfig.getAllowCredentials()); val urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration); return new CorsFilter(urlBasedCorsConfigurationSource); }}Copy the code

Configuring Basic Information

This can be configured through the properties file and the YML/YAML file.

# Configure swagger2 Swagger: enabled: true # Enable swagger, default: true 1.0.0.RC License: Apache License, Version 2.0 license- URL: https://www.apache.org/licenses/LICENSE-2.0.html terms - of - service - the url: http://www.life-runner.com contact: email: [email protected] name: Isaac-Zhang url: http://www.life-runner.com base-package: com.liferunner base-path: /**Copy the code

Stage Effect I

Run our API project and type in your browser:http://localhost:8088/swagger-ui.html, you can see the following:As you can see, we areymlThe information configured in the file is displayed at the top of the page. ClickUser management:As you can see from the figure above, our/users/createThe interface is displayed, and the parameters to be passed in, the request type, and so on are shown in the figure above. But what does it mean to pass parameters that are all our field information, and how do we make it more user-friendly to the caller? Let’s continue to refine our documentation information:

Complete description information

When we create a user, need to pass a com. Liferunner. Dto. UserRequestDTO object, the object’s properties are as follows:

@restController @requestMapping (value = "/users") @slf4j @API (tags = "User management ") Public class UserController {@autoWired private IUserService userService; @apiOperation (value = "user details ", notes =" query user ") @apiignore @getMapping ("/get/{id}") // @getMapping ("/{id}") Public String getUser(@pathVariable Integer ID) {return "Hello, life."; } @apiOperation (value = "create user ", @postMapping ("/create") public JsonResponse createUser(@requestBody UserRequestDTO UserRequestDTO) { / /... }}Copy the code

Constructor @noargsconstructor @apiModel (value = "create user DTO", Public class UserRequestDTO {@apiModelProperty (value = "username", notes = "username", example = "isaaczhang", required = true) private String username; @APIModelProperty (value = "register password", notes = "password", example = "12345678", required = true) private String password; @apiModelProperty (value = "confirm password ", notes = "confimPassword", example = "12345678", required = true) private String confirmPassword; }Copy the code

As you can see, we have a lot of annotations beginning with @apixxx. This is the annotation Swagger provides for us to explain fields and documentation.

  • @ApiProvides an API externally
  • @ApiIgnoreIndicates that it is not displayed and can be used for classes and methods
  • @ApiOperationA CURD action under an API
  • @ApiResponsesDescribes the exceptions that may occur during the operation
  • @ApiParamDescribes the single parameter information to be passed
  • @ApiModelA property description used to describe a Java Object
  • @ApiModelPropertyDescription Object Field description

    For all of these, it’s easy to go to the specific class of the associated annotation to view all the attribute information, which is not described here. To see more property descriptions,

    You can enter:Swagger Property Description Portal.

After the configuration, restart the application and refresh the UI page:The red boxes in the picture above are the instructions for our reconfiguration, which is simple enough

Integrate better UI interface

For API specification, our above information is good enough, but do technology, we should pursue is more extreme, the above UI interface when we provide mass user interface, there is a little bit of a lack of friendly, now let us introduce a better open sourceSwagger UI, please welcomeswagger-bootstrap-ui.As you can see from the figure above, this UI has more than 1.1K stars, which proves it’s pretty good. Let’s see what it really is.

Integration depends on

Just add the following dependency code to our expense-shoppom.xml:

<! <dependency> <groupId>com.github. Xiaoymin </groupId> <artifactId> Swagger -bootstrap-ui</artifactId> The < version > 1.6 < / version > < / dependency >Copy the code

preview

After adding dependencies, we just need to restart our application and accesshttp://localhost:8088/doc.html, the effect is as follows:Click Create user:The above effect is not more in line with our aesthetic ~ so far, we useSwaggerThe effects of dynamically generating the API have all been demonstrated, but what if one day we need to integrate with a customer who can’t connect to view our site? Or should I hand write them a document? That we are not the same very painful!! As programmers, we can’t allow this to happen! So let’s keep watching.

Generate offline documents

Is there a way to generate an offline document that will save us the pain of adding so much specification to the code? The answer is yes.

Open source project Swagger2Markup

A Swagger to AsciiDoc or Markdown converter to simplify the generation of an up-to-date RESTful API documentation by combining documentation that’s been hand-written with auto-generated API documentation.

Source portal Documents Portal

Swagger2Markup is primarily used to convert Swagger’s automatically generated documents into several popular formats for offline use

Format: AsciiDoc, HTML, Markdown, Confluence

Use the MAVEN plug-in to generate AsciiDoc documents

Add the following dependency code to mscX-shop-apipom.xml:

<build> <plugins> <! <plugin> <groupId> IO. Github. Swagger2markup </groupId> < artifactId > swagger2markup -- maven plugin < / artifactId > < version > 1.3.3 < / version > < configuration > <! B: This is to launch our project. Then grab the API docs returned results - - > < swaggerInput > http://localhost:8088/v2/api-docs < / swaggerInput > <outputDir>src/docs/asciidoc/generated-doc</outputDir> <config> <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage> </config> </configuration> </plugin> </plugins> </build>Copy the code
  • http://localhost:8088/v2/api-docsIt was to get ourapi JSONData, as shown below:

  • src/docs/asciidoc/generated-docSet the directory address we want to generate

Execute command:

expensive-shop\mscx-shop-api>mvn swagger2markup:convertSwagger2markupCopy the code

If the order seems too long, Can also click ` IDEA = > Maven = > MSCX – shop – API = > Plugins = > swagger2markup = > swagger2markup: convertSwagger2markup ` can perform, the diagram below:The result is as follows:Now that the adoc file is generated, let’s use it to generate HTML

Use the MAVEN plugin to generate HTML

Add the following dependency code to mscX-shop-apipom.xml:

<! Asciidoctor </groupId> <artifactId> maven-plugin</artifactId> The < version > 1.5.6 < / version > < configuration > < sourceDirectory > SRC/docs/asciidoc/generated - doc < / sourceDirectory > <outputDirectory>src/docs/asciidoc/html</outputDirectory> <backend>html</backend> <sourceHighlighter>coderay</sourceHighlighter> <attributes> <toc>left</toc> </attributes> </configuration> </plugin>Copy the code

  • src/docs/asciidoc/generated-docThe source file directory is specified as the ADOC we generated in the previous section
  • src/docs/asciidoc/htmlSpecify the output directory

Execute build command:

\expensive-shop\mscx-shop-api>mvn asciidoctor:process-asciidocCopy the code

The result is as follows:Open theoverview.htmlThat is as follows:

At this point, our documentation is all generated!

Next day forecast

In the next section, we will continue to develop our user login and part of the home page information display, in the process of using any development components, I will be introduced through a special section, brothers end panic!

Gogogo!!!

Running life garden | | blog segmentfault | spring4all | CSDN Denver | | OSChina book | | Jane headlines | zhihu | 51 cto