api返回值的标准化的介绍(代码示例)

互联网 19-3-8

本篇文章给大家带来的内容是关于api返回值的标准化的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

api返回值的标准化

例如

{"status":200,"message":"操作成功","data":"{\"id\":1,\"name\":\"张三\"}"}

封装返回对象

对象被封装在base.util.ResponseUtils类型下,返回值是标准的ResponseEntity对象,返回体进行了二次封装,主要有status,messsage和data组成,返回方法有ok和okMessage,如果真是返回消息,不需要对象,可以选择使用okMessage,反之使用ok方法。

封装的返回对象:

  @Builder   @Getter   @NoArgsConstructor   @AllArgsConstructor   static class ResponseBody {      private int status;     private String message;     private Object data;   }

httpError和我们封装的httpError

  • 使用标准http响应状态码
  @GetMapping(GET_HTTP_ERROR)   ResponseEntity<?> getHttpError() throws IOException {     return ResponseEntity.badRequest().build();   }   @Test   public void getHttpError() throws Exception {       mockMvc           .perform(               get(LindDemo.GET_HTTP_ERROR)                   .accept(MediaType.APPLICATION_JSON_UTF8))           .andExpect(status().is(400));       }

响应的结果

MockHttpServletResponse:            Status = 400     Error message = null           Headers = {}      Content type = null              Body =      Forwarded URL = null    Redirected URL = null           Cookies = []
  • 使用我们封装的status状态码
  @GetMapping(GET_ERROR)   ResponseEntity<?> getError() throws IOException {     return ResponseUtils.badRequest("传入的参数非法!");   }      @Test     public void getError() throws Exception {       mockMvc           .perform(               get(LindDemo.GET_ERROR)                   .accept(MediaType.APPLICATION_JSON_UTF8))           .andExpect(status().isOk());        }

响应的结果

MockHttpServletResponse:            Status = 200     Error message = null           Headers = {Content-Type=[application/json;charset=UTF-8]}      Content type = application/json;charset=UTF-8              Body = {"status":400,"message":"传入的参数非法!","data":{}}     Forwarded URL = null    Redirected URL = null           Cookies = []

总结

事实上,两种响应体都没有问题,关键在于开发之间的规则要确定,不要在项目里两者兼用!

以上就是api返回值的标准化的介绍(代码示例)的详细内容,更多内容请关注技术你好其它相关文章!

来源链接:
免责声明:
1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险
2.本文版权归属原作所有,仅代表作者本人观点,不代表本站的观点或立场
标签: api
上一篇:php获取远程图片并下载保存到本地的方法分析 下一篇:java读写操作的代码示例

相关资讯