線上API介面文件swagger2

weixin_34321977發表於2018-10-16

Swagger™的目標是為REST API 定義一個標準的,與語言無關的介面,使人和計算機在看不到原始碼或者看不到文件或者不能通過網路流量檢測的情況下能發現和理解各種服務的功能。當服務通過Swagger定義,消費者就能與遠端的服務互動通過少量的實現邏輯。
簡單說,swagger能夠根據程式碼中的註釋自動生成api文件,並且提供測試介面;

swagger和swagger2是兩個不同的版本,現在用的比較多的是swagger和springfox,springfox就是swagger-springmvc的升級版,也叫swagger2;
使用springfox;
整合springfox和springmvc:
//新增依賴

 <!-- swagger2 start -->
 <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version></dependency>
 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger-ui</artifactId>
     <version>2.7.0</version>
</dependency>
<!--  swagger2 end -->
@Configuration
@EnableSwagger2
public class ApiConfig {

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.wolfcode"))//掃描路徑
//                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiImplicitParams.class))//根據註解定製
                .paths(PathSelectors.any()) //定義哪些路徑的介面需要生成文件
                .build();
    }
    @Bean
    public ApiInfo apiInfo() {
        Contact contact = new Contact("sky","https://www.jianshu.com/u/a099a2677722","8888@126.com");
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2構建RESTful API")//文件首頁標題
                .description("swagger2-文件構建利器")//文件描述資訊
                .contact(contact) //建立者資訊
                .version("1.0")     //文件版本
                .build();
    }
}

訪問地址:http://localhost:8080/v2/api-docs
ui訪問地址:http://localhost:8080/swagger-ui.html

springfox的標籤:

@Api(value = "使用者增刪改查",description = "詳細描述")
@RestController
@RequestMapping("/users")
public class EmpController {

    //獲取使用者列表
    @ApiOperation(value = "獲取使用者列表",notes = "獲取使用者列表詳細描述")
    @GetMapping
    public List<Emp> getUsers(){
        List list = new ArrayList<>();
        list.add(new Emp(1L,"A"));
        list.add(new Emp(2L,"B"));
        list.add(new Emp(3L,"C"));
        return list;
    }
    //獲取使用者
    /*
        params = "pwd=999"
        headers = "Content-Type=application/json" == "Accept=application/json"
        headers="contentType=application/json" == consumes="application/json"
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Emp getUser(@PathVariable("id") Long id){
        System.out.println("id : "+id);
        return new Emp(1L,"xx");
    }
    //刪除使用者
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "使用者的唯一標識",required = true),
            @ApiImplicitParam(name = "name" ,value = "使用者名稱" , required = false)
    })
    @ApiResponses({
         @ApiResponse(code = 401 ,message = "禁止訪問")
    })
    @DeleteMapping("/{id}/{name}")
    public void deleteUsers(@PathVariable("id") Long id ,@PathVariable("name") String name){

        System.out.println("刪除成功...");
    }

    //建立使用者
    @ApiIgnore
    @PostMapping
    public Emp createUsers(@RequestBody Emp emp){
        System.out.println(emp);
        return emp;
    }

}

swagger2優點: 簡單 , 實時 , 可測試 , 容易管理
swagger2缺點: 程式碼侵入性太強, 影響正常程式碼閱讀

學習swagger2就是學習怎麼使用註解為介面新增描述資訊

@Api:修飾整個類,描述Controller的作用
@ApiOperation:描述一個類的一個方法,或者說一個介面
@ApiImplicitParams:多個請求引數
@ApiImplicitParam:一個請求引數
@ApiResponses:HTTP響應整體描述
@ApiResponse:HTTP響應其中1個描述
@ApiModel:用物件來接收引數
@ApiModelProperty:用物件接收引數時,描述物件的一個欄位
@ApiIgnore:使用該註解忽略這個API

類和方法的描述:
@Api修飾整個類,描述Controller的作用
@ApiOperation 貼在方法上,描述一個方法的作用
1、@Api註解的使用:貼在類上,主要用下面的這幾個屬性
1)value:該controller簡短的標題
2)description:詳細介紹
3)producer:說明該controller是使用什麼顯示層格式的
4)protocols:使用什麼協議
2、@ApiOperation註解的使用:貼在方法上,主要用下面的這幾個屬性
1)value:該方法簡短的變態
2)note:詳細介紹
3)code:正常情況下返回的狀態碼是多少
4)httpMethod:使用什麼http方法
5)response:響應什麼物件,這裡寫的是響應的物件的位元組碼

 /**
 * 
 * @param param
 * @return
 */
@ApiOperation(value = "獲取所有產品資訊", notes = "獲取所有產品資訊", httpMethod = "GET")
@ResponseBody
@RequestMapping(value="/sync/test", method = RequestMethod.GET)
public JSONMessage test(String value,String notes) {    
    return JSONMessage.success("測試功能");
}

引數的描述:
貼在引數上
@ApiImplicitParams 多個請求引數
@ApiImplicitParam 一個請求引數
@ApiParam 單個引數描述
1)name:引數名
2)value:引數名對應的值
3)dataType:引數的型別
4)require:該引數是否必填
5)paramType:該引數的來源型別,它的值有如下:
query:該引數從位址列問號後面的引數獲取
form:該引數從form表單中獲取
path:該引數從URL地址上獲取
body:該引數從請求體中獲取
header:該引數從請求頭獲取

響應的描述:
@ApiResponses:HTTP響應整體的描述
@ApiResponse:HTTP響應中某一種響應的描述
用在@ApiResponses中,一般用於表達一個錯誤的響應資訊(200相應不寫在這裡面)
code:數字,例如400
message:資訊,例如"請求引數沒填好"
response:丟擲的異常類

物件模型描述:
@ApiModel/@ApiModelProperty
@ApiModel:描述一個Model的資訊(這種一般用在post建立的時候,使用@RequestBody這樣的場景,請求引數無法使用@ApiImplicitParam註解進行描述的時候)
@ApiModelProperty:描述一個model的屬性

忽略介面API:
@ApiIgnore 貼了該註解的api 會被忽略,不生成介面文件

兩種不生成api的方式:
1、@ApiIgnore:可以貼在類和方法上
2、在swagger配置類上的select()方法上呼叫apis(),apis方法需要傳入一個selector。可以使用RequestHandlerSelector內建的selector

springBoot整合swagger2:
//新增依賴

 <!-- swagger2 start -->
 <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version></dependency>
 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger-ui</artifactId>
     <version>2.7.0</version>
</dependency>
<!--  swagger2 end -->
@Configuration
@EnableSwagger2
public class SwaggerConfig{

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
//              .apis(RequestHandlerSelectors.basePackage("cn.wolfcode.controller"))//掃描路徑
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiImplicitParams.class))//根據註解定製
                .paths(PathSelectors.any()) //定義哪些路徑的介面需要生成文件
                .build();
    }
    @Bean
    private ApiInfo apiInfo() {
        Contact contact = new Contact("sky","https://www.jianshu.com/u/a099a2677722","8888@126.com");
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2構建RESTful API")//文件首頁標題
                .description("swagger2-文件構建利器")//文件描述資訊
                .contact(contact) //建立者資訊
                .version("1.0")     //文件版本
                .build();
    }
}

相關文章