前后端接口后端使用框架 | Swagger

Swagger是一个流行的API管理工具,支持API全生命周期管理。它通过代码注解简化文档,提供在线接口生成和测试功能,提高开发效率。本文介绍了Swagger的配置,如引入Springfox依赖,设置SwaggerConfig,并展示了如何使用诸如@Api、@ApiOperation等注解来文档化API。
摘要由CSDN通过智能技术生成

简介

Swagger是一款目前世界最流行的API管理工具。目前Swagger已经形成一个生态圈,能够管理API的整个生命周期,从设计、文档到测试与部署。Swagger有几个重要特性:

  • 代码侵入式注解
  • 遵循YAML文档格式
  • 非常适合三端(PC、iOS及Android)的API管理,尤其适合前后端完全分离的架构模式。
  • 减少没有必要的文档,符合敏捷开发理念
  • 功能强大

作用

  • 接口的文档在线自动生成
  • 功能测试

优点

  1. 大大减少前后端的沟通
  2. 方便查找和测试接口
  3. 提高团队的开发效率
  4. 方便新人了解项目

配置swagger

引入依赖

<!-- swagger -->
<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>

配置类

package com.lxs.upload.config;
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;
/**
* Swagger 配置文件
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
	@Bean
	public Docket createRestApi() {
	return new Docket(DocumentationType.SWAGGER_2)
		.apiInfo(apiInfo())
		.select()
		.apis(RequestHandlerSelectors.basePackage("com.lxs.upload")) //swagger搜索的包
		.paths(PathSelectors.any()) //swagger路径匹配
		.build();
	}
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
			.title("文件上传文档")
			.description("使用FastDfs文件上传")
			.version("version 1.0")
			.build();
	}
}

常用注解

swagger通过在controller中,声明注解,API文档进行说明

1、@Api():用在请求的类上,表示对类的说明,也代表了这个类是swagger2的资源
参数:

tags:说明该类的作用,参数是个数组,可以填多个。
value=“该参数没什么意义,在UI界面上不显示,所以不用配置”
description = “用户基本信息操作”

2、@ApiOperation():用于方法,表示一个http请求访问该方法的操作
参数:

value=“方法的用途和作用”
notes=“方法的注意事项和备注”
tags:说明该方法的作用,参数是个数组,可以填多个。
格式:tags={“作用1”,“作用2”}
(在这里建议不使用这个参数,会使界面看上去有点乱,前两个常用)

3、@ApiModel():用于响应实体类上,用于说明实体作用
参数:

description=“描述实体的作用”

4、@ApiModelProperty:用在属性上,描述实体类的属性
参数:

value=“用户名” 描述参数的意义
name=“name” 参数的变量名
required=true 参数是否必选

5、@ApiImplicitParams:用在请求的方法上,包含多@ApiImplicitParam
6、@ApiImplicitParam:用于方法,表示单独的请求参数
参数:

name=“参数ming”
value=“参数说明”
dataType=“数据类型”
paramType=“query” 表示参数放在哪里
· header 请求参数的获取:@RequestHeader
· query 请求参数的获取:@RequestParam
· path(用于restful接口) 请求参数的获取:@PathVariable
· body(不常用)
· form(不常用)
defaultValue=“参数的默认值”
required=“true” 表示参数是否必须传

7、@ApiParam():用于方法,参数,字段说明 表示对参数的要求和说明
参数:

name=“参数名称”
value=“参数的简要说明”
defaultValue=“参数默认值”
required=“true” 表示属性是否必填,默认为false

8、@ApiResponses:用于请求的方法上,根据响应码表示不同响应
一个@ApiResponses包含多个@ApiResponse
9、@ApiResponse:用在请求的方法上,表示不同的响应
参数:

code=“404” 表示响应码(int型),可自定义
message=“状态码对应的响应信息”

10、@ApiIgnore():用于类或者方法上,不被显示在页面上

使用

实体类

@ApiModel("用户对象模型")
public class User {
	private Long id;
	private String username;
	private String password;
	private String email;
}

controller

package com.lxs.upload.controller;
import com.lxs.upload.domain.User;
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.xml.ws.Response;
/**
* /user post 新增
* /{id} delete 删除
* /{id} put 更新
* /{id} get 根据id加载
* /list-page post 分页查询
*/
@RestController
@RequestMapping("/user")
@Api(tags = {"用户管理API"})
public class UserController {
	@PostMapping
	@ApiOperation(value = "新增用户", notes = "新增后返回当前用户")
	@ApiResponses({
	@ApiResponse(code = 200, message = "返回成功", response = User.class),
	@ApiResponse(code = 400, message = "参数没有填好(id==1)", response = User.class),
	@ApiResponse(code = 401, message = "权限不足(id==1)", response = User.class),
	})
	public ResponseEntity<User> add(User user) {
		if (user.getId() == 1) {
			return new ResponseEntity<>(user, HttpStatus.BAD_REQUEST); //400
		} else if (user.getId() == 2) {
			return new ResponseEntity<>(user, HttpStatus.UNAUTHORIZED); //401
		} else {
			return ResponseEntity.ok(user);
		}
	}
	@PutMapping
	@ApiOperation(value = "修改用户", notes = "修改后返回当前用户")
	@ApiResponses({
	@ApiResponse(code = 200, message = "返回成功", response = User.class),
	@ApiResponse(code = 400, message = "参数没有填好(id==1)", response = User.class),
	@ApiResponse(code = 401, message = "权限不足(id==1)", response = User.class),
	})
	public ResponseEntity<User> update(User user) {
		if (user.getId() == 1) {
			return new ResponseEntity<>(user, HttpStatus.BAD_REQUEST); //400
		} else if (user.getId() == 2) {
			return new ResponseEntity<>(user, HttpStatus.UNAUTHORIZED); //401
		} else {
			return ResponseEntity.ok(user);
		}
	}
	@DeleteMapping("/{id}")
	@ApiOperation(value = "删除用户", notes = "删除后返回当前id")
	@ApiResponses({
	@ApiResponse(code = 200, message = "返回成功", response = User.class),
	@ApiResponse(code = 400, message = "参数没有填好(id==1)", response = User.class),
	@ApiResponse(code = 401, message = "权限不足(id==1)", response = User.class),
	})
	@ApiImplicitParam(paramType = "path", name = "id", value = "用户主键ID", required = true)
	public ResponseEntity<Long> delete(@PathVariable Long id) {
		if (id == 1) {
			return new ResponseEntity<>(id, HttpStatus.BAD_REQUEST); //400
		} else if (id == 2) {
			return new ResponseEntity<>(id, HttpStatus.UNAUTHORIZED); //401
		} else {
			return ResponseEntity.ok(id);
		}
	}
	@GetMapping("/{id}")
	@ApiIgnore
	public ResponseEntity<Long> toUpdate(@PathVariable Long id) {
		if (id == 1) {
			return new ResponseEntity<>(id, HttpStatus.BAD_REQUEST); //400
		} else if (id == 2) {
			return new ResponseEntity<>(id, HttpStatus.UNAUTHORIZED); //401
		} else {
			return ResponseEntity.ok(id);
		}
	}
	@PostMapping("/list-page")
	@ApiOperation(value = "分页查询", notes = "得到分页查询对象pageInfo")
	@ApiImplicitParams({
	@ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页", required = false, defaultValue = "1"),
	@ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页行数",required = false, defaultValue = "10")
	})
	public ResponseEntity<String> findByPage(@RequestParam(defaultValue = "1", required = false)
		Integer pageNum, @RequestParam(defaultValue = "10", required = false) Integer pageSize) {
		return ResponseEntity.ok("find page result...");
	}
}

结果

在这里插入图片描述
使用swagger测试文件上传

在这里插入图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
RuoYi是一个基于Spring Boot开发的前后端分离的快速开发平台,它的使用的是Vue.js框架后端使用的是Spring Boot框架。在开发过程中,我们通常需要对接口文档进行管理和测试,这就需要使用Swagger进行接口文档的生成和测试。那么如何访问Swagger呢? 1. 在后端项目中添加Swagger依赖 在pom.xml中添加以下依赖: <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> 2. 添加Swagger配置类 在后端项目中添加配置类SwaggerConfig,配置Swagger相关信息: @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("top.ruoyun.admin.system.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("RuoYi APIs") .description("Restful APIs document") .version("1.0") .build(); } } 3. 启动后端项目 启动后端项目,在浏览器中输入http://localhost:端口号/swagger-ui.html,即可进入Swagger页面。 4. 在项目中访问Swagger项目中添加axios依赖: npm install --save axios 在代码中使用axios进行接口访问: import axios from 'axios' //获取Swagger接口文档数据 export function getApiDocs() { return axios({ url: 'http://localhost:端口号/v2/api-docs', method: 'get' }) } //获取Swagger接口文档URL export function getApiDocsUrl() { return axios({ url: 'http://localhost:端口号/swagger-ui.html', method: 'get' }) } 在代码中调用getApiDocs()和getApiDocsUrl()函数,即可获取Swagger接口文档数据和URL。这样就可以在项目中访问Swagger,并进行接口文档的测试和管理了。 总的来说,在RuoYi前后端分离的开发过程中,访问Swagger的步骤比较简单,只需要在后端项目中添加Swagger依赖和配置类,然后在项目使用axios进行接口访问即可。通过Swagger使用,可以方便地管理和测试接口文档,提高开发效率和代码质量。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扑天鹰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值