1
头图
The front-end interface joint debugging requires API documents, which we often use tools to generate. I often used Swagger to generate it before, and recently I found a useful API document generation tool smart-doc , which has many features that Swagger does not have, and I recommend it to everyone.

SpringBoot actual combat e-commerce project mall (50k+star) address: https://github.com/macrozheng/mall

Talk about Swagger

When we use Swagger, we often need to use its annotations, such as @Api , @ApiOperation , and Swagger uses them to generate API documentation. For example, the following code:

Swagger is relatively intrusive to the code, and sometimes the content in the code comments and annotations is a bit repetitive. Is there any tool that can achieve zero annotation intrusion and directly generate API documentation based on code annotations? smart-doc happens to be this kind of tool!

Introduction to smart-doc

smart-doc is an API document generation tool. No extra operations are required. As long as you write code comments in a standardized way, you can generate API documents. At the same time, it can directly generate Postman debugging files, and import Postman to debug with one click, which is very easy to use!

smart-doc has the following advantages:

Generate API documentation

Next, we smart-doc into the SpringBoot project and experience its API document generation function.
  • First of all, we need to add the Maven plug- smart-doc smart-doc is a plug-in, even the dependency does not need to be added, it is really zero intrusion;
<plugin>
    <groupId>com.github.shalousun</groupId>
    <artifactId>smart-doc-maven-plugin</artifactId>
    <version>2.2.8</version>
    <configuration>
        <!--指定smart-doc使用的配置文件路径-->
        <configFile>./src/main/resources/smart-doc.json</configFile>
        <!--指定项目名称-->
        <projectName>mall-tiny-smart-doc</projectName>
    </configuration>
</plugin>
  • Next, add the configuration file smart-doc.json in the resources directory of the project, and refer to the comments directly for the attribute description;
{
  "serverUrl": "http://localhost:8088", //指定后端服务访问地址
  "outPath": "src/main/resources/static/doc", //指定文档的输出路径,生成到项目静态文件目录下,随项目启动可以查看
  "isStrict": false, //是否开启严格模式
  "allInOne": true, //是否将文档合并到一个文件中
  "createDebugPage": false, //是否创建可以测试的html页面
  "packageFilters": "com.macro.mall.tiny.controller.*", //controller包过滤
  "style":"xt256", //基于highlight.js的代码高设置
  "projectName": "mall-tiny-smart-doc", //配置自己的项目名称
  "showAuthor":false, //是否显示接口作者名称
  "allInOneDocFileName":"index.html" //自定义设置输出文档名称
}
  • Open the Maven panel of IDEA and double-click smart-doc:html smart-doc plug-in to generate API documentation;

  • At this point, we can find that the following files have been generated static/doc

  • Run the project, visit the generated API interface document, and find that the document is very detailed, including various descriptions of request parameters and response results. Visit address: http://localhost:8088/doc/index.html

  • When we went back and looked at the code of the entity class, we can find that we just added field comments in a standardized manner, which will be automatically available when the document is generated;
public class PmsBrand implements Serializable {
    /**
     * ID
     */
    private Long id;

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

    /**
     * 首字母
     * @since 1.0
     */
    private String firstLetter;

    /**
     * 排序
     */
    private Integer sort;

    /**
     * 是否为品牌制造商(0,1)
     */
    private Integer factoryStatus;

    /**
     * 显示状态(0,1)
     * @ignore
     */
    private Integer showStatus;

    /**
     * 产品数量
     */
    private Integer productCount;

    /**
     * 产品评论数量
     */
    private Integer productCommentCount;

    /**
     * 品牌logo
     */
    private String logo;

    /**
     * 专区大图
     */
    private String bigPic;

    /**
     * 品牌故事
     */
    private String brandStory;
    //省略getter、setter方法
}
  • Let's take a look at the code in the Controller. We also add comments to the method in a standardized manner, which is also automatically available when generating API documentation;
/**
 * 商品品牌管理
 */
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
    @Autowired
    private PmsBrandService brandService;
    
    /**
     * 分页查询品牌列表
     *
     * @param pageNum 页码
     * @param pageSize 分页大小
     */
    @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 also provides a custom annotation tag to enhance the document function;

    • @ignore: Whether to filter this attribute when generating the document;
    • @required: Used to modify whether the interface request parameters are required;
    • @since: Used to modify the version number added by attributes in the interface.
  • In order to write an elegant API document interface, we often encapsulate the returned results uniformly. smart-doc also supports this setting. Add the following configuration smart-doc.json
{
  "responseBodyAdvice":{ //统一返回结果设置
    "className":"com.macro.mall.tiny.common.api.CommonResult" //对应封装类
  }
}
  • We also often use enumerated types to encapsulate the status code, add the following configuration smart-doc.json
{
  "errorCodeDictionaries": [{ //错误码列表设置
    "title": "title",
    "enumClassName": "com.macro.mall.tiny.common.api.ResultCode", //错误码枚举类
    "codeField": "code", //错误码对应字段
    "descField": "message" //错误码描述对应字段
  }]
}
  • After the configuration is successful, the error code list can be generated in the API document;

  • Sometimes we also want to add custom request headers to certain interfaces. For example, add the Authorization header to some interfaces that need to log in, and add the following configuration smart-doc.json
{
  "requestHeaders": [{ //请求头设置
    "name": "Authorization", //请求头名称
    "type": "string", //请求头类型
    "desc": "token请求头的值", //请求头描述
    "value":"token请求头的值", //请求头的值
    "required": false, //是否必须
    "since": "-", //添加版本
    "pathPatterns": "/brand/**", //哪些路径需要添加请求头
    "excludePathPatterns":"/admin/login" //哪些路径不需要添加请求头
  }]
}
  • After the configuration is successful, you can view the custom request header information in the interface document.

Use Postman to test the interface

When we use Swagger to generate documents, we can directly test the interface above, and smart-doc is really weak. This may be the reason why it embraces Postman. After all, Postman is a very easy-to-use interface testing tool. Below we Let's use it in conjunction with Postman!
  • smart-doc built-in Postman's json generation plug-in, which can be generated and imported into Postman with one click, and smart-doc:postman can be generated by double-clicking the 0618b27b5e05fd button;

  • At this point in the project static/doc generate directory postman.json file;

  • postman.json file directly into Postman to use;

  • After the import is successful, all interfaces will be displayed in Postman, and now we can test the interfaces happily!

Summarize

smart-doc is indeed an easy-to-use API document generation tool, especially its feature of zero annotation intrusion. Although its interface testing capabilities are insufficient, it can generate a JSON file with one click and import it into Postman, which is very convenient to use!

Reference

Official document: https://gitee.com/smart-doc-team/smart-doc/wikis/HOME

Project source code address

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-smart-doc

This article GitHub https://github.com/macrozheng/mall-learning has been included, welcome to Star!

macrozheng
1.1k 声望1.3k 粉丝