In the past of Java Web development, Swagger accounted for most of the interface document generation. Despite Swagger’s complex configuration and extremely intrusive code, developers have no good tools to replace it. Other well-known projects abroad are mainly APIDOC, but THE use of APIDOC is more complex and cannot shake Swagger. Many developers in China have been eager to develop some low-intrusion document generation tools. From 2018 to now, several projects of Java generation restful API interface documents have been submitted on China’s internal code cloud platform. But many projects are almost impossible to use by outside companies and lack extensive usage testing.

At the end of 2017, a developer who refused to use Swagger finally came up with the idea of generating documents based on source code and annotation analysis and started developing the tool, smart-Doc. Smart-doc became open source in August 2018 and was first introduced to the company by OnePlus. In 2019, after continuous iteration and communication with users, Smart-Doc has entered hundreds of companies in China. Because of the zero-intrusion and zero-annotation features of Smart-Doc, they chose Smart-Doc instead of Swagger.

Smart – doc

Smart-doc is a Java restful API document generation tool. Smart-doc subverts the traditional implementation of swagger, which uses extensive annotation intrusion to generate documents. Smart-doc generates interface documentation entirely based on the source code analysis of the interface, with zero annotation intrusion. You only need to write Java standard annotations, smart-Doc can help you generate a simple markdown or a gitbook-style static HTML document. If you’re tired of swagger and other documentation tools with endless comments and intrusive pollution, embrace smart-doc!

Functional characteristics

  • Zero annotations, zero learning costs, and only standard Java annotations.
  • Automatic derivation based on source code interface definition, powerful return structure derivation.
  • Support Spring MVC,Spring Boot,Spring Boot Web Flux(controller writing).
  • Support the Callable, Future, CompletableFuture asynchronous interfaces such as returns are derived.
  • Supports JSR303 parameter verification specification on Javabeans.
  • The interface to JSON request parameters can automatically generate mock JSON parameters.
  • The ability to generate valid mock values for some common field definitions.
  • Support for generating JSON return value examples.
  • Support for generating field annotations (including jar packages published by the standard specification) by loading source code from outside the project.
  • Support to generate documents in various formats: Markdown, HTML5, Asciidoctor, Postman JSON.
  • Easy to view static HTML5 API documents online on the Spring Boot service.
  • Open document data, free access to the document management system.
  • Support for exporting error codes and various dictionary codes defined in code to interface documents.

Integrate into the SpringBoot project

For details about how to use and test smart-doc, see smart-doc Demo.

# git clone https://gitee.com/sunyurepository/api-doc-test.git
Copy the code

You can start this Spring Boot program, and then visit http://localhost:8080/doc/api.html to browse through smart – doc generated interface documentation.

Dependency

maven

<dependency> <groupId>com.github. Shalousun </groupId> <artifactId>smart-doc</artifactId> <version>{latest version}</version> <scope>test</scope>
</dependency>
Copy the code

gradle

testCompile 'com. Making. Shalousun: smart - doc: the latest version of the'
Copy the code

Create a unit test

Get Smart-Doc to produce a clean API document for you by running a unit test

/** * Description: ** @author yu 2018/06/11. */ public ApiDocTest { Void */ @test public void */ @test public voidtestBuilderControllersApi() {
        ApiConfig config = new ApiConfig();
        config.setServerUrl("http://localhost:8080");
        //trueComments are strictly required and recommendedtrue
        config.setStrict(true);
        //trueThe merged document is exported to a Markdown config.setallinone (false); / / generate HTML encryption document name not to reveal the name of the controller config. SetMd5EncryptedHtmlName (true); HTML_DOC_OUT_PATH; // Since version 1.7, choose to generate static HTML doc documents using the path: DocGlobalConstants.HTML_DOC_OUT_PATH; config.setOutPath(DocGlobalConstants.HTML_DOC_OUT_PATH); // config.setPackagefilters (); // if this option is not set, all controllers will be matched by default."com.power.doc.controller"); / / don't specify SourcePaths default load code for the project under the SRC/main/Java, if the project is of certain entities from external code can be loaded config. Together setSourceCodePaths (/ / since 1.7.0 version, here can not set the local code path, // SourceCodePath ().setdesc ()"Project Code").setPath("src/main/java"),
            SourceCodePath.path().setDesc("Load out-of-project code").setPath("E:\\ApplicationPower\\ApplicationPower\\Common-util\\src\\main\\java")); //since 1.7.5 // If the value of this option isfalse, then the name of the allinone. md file generated by smart-doc will automatically add the version number config.setcoverold (true); // Since 1.7.5 // Set the project name (optional). This will result in incorrect serial numbers when using some automatic title numbering tools. Config.setprojectname ("Panic buying system"); Config. SetRequestHeaders (apireqheader.header ().setName());"access_token").setType("string").setDesc("Basic auth credentials"),
                ApiReqHeader.header().setName("user_uuid").setType("string").setDesc("User Uuid key")); // For external JAR classes, comments will be erased after compilation. You cannot get comments, but please use them if there are too manysetIf you have this scenario, add your own fields and comments, API - late doc in fields with the same add comments directly to the appropriate field config. SetCustomResponseFields (CustomRespField. Field () elegantly-named setName ("success").setDesc("Return true on success, false on failure"),
                CustomRespField.field().setName("message").setDesc("Interface Response information"),
                CustomRespField.field().setName("data").setDesc("Interface Response data"),
                CustomRespField.field().setName("code").setValue("00000").setDesc("Response code")); List<ApiErrorCode> errorCodeList = new ArrayList<>(); List<ApiErrorCode> errorCodeList = new ArrayList<>();for(ErrorCodeEnum codeEnum : ErrorCodeEnum.values()) { ApiErrorCode errorCode = new ApiErrorCode(); errorCode.setValue(codeEnum.getCode()).setDesc(codeEnum.getDesc()); errorCodeList.add(errorCode); } // Leave config.setErrorCodes(errorCodeList) alone if you don't want to; // Not necessarily only whensetAllInOne set totrueWhen the document change record takes effect, https://gitee.com/sunyurepository/ApplicationPower/issues/IPS4O config.setRevisionLogs( RevisionLog.getLog().setRevisionTime("2018/12/15").setAuthor("chen").setRemarks("Test").setStatus("Create").setVersion("V1.0"),
                RevisionLog.getLog().setRevisionTime("2018/12/16").setAuthor("chen2").setRemarks("The test 2").setStatus("Change").setVersion("V2.0")); / / since 1.7.5 / config/document to add data dictionary setDataDictionaries (ApiDataDictionary. Dict (). The setTitle ("Order Status").setEnumClass(OrderEnum.class).setCodeField("code").setDescField("desc"),
            ApiDataDictionary.dict().setTitle("Order Status 1").setEnumClass(OrderEnum.class).setCodeField("code").setDescField("desc")); long start = System.currentTimeMillis(); ApiDocBuilder.builderControllersApi(config); / / @ since version 1.7 +, smart - doc support generates HTML document with bookmarks, HTML document alternative ways under the denomination. / / HtmlApiDocBuilder builderControllersApi (config); // since version 1.7+, smart-doc supports generating AsciiDoc documents. You can convert AsciiDoc into HTML5 format. //@see https://gitee.com/sunyurepository/api-doc-test //AdocDocBuilder.builderControllersApi(config); / / @ since 1.7.8, smart - doc support export Postman test json / / PostmanJsonBuilder BuildPostmanApi (config); long end = System.currentTimeMillis(); DateTimeUtil.printRunTime(end, start); }}Copy the code

Example interface document generation

Entity code:

Public class SimpleUser {/** * username * @since v1.0 */ @notnull private String username; /** * password * @since v1.0 */ private String password; /** * nickName * @since v1.0 */ private String nickName; /** ** @since v1.0 */ private String mobile; }Copy the code

The Controller layer interface

/** * Smart-doc interface generated test * @author CHT 2019/10/16. */ @restController Public Class ApiNoteController {/** * Interface generated test * @return
     */
    @PostMapping(value = "/test")
    public CommonResult<SimpleUser> test(@RequestBody SimpleUser user){
        returnCommonResult.ok().setResult(user); }}Copy the code

The document looks like this:

Smart-doc interface generation test

Interface generation test

URL: http://localhost:8080/test

Type: POST

Content-Type: application/json; charset=utf-8

Description: Indicates the interface generation test

Request-headers:

Header Type Description Required Since
token string token(Global) true
partnerId string Partner account (Global) true

Request-parameters:

Parameter Type Description Required Since
username string The user name true v1.0
password string password false v1.0
nickName string nickname false v1.0
mobile string The phone false v1.0

Request-example:

{
	"username":"Chi Chen Lo."."password":"xzl6bk"."nickName":"sofia.crist"."mobile":"17545455139"
}
Copy the code

Response-fields:

Field Type Description Since
success boolean The success of
message string Error message (succeed)
data object Successfully returned data
└ ─ the username string The user name v1.0
└ ─ the password string password v1.0
└ ─ nickName string nickname v1.0
└ ─ mobile string The phone v1.0
code string The error code
timestamp string The response time

Response-example:

{
	"success":true."message":"success"."data": {"username":"Chi Chen Lo."."password":"o85ttk"."nickName":"sofia.crist"."mobile":"17545455139"
	},
	"code":"86061"."timestamp":"The 2019-12-05 23:50:08"
}
Copy the code

As you can see, with smart-Doc you only need to write standard Javadoc comments. Smart-doc does not pollute your business code.

Smart-doc Related usage documents

  • smart-doc wiki

Smart-doc Project address

  • github
  • gitee

conclusion

From the above introduction and sample presentation, it is easy to see why Smart-Doc is used by hundreds of Chinese companies. Smart-doc is completely invulnerable and can produce quick and clean HTML static documents, documents in MarkDown format (the sample document data above comes from Smart-Doc’s Markdown generation), adoc documents, and even interface JSON files that can be imported into postMan tests with one click. Smart-doc has been verified by many users in the past year and has become stable and mature. It will become better with users in the future. Hopefully smart-Doc will help more users and attract more contributors.

Smart-doc User evaluation

  • The most powerful DOC component that enforces specifications and does not contaminate code.
  • Smartdoc really lives up to its name by starting with comments, i.e. specifications that enhance documentation and provide API functionality beyond source documentation.
  • Smart-doc is very comfortable to use and hopefully will get better and better.