swagger介绍及使用方法

swagger介绍使用方法

1 swagger的介绍

1、是一款让你更好的书写API文档规范且完整的框架。

2、提供描述、生产、消费和可视化RESTful Web Service。

3、是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业API管理的方方面面。

2 添加依赖

2.1 使用第三方依赖

1.在pom文件中添加第三方swagger依赖

	<dependency>
		<groupId>com.spring4all</groupId>
		<artifactId>swagger-spring-boot-starter</artifactId>
		<version>1.7.0.RELEASE</version>
	</dependency>

2.在SpringBoot项目的启动了上添加@EnableSwagger2Doc注解,就可以直接使用啦。

package com.marvin.demo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
@SpringBootApplication
@EnableSwagger2
public class SwaggerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SwaggerApplication.class);
    }
}

3、https://github.com/SpringForAll/spring-boot-starter-swagger这是GitHub上这个swagger依赖实现的项目,里面有详细的讲解。

2.2使用官方依赖

1.在pom.xml文件中添加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>

第一个是API获取的包,第二是官方给出的一个ui界面。这个界面可以自定义,默认是官方的,对于安全问题,以及ui路由设置需要着重思考。

2.2.1swagger的configuration

需要特别注意的是swagger scan base package,这是扫描注解的配置,即你的API接口位置。

package com.example.demo.config;

import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("利用swagger构建api文档")
                .description("简单使用swagger2")
                .version("1.0")
                .build();
    }
}

3 swagger的基本注解介绍

swagger通过注解生成接口文档,包括接口名、请求方法、参数、返回信息的等等。

注解作用处作用
@Api用于类修饰整个类,描述Controller的作用
@ApiOperation用于方法描述一个类的一个方法,或者说一个接口
@ApiParam用于方法,参数,字段说明单个参数描述
@ApiModel用于类用对象实体来作为入参
@ApiProperty用对象接实体收参数时,描述对象的一个字段
@ApiResponseHTTP响应其中1个描述
@ApiResponsesHTTP响应整体描述
@ApiIgnore用于类,方法,方法参数使用该注解忽略这个API
@ApiError发生错误返回的信息
@ApiImplicitParam用于方法一个请求参数
@ApiImplicitParams用于方法多个请求参数

3.1 @Api修饰整个类,描述Controller的作用

用于类;表示标识这个类是swagger的资源

  • tags–表示说明
  • value–也是说明,可以使用tags替代

但是tags如果有多个值,会生成多个list

@Api(value="用户controller",tags={"用户操作接口"})
@RestController
public class UserController {
 
}

img

3.2 @ApiOperation

用于描述一个方法或者接口

表示一个http请求的操作

  • value用于方法描述
  • notes用于提示内容
  • tags可以重新分组(视情况而用)

可以添加的参数形式:@ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”)

    @RequestMapping(value = "/hello",method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "入口请求",notes = "请求首页",httpMethod = "GET",response = String.class)
    public String testHello(@RequestParam("username") String username,int id){
        System.out.println("username:"+username+"==id:"+id);
        return "ok:"+username;
    }

image-20210922143211960

3.3 @ApiParam单个参数描述

用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)

  • name–参数名
  • value–参数说明
  • required–是否必填

@ApiParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”,dateType="变量类型”,paramType="请求方式”)

    @RequestMapping("/swagger")
    @ResponseBody
    @ApiOperation(value = "根据用户名获取用户的信息",notes = "查询数据库中的记录",httpMethod = "POST",response = String.class)
    @ApiImplicitParam(name = "userName",value = "用户名",required = true,dataType = "String",paramType = "query")
    public String getUserInfo(String userName) {
        return "1234";
    }

image-20210922143447606

3.4 @ApiImplicitParam 一个请求参数

用于方法
表示单独的请求参数

@ApiImplicitParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”,dateType="变量类型”,paramType="请求方式”)

    @RequestMapping("/swagger")
    @ApiOperation(value = "根据用户名获取用户的信息",notes = "查询数据库中的记录",httpMethod = "POST",response = String.class)
    @ApiImplicitParam(name = "userName",value = "用户名",required = true,dataType = "String",paramType = "query")
    public String getUserInfo(String userName) {
        return "1234";
    }

image-20210922143558421

3.5 @ApiImplicitParams 多个请求参数

用于方法,包含多个 @ApiImplicitParam

  • name–参数ming
  • value–参数说明
  • dataType–数据类型
  • paramType–参数类型
  • example–举例说明

参数和@ApiImplicitParam一致,只是这个注解可以添加多个参数而已

    @RequestMapping(value = "/getuserinfobynickname",method = {RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value = "根据用户昵称获取用户信息",notes = "查询数据库中的记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nickName",value = "用户的昵称",paramType = "query",dataType = "String",required = true),
            @ApiImplicitParam(name = "id",value = "用户的ID",paramType = "query",dataType = "int",required = true)
    })
    public String getUserInfoByNickName(String nickName, int id) {
        System.out.println("id:"+id+"--nickName:"+nickName);
        return "1234";
    }

image-20210922143636549

可以直接进行测试

image-20210922142723303

image-20210922142744120

3.6 @ApiModel()

用于类 ;表示对类进行说明,用于参数用实体类接收

  • value–表示对象名
  • description–描述

都可省略

3.7 @ApiModelProperty()

用于方法,字段; 表示对model属性的说明或者数据操作更改

  • value–字段说明
  • name–重写属性名字
  • dataType–重写属性类型
  • required–是否必填
  • example–举例说明
  • hidden–隐藏
@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable{
    private static final long serialVersionUID = 1L;
     @ApiModelProperty(value="用户名",name="username",example="xingguo")
     private String username;
     @ApiModelProperty(value="状态",name="state",required=true)
      private Integer state;
      private String password;
      private String nickName;
      private Integer isDeleted;
 
      @ApiModelProperty(value="id数组",hidden=true)
      private String[] ids;
      private List<String> idList;
     //省略get/set
}
  @ApiOperation("更改用户信息")
  @PostMapping("/updateUserInfo")
  public int updateUserInfo(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){
 
     int num = userService.updateUserInfo(user);
     return num;
  }

3.8 @ApiIgnore()

用于类或者方法上,可以不被swagger显示在页面上
比较简单, 这里不做举例

3.9 对应的实体说明:

package com.example.demo.pojo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "用户注册的实体")
public class Register {
    @ApiModelProperty(name = "userName",notes = "用户名",dataType = "String",required = true)
    private String userName;

    @ApiModelProperty(name = "nickName",notes = "用户昵称",dataType = "String",required = true)
    private String nickName;

    @ApiModelProperty(name = "age",notes = "用户年龄",dataType = "int",required = true)
    private int age;
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Register{" +
                "userName='" + userName + '\'' +
                ", nickName='" + nickName + '\'' +
                ", age=" + age +
                '}';
    }
}

4 测试地址

默认地址:

http://localhost:8080/swagger-ui.html

附录

IndexController代码

package com.example.demo.controller;

import com.example.demo.pojo.Register;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(value="用户controller",description="入口接口",tags={"入口接口"})
public class IndexController {
//    @RequestMapping(value = "/userregister",method = {RequestMethod.GET,RequestMethod.POST})
    //@RequestMapping(value = "/userregister",method = {RequestMethod.POST})
//    @ResponseBody
//    @ApiOperation(value = "register",notes = "注册的实体类")

//    @RequestMapping(value = "/hello",method = {RequestMethod.GET,RequestMethod.POST})
//    @ApiOperation(value = "入口请求",notes = "请求首页",httpMethod = "GET",response = String.class)
//    @RequestBody
//    @ApiImplicitParam(name = "username",value = "请求人姓名",required = true,dataType="String",paramType="query")

    @RequestMapping(value = "/hello",method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "入口请求",notes = "请求首页",httpMethod = "GET",response = String.class)
    @ApiImplicitParam(name = "username",value = "请求人姓名",required = true,dataType="String",paramType="query")
    public String testHello(@RequestParam("username") String username,int id){
        System.out.println("username:"+username+"==id:"+id);
        return "ok:"+username;
    }


    @RequestMapping("/swagger")
    @ResponseBody
    @ApiOperation(value = "根据用户名获取用户的信息",notes = "查询数据库中的记录",httpMethod = "POST",response = String.class)
    @ApiImplicitParam(name = "userName",value = "用户名",required = true,dataType = "String",paramType = "query")
    public String getUserInfo(String userName) {
        return "1234";
    }

    @RequestMapping(value = "/getuserinfobynickname",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "根据用户昵称获取用户信息",notes = "查询数据库中的记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nickName",value = "用户的昵称",paramType = "query",dataType = "String",required = true),
            @ApiImplicitParam(name = "id",value = "用户的ID",paramType = "query",dataType = "int",required = true)
    })
    public String getUserInfoByNickName(String nickName, int id) {
        System.out.println("id:"+id+"--nickName:"+nickName);
        return "1234";
    }

    @RequestMapping(value = "/getuserinfobyid",method = {RequestMethod.POST,RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "根据用户id获取用户信息",notes = "查询数据库中的记录",httpMethod = "POST")
    public String getUserInfoById(@ApiParam(name = "nickName",value = "用户的昵称",required = true,defaultValue = "123-默认值")
                                          String nickName,
                                  @ApiParam(name = "id",value = "用户ID",required = true)
                                          Integer id) {

        System.out.println("id:"+id+"--nickName:"+nickName);
        return "1234";
    }

    @RequestMapping(value = "/userregister",method = {RequestMethod.GET,RequestMethod.POST})
    //@RequestMapping(value = "/userregister",method = {RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "register",notes = "注册的实体类")
    public Register userRegister(Register register) {
        System.out.println(register.toString());
        return register;
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Swagger是一种用于RESTful API的开源框架,它可以根据API源代码生成交互式文档。Swagger还可以用于创建API客户端,以便开发人员可以轻松地将API集成到应用程序中。此外,Swagger还具有强大的测试和调试功能,可以帮助开发人员更有效地测试和集成API。 ### 回答2: Swagger是一种用于构建、设计、文档化和使用RESTful Web服务的开源工具。它提供了一种简单易用的方式来描述和展示Web API的功能和操作,并且允许开发者更轻松地与API进行交互。 Swagger的主要功能包括API文档自动生成、API可视化展示和API的测试和调试。通过Swagger,开发者可以使用简单的注解来描述API的参数、返回类型、路径和操作等细节,然后利用Swagger的代码生成器自动生成文档和客户端SDK。 API文档是Swagger的核心功能之一。通过Swagger,开发者可以使用Swagger注解来定义API的信息和细节,然后利用Swagger UI生成具有交互性和可视化展示的API文档。这样,开发者可以在不阅读源代码的情况下,直观地了解API的使用方法和功能。 除了文档生成,Swagger还提供了API的测试和调试功能。开发者可以利用Swagger UI直接在浏览器中进行API的测试,输入相关参数并查看API的响应结果。这样,开发者可以更便捷地验证API的正确性和性能,并且能够快速定位问题所在。 总结来说,Swagger是一种强大而灵活的工具,可以大幅度提升开发者在构建和使用RESTful Web服务过程中的效率和便捷性。它通过自动生成文档、提供可视化展示和支持测试调试等功能,使得API的设计、开发和使用更加简单和直观。通过使用Swagger,开发者可以更轻松地构建和管理高质量的API,从而提升开发效率和用户体验。 ### 回答3: Swagger是一个开源的项目,用于构建、文档化和自动化测试RESTful Web服务的工具。它使用简单的注解方式来描述API的元数据,并基于这些元数据生成美观、易读的API文档。 使用Swagger可以轻松地创建API文档,这样开发人员和用户就可以清楚地了解每个API的功能,并根据需要进行测试和调用。Swagger的文档可以使用JSON或YAML格式创建,并提供了交互式UI界面来展示文档,并让用户轻松地尝试API的各种功能。 Swagger除了提供文档化的功能外,还可以生成客户端代码和服务端框架的代码。通过在API代码中使用Swagger的注解,可以根据API的定义自动生成客户端代码,从而简化了开发人员的工作。同时,Swagger还提供了许多集成插件,允许开发人员将API文档和代码集成到各种开发环境中,如IDE、浏览器插件等。 Swagger具有高度的灵活性和可扩展性,支持多种编程语言和框架,如Java、JavaScript、Python等。它还支持多种API标准,如OpenAPI规范(即Swagger规范)、RAML、GraphQL等。这些特性使得Swagger成为开发RESTful Web服务的首选工具之一。 总而言之,Swagger是一个功能强大、易用、灵活的API工具,可以帮助开发人员构建、文档化和自动化测试RESTful Web服务。通过使用Swagger,开发人员可以更好地管理和使用API,并提高开发效率和代码质量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值