Swagger代码实战

什么是Swagger

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。Swagger API文档工具可以满足下列需求:

  • 支持项目中的API接口自动生成同步的在线文档。
  • 生成的API文档可用于项目内部API审核,查看等。
  • 通过Swagger实时的API接口同步功能,方便测试人员和接口调用者动态了解API及其变化。
  • 这些文档可作为客户产品文档的一部分进行发布。
  • 支持API规范生成代码,生成的客户端和服务器端骨架代码可以加速开发和测试速度。

常用到的注解有:

@Api :用在类上,说明该类的作用
@ApiOperation :用在方法上,说明方法的作用
@ApiImplicitParams :用在方法上包含一组参数说明
@ApiImplicitParam :用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
    paramType:参数放在哪个地方
        header-->请求参数的获取:@RequestHeader
        query-->请求参数的获取:@RequestParam
        path(用于restful接口)-->请求参数的获取:@PathVariable
        body(不常用)
        form(不常用)
    name:参数名
    dataType:参数类型
    required:参数是否必须传
    value:参数的意思
    defaultValue:参数的默认值
@ApiResponses :用于表示一组响应
@ApiResponse :用在@ApiResponses中,一般用于表达一个错误的响应信息
    code:数字,例如400
    message:信息,例如"请求参数没填好"
    response:抛出异常的类
@ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:描述一个model的属性

@API注解:

用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式:

@Api(value = "/user", description = "Operations about user")

与Controller注解并列使用。 属性配置:

属性名称                 备注
value                  url的路径值("别用!!!会在url上显示该值")
tags                   如果设置这个值、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 将在文档中隐藏

代码实战

控制器类

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的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",paramType = "query",value = "用户名",required = true),
            @ApiImplicitParam(name = "age",paramType = "query",value = "年龄",required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 401,message = "你没权限"),
            @ApiResponse(code = 403,message = "你被禁止访问了"),
            @ApiResponse(code = 404,message = "没找到,哈哈哈")
    })
    @ApiOperation("获取个人信息") //说明方法的作用
    @GetMapping("getInfo")
    public CreatePersonRequest getInfo(@RequestParam String name,@RequestParam Integer age){  //@RequestParam,用来直接获取URL中的参数
        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 {
    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     *
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//api接口包扫描路径
                .paths(PathSelectors.any()) //可以根据url路径设置哪些请求加入文档,忽略哪些请求
                .build();
    }

    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("myJson API")  //设置文档的标题
                .description("我的demo") //设置文档的描述
                .termsOfServiceUrl("http://192.168.10.3/")
                .contact(new Contact("黄宝玲","","[email protected]"))
                .version("1.0")
                .build();
    }

//    @Override
//    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
//    }

}
15296782-43daeb117db9c0de.png
本地运行代码,服务使用8080端口

接口上方的信息是在配置文件中设置的,我们主要看接口的信息,有点像restful API,最左边是请求类型,put、post、get等等,然后是url,再是描述。

15296782-93a696ab9760e791.png
在本地浏览器访问本地8080端口的swagger-ui.html#
15296782-1b63176bcecfd9e4.png
接口详情,点击try it out编写信息
15296782-7249c0c6f99c98c3.png
点击excute执行
15296782-7d13c3349e06a6d1.png
可以看到请求头、URL、请求体、返回响应等信息

猜你喜欢

转载自blog.csdn.net/weixin_34356138/article/details/86830928