如何使用Swagger-UI在線生成漂亮的接口文檔


一、簡單介紹

Swagger是一個實現了OpenAPI(OpenAPI Specification)規范的工具集。OpenAPI是Linux基金會的一個項目,試圖通過定義一種用來描述API格式或API定義的語言,來規范RESTful服務開發過程。

swagger大大方便了前后端開發人員,用過的人都說好。但是也有一些人並未體驗過swagger,還在苦苦的手寫接口文檔,麻煩又不規范;還有一些人雖然用過,但是只是朦朦朧朧,看別人怎么用直接就CV過來用了,使用的很碎片,不系統。我之前就是這個樣子,只知道添加個依賴,啟動項目后訪問:localhost:8080/swagger-ui.html,就能看到生成的文檔了,很是簡單。

一次我看到生成的文檔上總是多出來一個basic-error-controller,強迫症犯了,就想要把它弄掉,於是順便看了下swagger的配置,在這里記錄一下。

官網:https://swagger.io/

看官方的說明:

Swagger包含的工具集:

  • Swagger編輯器: Swagger Editor允許您在瀏覽器中編輯YAML中的OpenAPI規范並實時預覽文檔。
  • Swagger UI: Swagger UI是HTML,Javascript和CSS資產的集合,可以從符合OAS標准的API動態生成漂亮的文檔。
  • Swagger Codegen:允許根據OpenAPI規范自動生成API客戶端庫(SDK生成),服務器存根和文檔。
  • Swagger Parser:用於解析來自Java的OpenAPI定義的獨立庫
  • Swagger Core:與Java相關的庫,用於創建,使用和使用OpenAPI定義
  • Swagger Inspector(免費): API測試工具,可讓您驗證您的API並從現有API生成OpenAPI定義
  • SwaggerHub(免費和商業): API設計和文檔,為使用OpenAPI的團隊構建。

二、入門案例

SpringBoot已經集成了Swagger,使用簡單注解即可生成swagger的API文檔。

1.引入依賴

<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> 

2.編寫配置

@Configuration @EnableSwagger2 // Swagger的開關,表示已經啟用Swagger public class SwaggerConfig { @Bean public Docket api() { Docket docket = new Docket(DocumentationType.SWAGGER_2) .host("localhost:8081")// 不配的話,默認當前項目端口 .apiInfo(apiInfo()) .pathMapping("/") .select() // 選擇哪些路徑和api會生成document .apis(RequestHandlerSelectors.any())// 對所有api進行監控 // .apis(RequestHandlerSelectors.basePackage("com.hanstrovsky.controller"))// 選擇監控的package // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))// 只監控有ApiOperation注解的接口 //不顯示錯誤的接口地址 .paths(Predicates.not(PathSelectors.regex("/error.*")))//錯誤路徑不監控 .paths(PathSelectors.regex("/.*"))// 對根下所有路徑進行監控 .build(); return docket; } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("XXXX項目接口文檔") .contact(new Contact("Hanstrovsky", "www.hanstrovsky.com", "Hanstrovsky@gmail.com")) .description("這是用Swagger動態生成的接口文檔") .termsOfServiceUrl("NO terms of service") .license("The Apache License, Version 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .version("1.0") .build(); } } 

3.啟動測試

啟動服務,訪問:http://localhost:8081/swagger-ui.html

就能看到swagger-ui為我們提供的API頁面了:

可以看到我們編寫的接口,任意點擊一個,即可看到接口的詳細信息:

可以看到詳細的接口聲明,包括:

  • 請求方式:
  • 請求路徑
  • 請求參數
  • 響應等信息

點擊右上角的try it out!還可以測試接口。

三、常用注解

剛才的文檔說明中,是swagge-ui根據接口自動生成,不夠詳細。如果有需要,可以通過注解自定義接口聲明。常用的注解包括:

/** @Api:修飾整個類,描述Controller的作用 @ApiOperation:描述一個類的一個方法,或者說一個接口 @ApiParam:單個參數描述 @ApiModel:用對象來接收參數 @ApiProperty:用對象接收參數時,描述對象的一個字段 @ApiResponse:HTTP響應其中1個描述 @ApiResponses:HTTP響應整體描述 @ApiIgnore:使用該注解忽略這個API @ApiError :發生錯誤返回的信息 @ApiImplicitParam:一個請求參數 @ApiImplicitParams:多個請求參數 */ 

示例:

@PostMapping("/people") @ApiOperation(value = "保存人員信息") @ApiResponses({ @ApiResponse(code = 0, message = "保存成功"), @ApiResponse(code = 1, message = "保存失敗") }) public FrontResult save( @ApiParam(value = "保存參數", example = "") @RequestBody People people) { people.setBirthday(Timestamp.valueOf(LocalDateTime.now())); return new FrontResult(FrontResult.SUCCEED, "保存成功", peopleDao.save(people)); } 
@Data @ApiModel(description = "人員信息保存請求對象") public class People { @ApiModelProperty(value = "人員編號") private Long id; @ApiModelProperty(value = "姓名", required = true,position = 1) private String name; @ApiModelProperty(value = "性別", required = true,position = 2) private String sex; @ApiModelProperty(value = "生日", required = true,position = 3) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Timestamp birthday; } 

查看文檔:

四、美化一下

如果覺得用起來不太習慣,可以用Swagger-Bootstrap-UI 替換Swagger 默認的UI實現左右菜單風格的Swagger-UI ,讓其看起來更清晰明了。

1.添加依賴

<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency> 

2.重啟項目

訪問 http://localhost:8080/doc.html :

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM