什么是Swagger
Swagger 是一款RESTFUL接口的文檔在線自動生成+功能測試功能軟件。Swagger API文檔工具可以滿足下列需求:
- 支持項目中的API接口自動生成同步的在線文檔。
- 生成的API文檔可用于項目內(nèi)部API審核,查看等。
- 通過Swagger實時的API接口同步功能,方便測試人員和接口調(diào)用者動態(tài)了解API及其變化。
- 這些文檔可作為客戶產(chǎn)品文檔的一部分進行發(fā)布。
- 支持API規(guī)范生成代碼,生成的客戶端和服務(wù)器端骨架代碼可以加速開發(fā)和測試速度。
常用到的注解有:
@Api :用在類上,說明該類的作用
@ApiOperation :用在方法上,說明方法的作用
@ApiImplicitParams :用在方法上包含一組參數(shù)說明
@ApiImplicitParam :用在@ApiImplicitParams注解中,指定一個請求參數(shù)的各個方面
paramType:參數(shù)放在哪個地方
header-->請求參數(shù)的獲?。篅RequestHeader
query-->請求參數(shù)的獲取:@RequestParam
path(用于restful接口)-->請求參數(shù)的獲取:@PathVariable
body(不常用)
form(不常用)
name:參數(shù)名
dataType:參數(shù)類型
required:參數(shù)是否必須傳
value:參數(shù)的意思
defaultValue:參數(shù)的默認值
@ApiResponses :用于表示一組響應(yīng)
@ApiResponse :用在@ApiResponses中,一般用于表達一個錯誤的響應(yīng)信息
code:數(shù)字,例如400
message:信息,例如"請求參數(shù)沒填好"
response:拋出異常的類
@ApiModel:描述一個Model的信息(這種一般用在post創(chuàng)建的時候,使用@RequestBody這樣的場景,請求參數(shù)無法使用@ApiImplicitParam注解進行描述的時候)
@ApiModelProperty:描述一個model的屬性
@API注解:
用在類上,說明該類的作用??梢詷擞浺粋€Controller類做為swagger 文檔資源,使用方式:
@Api(value = "/user", description = "Operations about user")
與Controller注解并列使用。 屬性配置:
屬性名稱 備注
value url的路徑值("別用?。?!會在url上顯示該值")
tags 如果設(shè)置這個值、value的值會被覆蓋
description 對api資源的描述
basePath 基本路徑可以不配置
position 如果配置多個Api 想改變顯示的順序位置
produces For example, "application/json, application/xml"
consumes For example, "application/json, application/xml"
protocols Possible values: http, https, ws, wss.
authorizations 高級特性認證時配置
hidden 配置為true 將在文檔中隱藏
代碼實戰(zhàn)
控制器類
package com.demo.myjson.controller;
import com.demo.myjson.pojo.CreatePersonRequest;
import com.google.gson.Gson;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/person")
@Api(tags = "個人信息接口") //說明該類的作用
public class PersonController {
// @ResponseBody //將controller的方法返回的對象通過適當?shù)霓D(zhuǎn)換器轉(zhuǎn)換為指定的格式之后,寫入到response對象的body區(qū),通常用來返回JSON數(shù)據(jù)或者是XML數(shù)據(jù)
@ApiImplicitParams({
@ApiImplicitParam(name = "name",paramType = "query",value = "用戶名",required = true),
@ApiImplicitParam(name = "age",paramType = "query",value = "年齡",required = true)
})
@ApiResponses({
@ApiResponse(code = 401,message = "你沒權(quán)限"),
@ApiResponse(code = 403,message = "你被禁止訪問了"),
@ApiResponse(code = 404,message = "沒找到,哈哈哈")
})
@ApiOperation("獲取個人信息") //說明方法的作用
@GetMapping("getInfo")
public CreatePersonRequest getInfo(@RequestParam String name,@RequestParam Integer age){ //@RequestParam,用來直接獲取URL中的參數(shù)
CreatePersonRequest p = new CreatePersonRequest();
p.setName(name);
p.setAge(age);
return p;
}
@ResponseBody
// @ApiImplicitParam(name = "age",paramType = "body",value = "用戶名",required = true)
@ApiOperation("添加個人信息")
@PostMapping("addInfo")
public CreatePersonRequest addInfo(@RequestBody CreatePersonRequest person,@RequestBody Integer age){
person.setName("hbl");
person.setAge(18);
person.setBirthday("19951003");
return person;
}
// @ResponseBody
@ApiOperation("更新個人信息")
@PostMapping("updateInfo")
public CreatePersonRequest updateInfo(@RequestBody CreatePersonRequest person){
person.setName("hbl");
person.setAge(19);
person.setBirthday("19951003");
return person;
}
@ApiOperation("刪除個人信息")
@PostMapping("deleteInfo")
public boolean deleteInfo(@RequestBody CreatePersonRequest person){
person.setName("hbl");
person.setAge(18);
person.setBirthday("19951003");
if((getInfo("hbl",18) != null))
return true;
return false;
}
}
Swagger配置類
package com.demo.myjson.SwaggerConfig;
import io.swagger.annotations.Api;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger2配置類
* 在與spring boot集成時,放在與Application.java同級的目錄下。
* 通過@Configuration注解,讓Spring來加載該類配置。
* 再通過@EnableSwagger2注解來啟用Swagger2。
*/
//@SpringBootApplication //same as @Configuration+@EnableAutoConfiguration+@ComponentScan
@Configuration
@EnableSwagger2 //啟動swagger注解
public class SwaggerConfig implements WebMvcConfigurer {
/**
* 創(chuàng)建API應(yīng)用
* apiInfo() 增加API相關(guān)信息
* 通過select()函數(shù)返回一個ApiSelectorBuilder實例,用來控制哪些接口暴露給Swagger來展現(xiàn),
* 本例采用指定掃描的包路徑來定義指定要建立API的目錄。
*
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//api接口包掃描路徑
.paths(PathSelectors.any()) //可以根據(jù)url路徑設(shè)置哪些請求加入文檔,忽略哪些請求
.build();
}
/**
* 創(chuàng)建該API的基本信息(這些基本信息會展現(xiàn)在文檔頁面中)
* 訪問地址:http://項目實際地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("myJson API") //設(shè)置文檔的標題
.description("我的demo") //設(shè)置文檔的描述
.termsOfServiceUrl("http://192.168.10.3/")
.contact(new Contact("黃寶玲","","huangbaoling@sunseaaiot.com"))
.version("1.0")
.build();
}
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
// }
}

本地運行代碼,服務(wù)使用8080端口
接口上方的信息是在配置文件中設(shè)置的,我們主要看接口的信息,有點像restful API,最左邊是請求類型,put、post、get等等,然后是url,再是描述。

在本地瀏覽器訪問本地8080端口的swagger-ui.html#

接口詳情,點擊try it out編寫信息

點擊excute執(zhí)行

可以看到請求頭、URL、請求體、返回響應(yīng)等信息