天天看点

swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox

1.说明

现在SWAGGER官网主要提供了几种开源工具,提供相应的功能。可以通过配置甚至是修改源码以达到你想要的效果。

swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox

Swagger Codegen: 通过Codegen 可以将描述文件生成html格式和cwiki形式的接口文档,同时也能生成多钟语言的服务端和客户端的代码。支持通过jar包,docker,node等方式在本地化执行生成。也可以在后面的Swagger Editor中在线生成。

Swagger UI:提供了一个可视化的UI页面展示描述文件。接口的调用方、测试、项目经理等都可以在该页面中对相关接口进行查阅和做一些简单的接口请求。该项目支持在线导入描述文件和本地部署UI项目。

Swagger Editor: 类似于markendown编辑器的编辑Swagger描述文件的编辑器,该编辑支持实时预览描述文件的更新效果。也提供了在线编辑器和本地部署编辑器两种方式。

Swagger Inspector: 感觉和postman差不多,是一个可以对接口进行测试的在线版的postman。比在Swagger UI里面做接口请求,会返回更多的信息,也会保存你请求的实际请求参数等数据。

Swagger Hub:集成了上面所有项目的各个功能,你可以以项目和版本为单位,将你的描述文件上传到Swagger Hub中。在Swagger Hub中可以完成上面项目的所有工作,需要注册账号,分免费版和收费版。

Springfox Swagger: Spring 基于swagger规范,可以将基于SpringMVC和Spring Boot项目的项目代码,自动生成JSON格式的描述文件。本身不是属于Swagger官网提供的,在这里列出来做个说明,方便后面作一个使用的展开。

2.swagger Editor编写文档

swagger editor 的语法格式是yml的格式,通过缩进配置文件。简单示例:

swagger: "2.0"
info:   #文档头开始标签
  title: "swagger介绍文档"  #文档的标题
  version: "1.0.1"      #文档的版本号
  description: "这是swagger的介绍文档" #文档的具体描述  
  contact:    #文档开发者介绍
    name: "开发人员:xiaoxu"  #开发人员
    url: "www.xjqcomeon.top"  #开发者的联系网址
    email: "[email protected]"  #开发者的Email邮箱
host: "www.xjqcomeon.top"   #请求api的域名
basePath: "/api/v1.0"     #请求api的标识符

#api类目
tags:
  #类目一
- name: "api类目一"
  description: "api类目一具体描述"
  #类目二
- name: "api类目二"
  description: "api类目二具体描述"

#请求头协议配置
schemes:
- "请求头协议"
- "http"
- "https"

#具体api配置
paths:
  #api实例
  /api/stuManager:    #api的路径
    post:   #请求方式遵循rest规范,get,post,put,delete等
      tags: #这个api属于哪个类目下,可以存在多个类目
      - "api类目一"
      summary: "插入学生信息"  #api的介绍
      description: "这个api可以插入学生信息"  #api的具体描述
      consumes:     #参数从前端传输的格式
      - "application/json"
      - "application/xml"
      produces:
      - "application/xml"
      - "application/json"
      parameters:   #参数配置
      - in: "String"  #参数类型
        name: "body"  #参数名
        description: "这是其中一个参数" #参数介绍
        required: true    #这个参数是否必须
      responses:    #后端响应状态码
        "200":
          description: "ok"
        "405":
          description: "Invalid input"
          
    put:
      tags:
      - "api类目一"
      summary: "Update an existing pet"
      description: ""
      operationId: "updatePet"
      consumes:
      - "application/json"
      - "application/xml"
      produces:
      - "application/xml"
      - "application/json"
      parameters:
      - in: "body"
        name: "body"
        description: "Pet object that needs to be added to the store"
        required: true
        scheme: ""
      responses:
        "400":
          description: "Invalid ID supplied"
        "404":
          description: "Pet not found"
        "405":
          description: "Validation exception"

#model的配置
definitions:
#示例model配置
  Order:    #model名
    type: "object"  #model的类型
    properties:     #model的参数
      id:
        type: "integer"
        format: "int64"
      petId:
        type: "integer"
        format: "int64"
      quantity:
        type: "integer"
        format: "int32"
      shipDate:
        type: "string"
        format: "date-time"
      status:
        type: "string"
        description: "Order Status"
        enum:
        - "placed"
        - "approved"
        - "delivered"
      complete:
        type: "boolean"
        default: false
    xml:
      name: "Order"
      
           
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox

是不是发现直接写文档,很让人崩溃,要是能根据代码一键生成该多好啊!!

所以spring fox他来了!

3.springfox

是一个开源的API Doc的框架, 它的前身是swagger-springmvc,可以将我们的Controller中的方法以文档的形式展现。官方定义为: Automated JSON API documentation for API’s built with Spring

话不多说:直接淦

3.1 使用方法

3.1.1 导入springfox依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>


           

3.1.2 创建controller

@RestController
@RequestMapping("/api")
public class StudentController {

    @RequestMapping(value = "/stu",method = RequestMethod.GET)
    public String getStudent(String id){
        return "student";
    }

    @PostMapping("/stu")
    public String inset(String username,String pwd){
        return "success";
    }

}
           

3.1.3 开启swagger2的注解@EnableSwagger2

@SpringBootApplication
@EnableSwagger2
public class SwaggerApplication {

	public static void main(String[] args) {
		SpringApplication.run(SwaggerApplication.class, args);
	}

}
           

3.1.4 启动项目,访问/swagger-ui.html

swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox

是不是很爽,不需要写一行yml配置,就自动生成了接口文档。

但是我们发现这个文档生成的很简陋,不符合我们具体的需要,能够定制那就更好了。

3.2 swagger 定制化配置

3.2.1 自定义文档的标题部分

为spring容器添加配置类Docket对象

@Configuration
public class SwaggerConf {

    @Bean
    public Docket getDocket(){
        //创建Docket对象,参数为创建的文档的类型
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        //创建 ApiInfo对象,为文档的信息进行配置
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("自定义swagger文档标题")    //设置文档的标题
                .version("1.2")                   //设置文档的版本号
                .description("这是这个文档的具体描述") //文档的具体描述
                .contact(new Contact("开发者:xiaoxu",
                        "www.xjqcomeon.top","[email protected]"))  //文档开发者的信息
                .build();

        docket.apiInfo(apiInfo)
                .select()
                //设置扫描特定包生成接口
                .apis(RequestHandlerSelectors.basePackage("com.xjq.swagger.controller"))
                .build();
        return docket;

    }

}
           
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox

3.2.2 @Api注解使用

使用位置:@Target({ElementType.TYPE}) 只能使用在类上

常用参数:

  • String value() default “” 这个类目的值 没有找到显示的位置
  • String[] tags() default {""}; 这个类中解析的接口属于哪几个类目
  • String description() default “”; 这个类中所有接口的描述
  • 完整参数说明
@Api(value = "学生管理接口",tags = {"学生接口"},description = "这个这个学生接口类目的具体描述")
public class StudentController {
           
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox

3.2.3 @ApiOperation注解使用

使用位置:@Target({ElementType.METHOD, ElementType.TYPE}) 类和方法

常用参数:

  • String value(); 接口的名称
  • String notes() default “”; 接口的描述
  • String[] tags() default {""}; 接口属于哪些类目
  • 完整参数说明
@RequestMapping(value = "/stu",method = RequestMethod.GET)
    @ApiOperation(value = "getStu--value",notes = "getStu--notes",tags = {"学生接口","其他接口"})
    public String getStudent(String id){
        return "student";
    }
           
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox

3.2.4 @ApiParam注解使用

使用位置:@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD}) 参数,方法,字段

常用参数:

  • String name() default “”; 参数的描述
  • String value() default “”;参数名称,参数名称将从 filed/method/parameter 名称中派生,但你可以覆盖它,路径参数必须始终命名为它们所代表的路径部分
  • boolean required() default false 参数是否是必须
  • 完整参数说明
@RequestMapping(value = "/stu",method = RequestMethod.GET)
    @ApiOperation(value = "getStu--value",notes = "getStu--notes",tags = {"学生接口","其他接口"})
    public String getStudent(
            @ApiParam(value = "id--value",name = "id--name", required = true) String id){
        return "student";
    }
           
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox

3.2.5 @ApiResponses 和 @ApiResponse

使用位置:@Target({ElementType.METHOD}) 方法上

常用参数:

  • int code(); 响应状态码
  • String message(); 状态码介绍
  • 完整参数说明
@RequestMapping(value = "/stu",method = RequestMethod.GET)
    @ApiOperation(value = "getStu--value",notes = "getStu--notes",tags = {"学生接口","其他接口"})
    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "相应成功")
    })
    public String getStudent(
            @ApiParam(value = "id--value",name = "id--name", required = true) String id){
        return "student";
    }
           
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox

3.2.6 @ApiModel 和 @ApiModelProperty

使用位置:接口返回值为一个类,这个类可以使用这个注解

完整参数说明

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@ApiModel(value = "model--value",description = "model--description")
public class Student implements Serializable {
    @ApiModelProperty(value = "用户名",name = "name",required = true)
    private String username;
    @ApiModelProperty(value = "密码",name = "pwd",required = true)
    private String password;
}

           
swagger学习------swagger的介绍和使用1.说明2.swagger Editor编写文档3.springfox

3.2.7 更多配置

更多配置详解