Knife4j 2.0.6 released, supporting OpenAPI3 and Auth2 authentication

Knife4jThe predecessor is swagger-bootstrap-uia tool that empowers Swagger interface documents

Keywords : OpenAPI3 , Auth2.0 , AfterScript , Springfox3.0 , enhancement and improvement

Document : https://doc.xiaominfo.com

Effect (old version) : http://swagger-bootstrap-ui.xiaominfo.com/doc.html

Effect (version 2.X) : http://knife4j.xiaominfo.com/doc.html

Giteehttps://gitee.com/xiaoym/knife4j

GitHubhttps://github.com/xiaoymin/swagger-bootstrap-ui

Example : https://gitee.com/xiaoym/swagger-bootstrap-ui-demo

Features & optimization

2.0.6 is to continue the iterative update in the previous version. Developers can use the structure of OpenAPI2 to directly modify the version number to upgrade. The springfox framework is upgraded to2.10.5

Springfox 2.10.5 version changes:

1. The spring-plugin component is upgraded to 2.0.0, and the guava package is removed

2. @EnableSwagger2 annotation is upgraded to @EnableSwagger2WebMvc

Maven quote:

< dependency > 
    < groupId > com.github.xiaoymin </ groupId > 
    < artifactId > knife4j-spring-boot-starter </ artifactId > 
    <!--Developers of OpenAPI2.0 continue to use the version of the Knife4j 2.x series-- > 
    < version > 2.0.6 </ version > 
</ dependency >

1. OAuth2 authentication function support: simplified mode (implicit), authorization code mode (authorization_code), password mode (password), client mode (client_credentials) , please refer to the document for detailed rules

2. Regarding @RequestBodythe request entity class marked with annotations, whether it is necessary requireto display abnormality when requesting parameters in the interface Gitee #I1VBGBGitee #I1YK2QGitee #I1WCMFGitee #I1VDSHGitHub #277

3. consumesOptimize for the situation specified by the server . If the server does not specify, Ui will adapt according to the parameter type by default. Gitee #I1VE25

4. Solve the problem that the interface address of the document interface is abnormal after Docketassigning Hostattributes when creating an object Gitee #I1XYG9

5. When the microservice gateway aggregates documents, the custom group name causes the enhancement failure Gitee #I1Y79W

6. For the querytype of parameter, if the parameter is a schema type, parse the schema to json and provide the requested value. Gitee #I1VLHH , as shown below:

  • Document display:

  • Debug effect:

7. New AfterScriptfeatures in the debug bar , developers can Knife4jwrite custom JavaScriptscripts based on defined global variables to enhance the interface interaction experience Gitee #I1YNU3Gitee #I1CAAD , AfterScriptplease refer to the documentation for features

Main application scenarios:

  • For JWT-type interfaces, after calling the login interface, each interface request is brought with the Token parameter. At this time, the global token parameter can be dynamically assigned through the script, saving the trouble of copying and pasting.

Assume that the JSON content of a login interface response is as follows:

{
  "code": 8200,
  "message": null,
  "data": {
    "token": "1y1tn8tvw93fxixp79dcx0nugixkw4su"
  }
}

This interface is a login interface. All requests except this interface need to bring tokenrequest headers. Therefore, after accessing the login interface, we set the global Header parameters token. This operation Knife4jwill then bring tokenparameters for each request interface . The code is as follows:

var  code = Response . Data . code ;
 IF ( code == 8200 ) {
     // determine if the server in response to the operation code is performed before 8200 
    // get token 
    var  token = Response . Data . Data . token ;
     //. 1, If the parameter is Header, set the global Header 
    ke . Global . SetHeader ( "token" , token );
}

8. When setting globalOperationParametersglobal parameters when creating a Docket object , the headertype allowableValuesdoes not support drop-down box selection Gitee #I1OC0H

code show as below:

parameters.add(new ParameterBuilder().name("header-test").description("balabala")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .allowableValues(new AllowableListValues(Arrays.asList("下拉1", "下拉2"), "string"))
                .required(false).order(1).build());
new Docket(DocumentationType.SWAGGER_2)
                .host("https://www.baidu.com")
                . apiInfo ( apiInfo ())
                . groupName ( "2.X version" )
                .globalOperationParameters(parameters)

final effect:

9. The offline export function section adds to export the original JSON format data of OpenAPI, and export the original json format of OpenAPI of all interfaces under this logical grouping. As shown below:

10. For a single interface, the OpenAPI source code format is provided, which can be directly imported into POSTMAN for testing by copying or downloading the source code format Gitee #I1Z7AP . As shown below:

11. Enhanced annotations @EnableKnfie4jincrease the Conditional conditions in Spring Boot, which are @ConditionalOnWebApplicationonly loaded in the Web environment to avoid junitexceptions when using unit tests.

12. There are two main changes in the enhancement mode. For more detailed usage rules , developers please refer to the documentation :

  • Provide spring.factoriesautomatic device, developers can directly use the Spring Boot configuration file ymlor propertyother properties knife4j.enable:truefor use, no need to use @EnableKnife4jannotations after configuring properties

  • Provide a spring-configuration.meta.jsonfile Knife4jto annotate each enhanced configuration attribute provided, so that developers can configure in the configuration file, as shown below:

13. For the configuration of other documents, the developer can configure the Docket according to each logical grouping, and other documents support the group title of the custom document

14. There is no need to check and enhance the UI interface for interface ordering requirements. You only need to open the knife4j.enable=trueinterface in the configuration file , and then use @ApiSupportannotations or use it @ApiSorton the Controllerclass. Priority @ApiSupport>@ApiSort. This method is more integrated with the characteristics of the springfox framework and is more in line with the extension For the specification of attribute extension, add x-orderextended parameters to the OpenAPI structure node , as shown in the figure below:

15. Remove the enhanced extended interface address /v2/api-docs-ext, personalized configuration and enhancement can be configured through the back-end configuration file, and through more standardized use of enhanced annotations, it conforms to the extended attribute specification of OpenAPI.

16. Other documents are displayed in accordance with the extension specifications of OpenAPI. Developers can configure multiple grouping documents ( 前提是knife4j.enable=true) in the yml configuration file , and then Docketuse the Knife4jprovided OpenApiExtensionResolverextensions in the created objects extension. The final configured md file will be in the document Group presentation. GitHub #115

application.ymlThe configuration example code is as follows:

knife4j:
  enable: true
  documents:
    -
      group : 2.X version
       name : interface signature
       locations : classpath : sign/*
    -
      group : 2.X version
       name : For other document grouping please see here
       locations : classpath : markdown/*

Java code:

@Configuration
@EnableSwagger2WebMvc
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfiguration {
 
   private final OpenApiExtensionResolver openApiExtensionResolver;
    @Autowired
    public SwaggerConfiguration(OpenApiExtensionResolver openApiExtensionResolver) {
        this.openApiExtensionResolver = openApiExtensionResolver;
    }
    
    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        String groupName="2.X版本";
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .host("https://www.baidu.com")
                . apiInfo ( apiInfo ())
                .groupName(groupName)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.swagger.bootstrap.ui.demo.new2"))
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                . build ()
             //Call the method of openApiExtensionResolver here to get the extensions collection 
                . extensions ( openApiExtensionResolver . buildExtensions ( groupName ))
                .securityContexts(CollectionUtil.newArrayList(securityContext())).securitySchemes(CollectionUtil.newArrayList(apiKey()));
        return docket;
    }
}

Final UI interface renderings:

17. Regarding the use of @ApiModelPropertyannotations, examplethe issue of giving an example value json string to the attribute field of the entity String type is displayed abnormally GitHub #233

18. The problem of the loss of precision of the long plastic in the request example and the response example GitHub #269

19. When there is Authorze authentication on the current interface, the parameters will not default to the bug in interface debugging when the function is not clicked, and the query type parameters always appear in the parameter column of the request header Gitee #I1VC4I

20. Remove the enable enhanced configuration in the personalized settings in the UI interface.

21. The problem of missing dynamic response fields when using enhanced annotations @ApiOperationSupportand @DynamicResponseParameterssimultaneous use Gitee #I22K0R

22. The problem of offline document download failure, variable reference error causes Gitee #I1W5UB

OpenAPI3

If developers want to use springfox's OpenAPI3 version, Knife4j has released two versions this time. For version 3.0, Knife4j upgrades the springfox components to the bottom layer springfox3.0.0, and the version number starts from the 3.xseries, representing OpenAPI3 to distinguish the 2.xseries.

Maven reference

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <!--如果想使用springfox3.0及OpenAPI3请用3.x版本-->
    <version>3.0</version>
</dependency>

For the version of SpringFox3.0, although the author supports OpenAPI3 on ​​Ui during the development process, there are still many problems with springfox3.0. It is recommended that developers use springfox3 with caution. Regardless of the support for OpenApi2 and OpenApi3, springfox3 currently has some problems in compatibility and other aspects. After all, a version has just been released.

Relatively speaking, the version of the springfox2.x series is relatively stable. When the structure of Springfox is relatively stable for 3.0, the main branch version of Knife4j will move closer to 3.0.

Related ISSUES:

Features

  • Documents built based on Vue+Ant Design, stronger and clearer interface documentation description capabilities and interface debugging capabilities

  • Left and right layout, multi-document lookup style based on Tabs component

  • Support online export of offline documents in various formats such as Html, Markdown, Word, PDF, etc.

  • Interface sorting, support grouping and interface sorting function

  • Support interface global online search function

  • Provide Swagger resource protection strategy to protect document security

  • Interface debugging supports unlimited parameters, developers are very flexible in debugging, adding and deleting parameters dynamically

  • Debugging information is cached globally, it still exists after the page is refreshed, which is convenient for developers to debug

  • Show Swagger Models functions with a more user-friendly table tree component

  • Documents can display multiple interface documents in multiple tabs

  • Request parameter column request type, whether it must be filled in with color

  • Roughly count the number of different types of interfaces in the homepage

  • Support custom global parameter function, homepage includes header and query two types

  • JSR-303 annotations support

  • More personalized settings

interface

The interface document display interface is as follows:

The interface debugging interface is as follows:

Swagger Models features

It supports the export of offline Markdown and Html functions. Compared with the original version, the markdown table is displayed as a tree structure through reduction. Click Preview to export the offline Html effect . The effect diagram is as follows:

The PDF effect exported by third-party Markdown software is as follows:

At the same time, it provides the function of exporting offline Html. The interface style of Html function is almost the same as that of online. It is beautiful, generous and concise. Click to preview the effect online ,

The interface effect is as follows:

Star & Issue

Thank you all for your support, go to https://gitee.com/xiaoym/knife4j to order a Star~~ :)

At last

Knife4jI am honored to be selected for the 2020 OSC open source project (development tool category) selection, and look forward to your vote ~~!!!

Guess you like

Origin www.oschina.net/news/119457/knife4j-2-0-6-released