花10分钟写个漂亮的后端API接口模板!
ztj100 2025-05-11 19:43 18 浏览 0 评论
在这微服务架构盛行的黄金时段,加上越来越多的前后端分离,导致后端API接口规范变得越来越重要了。
比如:统一返回参数形式、统一返回码、统一异常处理、集成swagger等。
目的主要是规范后端项目代码,以及便于前端沟通联通以及问题的排查。
本文内容:
统一返回参数形式
目前主流的返回参数形式:
{
"code": 200000,
"message": "成功",
"data": {
"id": 1,
"userName": "tiange",
"password": "123456",
"phone": "18257160375",
"gender": 0,
"status": 0,
"createTime": "2024-05-17 20:24:40"
}
}
code是接口返回编码,message是消息提示,data是具体返回数据内容。
返回码
返回码定义很重要,我们应该可以参考HTTP请求返回的状态码(下面是常见的HTTP状态码):
200 - 请求成功
301 - 资源(网页等)被永久转移到其它URL
404 - 请求的资源(网页等)不存在
500 - 内部服务器错误
这样前端开发人员在得到返回值后,根据状态码就可以知道,大概什么错误,再根据message相关的信息描述,可以快速定位。
由于我们业务系统中可能会又大量的code,所以,我们对此做一个改良。
/**
* {@code @description:} 返回码
*
* @author tianwc
*
* {@code @date:} 2024-07-28 15:10
* {@code @version:} 1.0
*/
@Getter
public enum ResultCode implements Serializable {
SUCCESS(200000, "成功"),
FAIL(500000, "系统错误,请稍后重试!"),
USER_NOT_EXIST(401000, "用户不存在"),
USER_CANCELLED(401001, "用户已注销"),
USER_ROLE_ERROR(401002, "用户角色不对"),
NOT_FOUND(404000, "接口不存在"),
PARAMETER_ERROR(404001, "参数有误"),
PARAMETER_IS_NULL(404002, "参数为空");
private final int code;
private final String message;
ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
}
对此,我们还可以进一步细分,比如402开头的是用户相关的 、403开头又是xxx的,.....
这样后期如果又什么问题,这样就能快速定位到具体模块中。
统一返回
我们可以专门写一个类来对返回数据进行包装。
/**
* {@code @description:} 返回结果马甲
*
* @author tianwc
*
* {@code @date:} 2024-07-28 15:12
* {@code @version:} 1.0
*/
@Data
public class Result implements Serializable {
private Integer code;
private String message;
private Object data;
public Result(Integer code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
public static Result success() {
return new Result(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
}
public static Result success(Object data) {
return new Result(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
}
public static Result fail(ResultCode resultCode) {
return new Result(resultCode.getCode(), resultCode.getMessage(), null);
}
public static Result fail(int code, String message) {
return new Result(code, message, null);
}
}
我们定义了常用的四种格式。
具体使用如下:
我们在Service层和实现层:
public interface UserInfoService extends IService<UserInfo> {
Result findByCondition(UserInfoReqDto userInfoReqDto);
}
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
@Override
public Result findByCondition(UserInfoReqDto userInfoReqDto) {
Wrapper<UserInfo> wrapper = Wrappers.<UserInfo>lambdaQuery()
.eq(UserInfo::getUserName, userInfoReqDto.getUserName())
.eq(UserInfo::getPassword, userInfoReqDto.getPassword());
return Result.success(this.baseMapper.selectList(wrapper));
}
}
在controller层:我们会在controller层处理业务请求,并返回给前端 。
@RestController
@RequestMapping("/user/info")
public class UserInfoController {
@Resource
private UserInfoService userInfoService;
@GetMapping("/condition")
public Result findByCondition(UserInfoReqDto userInfoReqDto) {
return userInfoService.findByCondition(userInfoReqDto);
}
}
执行:
GET http://localhost:8089/user/info/condition?userName=tiange&password=123456
返回:
{
"code": 200000,
"message": "成功",
"data": [
{
"id": 1,
"userName": "tiange",
"password": "123456",
"phone": "18257160375",
"gender": 0,
"status": 0,
"createTime": "2024-05-17T20:24:40.000+00:00"
}
]
}
前端根据我们但会的code判断是否需要取data字段。
统一异常处理
统一异常处理我们分业务异常、系统异常以及参数异常:
业务异常
我们自定义一个业务异常:BusinessException
/**
* @author tianwc
* @version 1.0.0
* @date 2024-07-28 15:12
*
* <p>
* 自定义业务异常
*/
@Getter
public class BusinessException extends RuntimeException {
/**
* http状态码
*/
private Integer code;
private Object object;
public BusinessException(String message, Integer code, Object object) {
super(message);
this.code = code;
this.object = object;
}
public BusinessException(String message, Integer code) {
super(message);
this.code = code;
}
public BusinessException(ResultCode resultCode) {
super(resultCode.getMessage());
this.code = resultCode.getCode();
this.object = resultCode.getMessage();
}
public BusinessException(ResultCode resultCode, String message) {
this.code = resultCode.getCode();
this.object = message;
}
public BusinessException(String message) {
super(message);
}
}
异常处理:GlobalAdvice
@RestControllerAdvice
@Slf4j
public class GlobalAdvice {
@ExceptionHandler(Exception.class)
public Result doException(Exception e) {
log.error("统一异常处理机制,触发异常 msg ", e);
String message = null;
int errorCode = ResultCode.FAIL.getCode();
//自定义异常
if (e instanceof BusinessException) {
BusinessException exception = (BusinessException) e;
message = exception.getMessage();
errorCode = exception.getCode();
} else if (e instanceof HttpRequestMethodNotSupportedException) {
message = "不支持GET/POST方法";
} else if (e instanceof NoHandlerFoundException) {
message = "请求接口不存在";
} else if (e instanceof MissingServletRequestParameterException) {
errorCode = ResultCode.PARAMETER_IS_NULL.getCode();
message = String.format("缺少必要参数[%s]", ((MissingServletRequestParameterException) e).getParameterName());
} else if (e instanceof MethodArgumentNotValidException) {
BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
FieldError error = result.getFieldError();
errorCode = ResultCode.PARAMETER_IS_NULL.getCode();
message = error == null ? ResultCode.PARAMETER_ERROR.getMessage() : error.getDefaultMessage();
} else if (e instanceof BindException) {
errorCode = ResultCode.PARAMETER_IS_NULL.getCode();
message = ((BindException) e).getFieldError().getDefaultMessage();
} else if (e instanceof IllegalArgumentException) {
errorCode = ResultCode.PARAMETER_IS_NULL.getCode();
message = e.getMessage();
}
return Result.fail(errorCode, message);
}
}
使用:
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
@Override
public Result findByCondition(UserInfoReqDto userInfoReqDto) {
if("admin".equals(userInfoReqDto.getUserName())){
//对于某些业务问题抛出自定义异常
throw new BusinessException(ResultCode.USER_ROLE_ERROR);
}
Wrapper<UserInfo> wrapper = Wrappers.<UserInfo>lambdaQuery()
.eq(UserInfo::getUserName, userInfoReqDto.getUserName())
.eq(UserInfo::getPassword, userInfoReqDto.getPassword());
return Result.success(this.baseMapper.selectList(wrapper));
}
}
系统异常
假设系统异常:
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
@Override
public Result findByCondition(UserInfoReqDto userInfoReqDto) {
if("123456".equals(userInfoReqDto.getPassword())){
throw new RuntimeException("你的系统异常了");
}
Wrapper<UserInfo> wrapper = Wrappers.<UserInfo>lambdaQuery()
.eq(UserInfo::getUserName, userInfoReqDto.getUserName())
.eq(UserInfo::getPassword, userInfoReqDto.getPassword());
return Result.success(this.baseMapper.selectList(wrapper));
}
}
执行:
GET http://localhost:8089/user/info/condition?userName=tian&password=123456
返回结果:
{
"code": 500000,
"message": "系统异常",
"data": null
}
参数校验
添加pom依赖
<!--参数验证-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
请求参数:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfoReqDto {
@NotBlank(message = "姓名不能为空")
private String userName;
@NotBlank(message = "密码不能为空")
private String password;
}
其他相关注解:
注解作用@NotNull判断包装类是否为null@NotBlank判断字符串是否为null或者是空串(去掉首尾空格)@NotEmpty判断集合是否为空@Length判断字符的长度(最大或者最小)@Min判断数值最小值@Max判断数值最大值@Email判断邮箱是否合法
controller层添加注解@Validated
@RestController
@RequestMapping("/user/info")
public class UserInfoController {
@Resource
private UserInfoService userInfoService;
@GetMapping("/condition")
public Result findByCondition(@Validated UserInfoReqDto userInfoReqDto) {
return userInfoService.findByCondition(userInfoReqDto);
}
}
最后在统一异常处理里处理。
执行:
GET http://localhost:8089/user/info/condition?userName=tian
返回:
{
"code": 404002,
"message": "密码不能为空",
"data": null
}
执行:
GET http://localhost:8089/user/info/condition?password=123456
返回:
{
"code": 404002,
"message": "姓名不能为空",
"data": null
}
集成mybatis-plus
添加依赖
<!--mybatis-plus 依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
数据库信息配置:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/user-center?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456
mybatis-plus配置:
@Configuration
@MapperScan(basePackages = "com.tian.dao.mapper")
public class DataSourceConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
//注册乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource, MybatisPlusInterceptor interceptor) throws Exception {
MybatisSqlSessionFactoryBean ssfb = new MybatisSqlSessionFactoryBean();
ssfb.setDataSource(dataSource);
ssfb.setPlugins(interceptor);
//到哪里找xml文件
ssfb.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:mapper/*.xml"));
return ssfb.getObject();
}
}
实体类:
@TableName(value = "user_info")
@Data
public class UserInfo {
/**
* 主键ID
*/
@TableId(value = "id")
private Long id;
/**
* 姓名
*/
@TableField(value = "user_name")
private String userName;
/**
* 密码
*/
@TableField(value = "password")
private String password;
/**
* 手机号
*/
@TableField(value = "phone")
private String phone;
/**
* 性别,0:女,1:男
*/
@TableField(value = "gender")
private Integer gender;
/**
* 状态,0:正常,1:已注销
*/
@TableField(value = "status")
private Integer status;
/**
* 注册时间
*/
@TableField(value = "create_time")
private Date createTime;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
mapper:
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}
service部分代码参照前面的代码来。
执行
GET http://localhost:8089/user/info/condition?userName=tiange&password=123456
返回
{
"code": 200000,
"message": "成功",
"data": [
{
"id": 1,
"userName": "tiange",
"password": "123456",
"phone": "18257160375",
"gender": 0,
"status": 0,
"createTime": "2024-05-17T20:24:40.000+00:00"
}
]
}
到这里我们的项目就成功把mybatis-plus集成进来。
swagger
作为前后端分离项目,在团队开发中,一个好的 API 文档不但可以减少大量的沟通成本,还可以帮助一位新人快速上手业务。传统的做法是由开发人员创建一份 RESTful API文档来记录所有的接口细节,并在程序员之间代代相传。这种做法存在以下几个问题:
1)API 接口众多,细节复杂,需要考虑不同的HTTP请求类型、HTTP头部信息、HTTP请求内容等,想要高质量的完成这份文档需要耗费大量的精力;
2)难以维护。随着需求的变更和项目的优化、推进,接口的细节在不断地演变,接口描述文档也需要同步修订,可是文档和代码处于两个不同的媒介,除非有严格的管理机制,否则很容易出现文档、接口不一致的情况;
Swagger2 的出现就是为了从根本上解决上述问题。它作为一个规范和完整的框架,可以用于生成、描述、调用和可视化 RESTful 风格的 Web 服务:
- 接口文档在线自动生成,文档随接口变动实时更新,节省维护成本;
- 支持在线接口测试,不依赖第三方工具;
Swagger2 是一个规范和完整的框架,用于生成、描述、调用和可视化Restful风格的web服务,现在我们使用spring boot 整合它。作用:
- 接口的文档在线自动生成;
- 功能测试;
常用注解
注解描述@Api将类标记为 Swagger 资源。@ApiImplicitParam表示 API 操作中的单个参数。@ApiImplicitParams允许多个 ApiImplicitParam 对象列表的包装器。@ApiModel提供有关 Swagger 模型的其他信息。@ApiModelProperty添加和操作模型属性的数据。@ApiOperation描述针对特定路径的操作或通常是 HTTP 方法。@ApiParam为操作参数添加额外的元数据。@ApiResponse描述操作的可能响应。@ApiResponses允许多个 ApiResponse 对象列表的包装器。@Authorization声明要在资源或操作上使用的授权方案。@AuthorizationScope描述 OAuth2 授权范围。
swagger配置
@Configuration //加入到容器里面
@EnableSwagger2 //开启Swagger
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.tian.controller"))
.build();
}
private ApiInfo apiInfo(){
Contact contact = new Contact("web项目demo", "https://www.woaijava.cc/", "251965157@qq.com");
return new ApiInfo(
"web项目demo的API文档",
"练手所用",
"v1.0",
"https://www.woaijava.cc/",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
我们就可以在对应业务代码中标注上swagger:
@RestController
@RequestMapping("/user/info")
@Api(value = "用户信息接口",tags = "用户信息")
public class UserInfoController {
@Resource
private UserInfoService userInfoService;
@GetMapping("/{id}")
@ApiOperation(value = "根据id查询用户信息", notes = "根据id查询用户信息"
,produces = "application/json",consumes = "application/json")
@ApiImplicitParams({
@ApiImplicitParam(name="id",value="用户id",required = true,dataType = "Integer")
})
public Result findById(@PathVariable("id") Integer id) {
return Result.success(userInfoService.getById(id));
}
@GetMapping("/condition")
@ApiOperation(value = "根据条件查询用户信息")
public Result findByCondition(@Validated UserInfoReqDto userInfoReqDto) {
return userInfoService.findByCondition(userInfoReqDto);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value="用户信息查询条件")
public class UserInfoReqDto {
@NotBlank(message = "姓名不能为空")
@ApiModelProperty(value="姓名")
private String userName;
@NotBlank(message = "密码不能为空")
@ApiModelProperty(value="密码")
private String password;
}
效果
启动项目,访问:
http://localhost:8089/swagger-ui.html
也到这里,我们就基本形成了一个完整的demo级后端项目。
- 上一篇:十年之重修MyBatis原理
- 下一篇:spring常用注解
相关推荐
- 使用Python编写Ping监测程序(python 测验)
-
Ping是一种常用的网络诊断工具,它可以测试两台计算机之间的连通性;如果您需要监测某个IP地址的连通情况,可以使用Python编写一个Ping监测程序;本文将介绍如何使用Python编写Ping监测程...
- 批量ping!有了这个小工具,python再也香不了一点
-
号主:老杨丨11年资深网络工程师,更多网工提升干货,请关注公众号:网络工程师俱乐部下午好,我的网工朋友。在咱们网工的日常工作中,经常需要检测多个IP地址的连通性。不知道你是否也有这样的经历:对着电脑屏...
- python之ping主机(python获取ping结果)
-
#coding=utf-8frompythonpingimportpingforiinrange(100,255):ip='192.168.1.'+...
- 网站安全提速秘籍!Nginx配置HTTPS+反向代理实战指南
-
太好了,你直接问到重点场景了:Nginx+HTTPS+反向代理,这个组合是现代Web架构中最常见的一种部署方式。咱们就从理论原理→实操配置→常见问题排查→高级玩法一层层剖开说,...
- Vue开发中使用iframe(vue 使用iframe)
-
内容:iframe全屏显示...
- Vue3项目实践-第五篇(改造登录页-Axios模拟请求数据)
-
本文将介绍以下内容:项目中的public目录和访问静态资源文件的方法使用json文件代替http模拟请求使用Axios直接访问json文件改造登录页,配合Axios进行登录请求,并...
- Vue基础四——Vue-router配置子路由
-
我们上节课初步了解Vue-router的初步知识,也学会了基本的跳转,那我们这节课学习一下子菜单的路由方式,也叫子路由。子路由的情况一般用在一个页面有他的基础模版,然后它下面的页面都隶属于这个模版,只...
- Vue3.0权限管理实现流程【实践】(vue权限管理系统教程)
-
作者:lxcan转发链接:https://segmentfault.com/a/1190000022431839一、整体思路...
- swiper在vue中正确的使用方法(vue中如何使用swiper)
-
swiper是网页中非常强大的一款轮播插件,说是轮播插件都不恰当,因为它能做的事情太多了,swiper在vue下也是能用的,需要依赖专门的vue-swiper插件,因为vue是没有操作dom的逻辑的,...
- Vue怎么实现权限管理?控制到按钮级别的权限怎么做?
-
在Vue项目中实现权限管理,尤其是控制到按钮级别的权限控制,通常包括以下几个方面:一、权限管理的层级划分...
- 【Vue3】保姆级毫无废话的进阶到实战教程 - 01
-
作为一个React、Vue双修选手,在Vue3逐渐稳定下来之后,是时候摸摸Vue3了。Vue3的变化不可谓不大,所以,本系列主要通过对Vue3中的一些BigChanges做...
- Vue3开发极简入门(13):编程式导航路由
-
前面几节文章,写的都是配置路由。但是在实际项目中,下面这种路由导航的写法才是最常用的:比如登录页面,服务端校验成功后,跳转至系统功能页面;通过浏览器输入URL直接进入系统功能页面后,读取本地存储的To...
- vue路由同页面重定向(vue路由重定向到外部url)
-
在Vue中,可以使用路由的重定向功能来实现同页面的重定向。首先,在路由配置文件(通常是`router/index.js`)中,定义一个新的路由,用于重定向到同一个页面。例如,我们可以定义一个名为`Re...
- 那个 Vue 的路由,路由是干什么用的?
-
在Vue里,路由就像“页面导航的指挥官”,专门负责管理页面(组件)的切换和显示逻辑。简单来说,它能让单页应用(SPA)像多页应用一样实现“不同URL对应不同页面”的效果,但整个过程不会刷新网页。一、路...
- Vue3项目投屏功能开发!(vue投票功能)
-
最近接了个大屏项目,产品想在不同的显示器上展示大屏项目不同的页面,做出来的效果图大概长这样...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)