Swagger入門


文檔向來在軟件開發過程中的每一個階段都是非常重要的,如果沒有文檔,那軟件的可維護性就會變得很糟,以致于影響可擴展性,最后慢慢的使軟件變成一堆亂糟糟的無用的代碼。而不同系統之間的接口文檔其重要性更顯而易見,一般常用的接口文檔采用以下形式:

  • [ ] 口口相傳
  • [x] 用world或其他文本文件進行保存
  • [x] 用wiki編寫

上面這些方式都有各自的缺點,比如不易維護,不易測試接口,接口變更而文檔未能同步更新等。但Swagger的出現改變了這些情形,Swagger的文檔編寫相當于就是在寫代碼,在更改接口代碼的同時就能方便的更新文檔,還能方便的進行接口的測試,怎么樣,很心動吧,心動不如行動,那我們開始練習吧。

創建一個Spring boot工程:

Spring boot工程目錄

加入Swagger依賴:

        <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>

寫一個controller作為API接口:

@RestController
@RequestMapping("/demo")
public class DemoController {

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public User addUser(@RequestBody @Valid User user){
        user.setDescription("had been dealed");
        return user;
    }

    @RequestMapping(value="/delete/{id}", method = RequestMethod.DELETE)
    public ResponseEntity delete(@PathVariable Integer id){
        //mock deleted;
        return new ResponseEntity("User had been deleted", HttpStatus.OK);
    }

    @RequestMapping(value = "/show", method= RequestMethod.GET)
    public User showUser(@RequestParam("id") Integer id){
        User user = new User();
        user.setId(1);
        user.setDescription("show user");
        user.setAge(100);
        user.setUsername("test");
        return user;
    }
}
這個和普通controller沒有撒區別,而我們想要讓它生成出接口文檔,并且能夠供別人進行接口測試,就需要進行Swagger的配置及其相關的注解的幫助了。

配置Swagger

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                //指定要生成api文檔的根包
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                //路徑配置
                .paths(regex("/demo.*"))
                .build()
                .apiInfo(apiInfo());

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger2的Restful API 文檔")
                .description("Spring Boot和Swagger的結合")
                .version("1.0")
                .build();
    }

}

配置好后,就可以啟動你的spring boot 應用,先一睹swagger的芳容,進入這個地址:http://localhost:8000/swagger-ui.html,具體的服務器端口號撒的根據你本地的進行更改,然后就會看到這個頁面:

swagger 頁面

但是,雖然能看到文檔頁面了,但這還比較簡陋,各個Restful方法的具體文檔都還沒有,這些還得靠我們去代碼里加入,畢竟還不是那么智能的,怎么加入呢,請接著往下看。
@Api在Controller類上定義這個服務的描述信息,像這樣:

@RestController
@RequestMapping("/demo")
@Api(value="demo", description="這是一個Swagger demo的服務")
public class DemoController {
    .....
}

然后在swagger ui里面就看到了對這個controller的描述信息:

@Api in controller class

有注解能對controller進行描述,當然也有注解能對里面的各個方法進行描述,這就是@ApiOperation和它的小伙伴們:


    @RequestMapping(value = "/add", method = RequestMethod.POST,produces = "application/json")
    @ApiOperation(value = "新增一個用戶", response = User.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功保存"),
            @ApiResponse(code = 401, message = "你沒權限"),
            @ApiResponse(code = 403, message = "你被禁止訪問了"),
            @ApiResponse(code = 404, message = "沒找到,哈哈哈")
    }
    )
    @ApiImplicitParam(name = "user",
            value = "要新增的用戶",
            dataType = "User",//This can be the class name or a primitive
            required = true,
            paramType = "body")
    public User addUser(@RequestBody @Valid User user){
        user.setDescription("had been dealed");
        return user;
    }

    @RequestMapping(value="/delete/{id}", method = RequestMethod.DELETE,produces = "application/json")
    @ApiOperation(value = "刪除一個用戶", response = ResponseEntity.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功保存"),
            @ApiResponse(code = 401, message = "你沒權限"),
            @ApiResponse(code = 403, message = "你被禁止訪問了"),
            @ApiResponse(code = 404, message = "沒找到,哈哈哈")
    }
    )
    @ApiImplicitParam(name="id",
            value = "要刪除的用戶id",
            dataType = "int",//This can be the class name or a primitive
            required = true,
            paramType = "path")//Valid values are {@code path}, {@code query}, {@code body}, {@code header} or {@code form}
    public ResponseEntity delete(@PathVariable Integer id){
        //mock deleted;
        return new ResponseEntity("User had been deleted", HttpStatus.OK);
    }

    @RequestMapping(value = "/show", method= RequestMethod.GET,produces = "application/json")
    @ApiOperation(value = "顯示一個用戶", response = ResponseEntity.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功保存"),
            @ApiResponse(code = 401, message = "你沒權限"),
            @ApiResponse(code = 403, message = "你被禁止訪問了"),
            @ApiResponse(code = 404, message = "沒找到,哈哈哈")
    }
    )
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",
                    value = "要刪除的用戶id",
                    dataType = "int",//This can be the class name or a primitive
                    required = true,
                    paramType = "query"),//Valid values are {@code path}, {@code query}, {@code body}, {@code header} or {@code form}
            @ApiImplicitParam(name = "param",
                    value = "其他參數",
                    dataType = "String",//This can be the class name or a primitive
                    required = true,
                    paramType = "query")//Valid values are {@code path}, {@code query}, {@code body}, {@code header} or {@code form}
    })

    public User showUser(@RequestParam("id") Integer id,@RequestParam("param") String otherParam){
        User user = new User();
        user.setId(1);
        user.setDescription("show user");
        user.setAge(100);
        user.setUsername("test");
        return user;
    }

當參數是復雜類型(非原始類或及其包裝類)時,就需要用到@ApiModel@ApiModelProperty

@Data
@ApiModel
public class User {
    @ApiModelProperty(notes = "用戶id",required = false,dataType="Integer")
    private Integer id;
    @NotBlank
    @ApiModelProperty(notes = "用戶名",required = true,dataType="String")
    private String username;
    @NotNull
    @Max(100)
    @Min(1)
    @ApiModelProperty(notes = "年齡",required = true,dataType="Integer",allowableValues = "range[0,100]")
    private Integer age;
    @ApiModelProperty(notes = "描述",required = false,dataType="String")
    private String description;
}

注解說明:
@ApiOperation:對方法進行描述,說明方法作用
@ApiResponses:表示一組響應
@ApiImplicitParams:對方法的多個參數進行描述
@ApiImplicitParam:對單個的參數進行描述(name:參數名,value:參數的描述,dataType:參數類型,required:是否必須,paramType:參數來源方式)
@ApiModel:對復雜類型參數進行說明
@ApiModelProperty:對復雜類型字段進行說明

寫了這么多,讓我們看看最終的效果圖吧:

final

這就是最終出來的文檔頁面,那個Try it out!按鈕是用來進行接口測試的,你可以填入參數進行測試。

最后貼上工程代碼:
project code

如果用markdown編寫文章的話,強烈推薦小書匠,真的很好用,這篇文章就是用那個寫出來的?

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,443評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,530評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 176,407評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,981評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,759評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,204評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,263評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,415評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,955評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,650評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,892評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,675評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,967評論 2 374

推薦閱讀更多精彩內容

  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,898評論 6 342
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,659評論 25 708
  • 你,終會明白 有些人 要等 有些事 很順 有些時候 得熬 等有等的必要 順有順的條件 熬有熬的價值 無論怎樣 都是...
    Mr_Zoul閱讀 268評論 0 0
  • 一維空間是直線,二維空間是平面,三維空間是立體,每一維空間都是相對于它的上維空間才能封閉的(上文說過),一維直線是...
    一如當初月閱讀 2,840評論 1 0
  • 煙波嫌水瘦!不肯動情深。 捉紋撩秋意,別怨風流人。
    撲忒閱讀 272評論 0 3