当前位置:网站首页>Still using swagger? Try this zero annotation intrusion API document generation tool, which is perfect for postman!

Still using swagger? Try this zero annotation intrusion API document generation tool, which is perfect for postman!

2021-11-25 18:21:32 macrozheng

The joint commissioning of front and rear interfaces requires API file , We often use tools to generate . I used to use Swagger To generate , Recently, I found an easy-to-use API Document generation tool smart-doc, It has a lot of Swagger Features not available , I recommend it to you .

SpringBoot Actual e-commerce projects mall(50k+star) Address :https://github.com/macrozheng/mall

Chat Swagger

When we use Swagger When , Its annotations are often needed , such as @Api@ApiOperation these ,Swagger Generate... From them API file . Consider the following code :

Swagger The code is relatively invasive , Sometimes code comments and comments are a little repetitive . Is there any tool that can achieve zero annotation intrusion , Generate... Directly from code comments API Documents ?smart-doc It happens to be this tool !

smart-doc brief introduction

smart-doc Is a API Document generation tool , No unnecessary operation is required , As long as you write code comments properly , Can generate API file . At the same time, it can directly generate Postman Commissioning documents , Import one key Postman Ready for debugging , Very easy to use !

smart-doc Has the following advantages :

Generate API file

Next, we will smart-doc Integrated into the SpringBoot In the project , Experience its API Document generation .
  • First we need to add... To the project smart-doc Of Maven plug-in unit , You can find smart-doc It's just a plug-in , You don't even have to add dependencies , Really zero invasion ;
<plugin>
    <groupId>com.github.shalousun</groupId>
    <artifactId>smart-doc-maven-plugin</artifactId>
    <version>2.2.8</version>
    <configuration>
        <!-- Appoint smart-doc The configuration file path used -->
        <configFile>./src/main/resources/smart-doc.json</configFile>
        <!-- Specify project name -->
        <projectName>mall-tiny-smart-doc</projectName>
    </configuration>
</plugin>
  • Next in the project resources Under the table of contents , Add configuration file smart-doc.json, The attribute description can be directly referred to the annotation ;
{
  "serverUrl": "http://localhost:8088", // Specify the back-end service access address 
  "outPath": "src/main/resources/static/doc", // Specify the output path of the document , Generate to the project static file directory , As the project starts, you can view 
  "isStrict": false, // Whether to turn on strict mode 
  "allInOne": true, // Whether to merge documents into one file 
  "createDebugPage": false, // Whether to create a test html page 
  "packageFilters": "com.macro.mall.tiny.controller.*", //controller Packet filtering 
  "style":"xt256", // be based on highlight.js Code high setting 
  "projectName": "mall-tiny-smart-doc", // Configure your own project name 
  "showAuthor":false, // Whether to display the interface author name 
  "allInOneDocFileName":"index.html" // Customize the output document name 
}
  • open IDEA Of Maven panel , double-click smart-doc The plug-in smart-doc:html Button , It can generate API file ;

  • Now we can see that , In the project static/doc The following files have been generated in the directory ;

  • Run the project , Access generated API Interface document , The document was found to be very detailed , It includes various descriptions of request parameters and response results , Access address :http://localhost:8088/doc/ind...

  • Let's look back at the code of the entity class , It can be found that we just add field comments in a normative way , When the document is generated, there is automatically ;
public class PmsBrand implements Serializable {
    /**
     * ID
     */
    private Long id;

    /**
     *  name 
     * @required
     */
    private String name;

    /**
     *  The first letter 
     * @since 1.0
     */
    private String firstLetter;

    /**
     *  Sort 
     */
    private Integer sort;

    /**
     *  Is it a brand manufacturer (0,1)
     */
    private Integer factoryStatus;

    /**
     *  Display state (0,1)
     * @ignore
     */
    private Integer showStatus;

    /**
     *  Product quantity 
     */
    private Integer productCount;

    /**
     *  Number of product reviews 
     */
    private Integer productCommentCount;

    /**
     *  brand logo
     */
    private String logo;

    /**
     *  Big picture of the special area 
     */
    private String bigPic;

    /**
     *  Brand story 
     */
    private String brandStory;
    // Omit getter、setter Method 
}
  • And then look at Controller In the code , We also annotate the method in a standard way , Generate API The document is automatically generated when it is ;
/**
 *  Brand management 
 */
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
    @Autowired
    private PmsBrandService brandService;
    
    /**
     *  Paging query brand list 
     *
     * @param pageNum  Page number 
     * @param pageSize  Paging size 
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    @PreAuthorize("hasRole('ADMIN')")
    public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1")
                                                                Integer pageNum,
                                                        @RequestParam(value = "pageSize", defaultValue = "3")
                                                                Integer pageSize) {
        List<PmsBrand> brandList = brandService.listBrand(pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(brandList));
    }
}
  • Of course smart-doc Custom comments are also provided tag, Used to enhance document functionality ;

    • @ignore: Whether to filter this attribute when generating the document ;
    • @required: Used to decorate whether the interface request parameters must ;
    • @since: Used to decorate the version number added by the attribute in the interface .
  • In order to write elegant API Document interface , We often encapsulate the returned results ,smart-doc This setting is also supported , stay smart-doc.json Add the following configuration to ;
{
  "responseBodyAdvice":{ // Unified return result settings 
    "className":"com.macro.mall.tiny.common.api.CommonResult" // Corresponding to encapsulation class 
  }
}
  • We also often use enumeration types to encapsulate status codes , stay smart-doc.json Add the following configuration to ;
{
  "errorCodeDictionaries": [{ // Error code list settings 
    "title": "title",
    "enumClassName": "com.macro.mall.tiny.common.api.ResultCode", // Error code enumeration class 
    "codeField": "code", // The error code corresponds to the field 
    "descField": "message" // Error code description corresponding field 
  }]
}
  • After successful configuration , Can be in API Generated in document Error code list ;

  • Sometimes we also want to add custom request headers to some interfaces , For example, add... To some interfaces that need to log in Authorization head , stay smart-doc.json Add the following configuration to ;
{
  "requestHeaders": [{ // Request header Settings 
    "name": "Authorization", // Request header name 
    "type": "string", // Request header type 
    "desc": "token The value of the request header ", // Request header description 
    "value":"token The value of the request header ", // The value of the request header 
    "required": false, // Whether must 
    "since": "-", // Add version 
    "pathPatterns": "/brand/**", // Which paths need to add request headers 
    "excludePathPatterns":"/admin/login" // Which paths do not need to add request headers 
  }]
}
  • After successful configuration , You can view the custom request header information in the interface document .

Use Postman Test interface

We use Swagger When generating documents , You can test the interface directly on it , and smart-doc The interface testing capability of is really weak , This may be its hug Postman Why? , After all Postman It is a very easy-to-use interface testing tool , Let's combine Postman Use it !
  • smart-doc Built in Postman Of json Build plug-ins , It can be generated and imported into Postman In the middle , double-click smart-doc:postman Button ;

  • This will be done in the project static/doc Generate under directory postman.json file ;

  • take postman.json Import files directly into Postman Can be used in ;

  • After importing successfully , All interfaces will be in Postman It shows that , Now we can happily test the interface !

summary

smart-doc It's really an easy to use API Document generation tool , In particular, it has the characteristics of zero annotation intrusion . Although its interface testing capability is insufficient , But it can be generated with one click JSON File and import to Postman In the middle , It is also very convenient to use !

Reference material

Official documents :https://gitee.com/smart-doc-t...

Project source address

https://github.com/macrozheng...

this paper GitHub https://github.com/macrozheng/mall-learning Included , Welcome to Star!

版权声明
本文为[macrozheng]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/11/20211109101113017Q.html

随机推荐