如何在swgger中设置连接前后端的API接口

109 阅读4分钟

在的网站大多都是前后端分离式的开发,前后端都衍生出了自己的框架。现在前后端交互的唯一方式就是API接口。

曾经前后端交互都需要后端人员手动编写API接口文档,规定路径、请求方式、返回类型,这样效率很低。

swagger就是更好地书写API文档的框架。

二、swagger介绍

swagger可以根据后台接口自动生成可视化的restful风格的API文档,并可以进行API测试(发送各种请求,测试接口)

1、前端人员不用再去理解后端代码,后端人员也不用专门编写接口文档。
2、swagger直接自动生成可供测试、可视化的API文档,前端人员在不知道后端代码的情况下,也能根据swagger提供的API文档理解每个接口的作用,并可以测试接口是否能够正常使用。

三、在maven+springboot项目中使用swagger

1.首先在pom.xml中导入依赖

 springfox-swagger2是swagger的java实现
springfox-swagger-ui是网页上显示swagger文档的jar包

<!--swagger jar包-->
   <dependency>
       <groupId>io.springfox</groupId>
       <artifactId>springfox-swagger2</artifactId>
       <version>2.8.0</version>
   </dependency>
   <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.8.0</version>
   </dependency>
<!--swagger jar包-->

2.编写swagger配置文件 

创建一个config文件夹,在文件夹里创建SwaggerConfig.java文件作为我们的swagger配置文件。

 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
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;
 
@Configuration // 标注一个配置类
@EnableSwagger2 // 提供swagger注解
@ComponentScan("whu.xsy.swagger_use.controller")//扫描控制器包下的文件
public class SwaggerConfig {
 
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }
 
    //展现API文档的基本信息
    private ApiInfo apiInfo(){
    	//联系人信息(展现在主页)
        Contact contact = new Contact("xsy",
                "","827041735@qq.com");
        return new ApiInfoBuilder()
                .title("测试swagger")
                .description("测试swagger对于接口的展示和调用")
                .contact(contact)
                .version("1.1.0")
                .build();
    }
}
  1. 创建实体类Student
注解作用
@ApiModel标注在实体类上,value=类名描述
@ApiModelProperty标注在属性上,value=字段描述,required默认为false,如果是不可缺少的字段,比如主键,required则要变成true
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
 
@ApiModel(value = "学生类")
public class student {
 
    @ApiModelProperty(value = "学号",required = true)
    private int id;
 
    @ApiModelProperty(value = "姓名")
    private String name;
 
    public student() {}
 
    public student(int id, String name) {
        this.id = id;
        this.name = name;
    }
 
    public int getId() { return id; }
 
    public void setId(int id) { this.id = id; }
 
    public String getName() { return name; }
 
    public void setName(String name) { this.name = name; }
}

4.创建控制器studentController(此处用List模拟数据库)

注解作用
@Api标注在类上,tags则为类的名字,会展示给前端
@ApiOperation标注在方法上,value简单地概括方法的用处,notes则描述方法的使用
@ApiImplicitParam标注在方法上,用于描述参数字段,name是参数的名字(一定要与@Requestparam、@PathVariable、或者传递的类中的字段名相同,否则会在前端显示新的参数),required默认为false,如果是不可缺少的字段,则要改为true
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import whu.xsy.swagger_use.entity.student;
 
import java.util.ArrayList;
import java.util.List;
 
 
@RestController
@RequestMapping("/student")
@Api(value = "studentController", tags = "学生模块") //标注在类上的
public class studentController {
 
    //模拟数据库
    private static List<student> students = new ArrayList<>();
 
    //初始化模拟数据库
    static{
        students.add(new student(1,"xsy"));
        students.add(new student(2,"theory"));
    }
 
    @ApiOperation(
            value = "获取所有学生信息",
            notes = "获取所有学生的学号和姓名"
    )
    @GetMapping("")
    public List<student> getAll(){
        return students;
    }
 
 
 
    @ApiOperation(
            value = "获取单个学生",
            notes = "根据id查询学生,id为整数,返回学生实体,没查到则返回null"
    )
    @ApiImplicitParam(value = "学生学号", name = "id",paramType = "path")
    @GetMapping("/{id}")
    public student getById(@PathVariable("id") int id){
        for (student s : students) {
            if(s.getId() == id)
                return s;
        }
        return null;
    }
 
 
 
    @ApiOperation(
            value = "添加单个学生",
            notes = "前端上传学生信息(学号,姓名)"
    )
    //此处 name 一定要与student中的变量名相同,否则在前端会生成新的parameter
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学生学号",name = "id",paramType = "query"),
            @ApiImplicitParam(value = "学生姓名",name = "name",paramType = "query")
    })
    @PostMapping("")
    public boolean add(student student){
        return students.add(student);
    }
 
 
 
    @ApiOperation(
            value = "更新单个学生",
            notes = "前端上传学生信息(学号,姓名),学号相同则会更新"
    )
    //此处 name 一定要与student中的变量名相同,否则在前端会生成新的parameter
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学生学号",name = "id",paramType = "query"),
            @ApiImplicitParam(value = "学生姓名",name = "name",paramType = "query")
    })
    @PutMapping("")
    public boolean update(student student){
        for (student s : students) {
            if(s.getId() == student.getId()) {
                students.set(students.indexOf(s), student);
                return true;
            }
        }
        return false;
    }
 
 
 
    @ApiOperation(
            value = "删除单个学生",
            notes = "根据学生id删除某个学生"
    )
    @ApiImplicitParam(value = "学生学号", name = "id",paramType = "path")
    @DeleteMapping(value = "/{id}")
    public boolean deleteById(@PathVariable("id") int id){
        for (student s : students) {
            if(s.getId() == id)
                return students.remove(s);
        }
        return false;
    }
}
  1. 输入localhost:8080/swagger-ui.html,打开swagger-ui界面

6. 查看并测试API接口 

进入post方法,parameters展示了后台接收的参数,后面的描述对应ApiImplicitParam中的value,点击Try it out输入参数值后点击Execute运行

然后就可以在下方查看到后台返回结果了 

  1. 验证是否真的上传成功

同样的操作使用获取所有学生信息的GET接口,可以发现刚刚插入的id为3,名字为ys的学生已经插入了

四、swagger在项目中的好处

  • 前后端可以只通过swagger-ui.html交互,前端完全不需要后台代码,只用看API文档就可以调用相应接口。
  • 有时需要往数据库中插入测试数据,但是不建议直接操作数据库加入数据,直接在数据库中加入的时候有时会影响后台插入数据,而后台又需要写代码插入不同数据,非常麻烦,使用swagger-ui调用post方法,可视化地去添加数据,方便快捷。
  • 及时更新。后台代码更新后,无需后台人员区更改API接口文档,swagger直接同步了。