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阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,367评论 6 343
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • 你,终会明白 有些人 要等 有些事 很顺 有些时候 得熬 等有等的必要 顺有顺的条件 熬有熬的价值 无论怎样 都是...
    Mr_Zoul阅读 242评论 0 0
  • 一维空间是直线,二维空间是平面,三维空间是立体,每一维空间都是相对于它的上维空间才能封闭的(上文说过),一维直线是...
    一如当初月阅读 2,705评论 1 0
  • 烟波嫌水瘦!不肯动情深。 捉纹撩秋意,别怨风流人。
    扑忒阅读 254评论 0 3