1. 程式人生 > 其它 >Swagger的常用註解與使用

Swagger的常用註解與使用

Swagger

簡介

  • 由於架構革新,進入了前後端分離,服務端只需提供RESTful API的時代。
  • 而構建RESTful API會考慮到多終端的問題,這樣就需要面對多個開發人員甚至多個開發團隊。
  • 為了減少與其他團隊對接的溝通成本,我們通常會寫好對應的API介面文件。
  • 從最早開始的word文件,到後續的showdoc,都能減少很多溝通成本,但隨之帶來的問題也比較麻煩。在開發期間介面會因業務的變更頻繁而變動,如果需要實時更新介面文件,這是一個費時費力的工作。
  • 為了解決上面的問題,Swagger應運而生。他可以輕鬆的整合進框架,並通過一系列註解生成強大的API文件。他既可以減輕編寫文件的工作量,也可以保證文件的實時更新,將維護文件與修改程式碼融為一體,是目前較好的解決方案。

常用註解

  • @Api()用於類;
    表示標識這個類是swagger的資源
  • @ApiOperation()用於方法;
    表示一個http請求的操作
  • @ApiParam()用於方法,引數,欄位說明;
    表示對引數的新增元資料(說明或是否必填等)
  • @ApiModel()用於類
    表示對類進行說明,用於引數用實體類接收
  • @ApiModelProperty()用於方法,欄位
    表示對model屬性的說明或者資料操作更改
  • @ApiIgnore()用於類,方法,方法引數
    表示這個方法或者類被忽略
  • @ApiImplicitParam() 用於方法
    表示單獨的請求引數
  • @ApiImplicitParams() 用於方法,包含多個 @ApiImplicitParam

程式碼示例

  1. @Api
@Api(value = "使用者部落格", tags = "部落格介面")
public class NoticeController {

}
  1. @ApiOperation
@GetMapping("/detail")
@ApiOperation(value = "獲取使用者詳細資訊", notes = "傳入notice" , position = 2)
public R<Notice> detail(Integer id) {
   Notice detail = noticeService.getOne(id);
   return R.data(detail );
}
  1. @ApiResponses
@GetMapping("/detail")
@ApiOperation(value = "獲取使用者詳細資訊", notes = "傳入notice" , position = 2)
@ApiResponses(value = {@ApiResponse(code = 500, msg= "INTERNAL_SERVER_ERROR", response = R.class)})
public R<Notice> detail(Integer id) {
   Notice detail = noticeService.getOne(id);
   return R.data(detail );
}
  1. @ApiImplicitParams
@GetMapping("/list")
@ApiImplicitParams({
   @ApiImplicitParam(name = "category", value = "公告型別", paramType = "query", dataType = "integer"),
   @ApiImplicitParam(name = "title", value = "公告標題", paramType = "query", dataType = "string")
})
@ApiOperation(value = "分頁", notes = "傳入notice", position = 3)
public R<IPage<Notice>> list(@ApiIgnore @RequestParam Map<String, Object> notice, Query query) {
   IPage<Notice> pages = noticeService.page(Condition.getPage(query), Condition.getQueryWrapper(notice, Notice.class));
   return R.data(pages );
}
  1. @ApiParam
@PostMapping("/remove")
@ApiOperation(value = "邏輯刪除", notes = "傳入notice", position = 7)
public R remove(@ApiParam(value = "主鍵集合") @RequestParam String ids) {
   boolean temp = noticeService.deleteLogic(Func.toIntList(ids));
   return R.status(temp);
}
  1. @ApiModel@ApiModelProperty
@Data
@ApiModel(value = "BladeUser ", description = "使用者物件")
public class BladeUser implements Serializable {

   private static final long serialVersionUID = 1L;

   @ApiModelProperty(value = "主鍵", hidden = true)
   private Integer userId;

   @ApiModelProperty(value = "暱稱")
   private String userName;

   @ApiModelProperty(value = "賬號")
   private String account;

   @ApiModelProperty(value = "角色id")
   private String roleId;
 
   @ApiModelProperty(value = "角色名")
   private String roleName;

}
  1. @ApiIgnore()
@ApiIgnore()
@GetMapping("/detail")
public R<Notice> detail(Integer id) {
   Notice detail = noticeService.getOne(id);
   return R.data(detail );
}