API(Application Programming Interface),顾名思义:是一组编程接口规范,客户端与服务端通过请求响应进行数据通信。REST(Representational State Transfer)表述性状态传递,决定了接口的形式与规则。RESTful是基于http方法的API设计风格,而不是一种新的技术.
对接口开发提供了一种可以广泛适用的规范,为前端后端交互减少了接口交流的口舌成本,是约定大于配置的体现。通过下面的设计,大家来理解一下这三句话.
当然也不是所有的接口,都能用REST的形式来表述。在实际工作中,灵活运用,我们用RESTful风格的目的是为大家提供统一标准,避免不必要的沟通成本的浪费,形成一种通用的风格。就好比大家都知道:伸出大拇指表示“你很棒“的意思,绝大部分人都明白,因为你了解了这种风格习惯。但是不排除有些地区伸出大拇指表示其他意思,就不适合使用!
REST 通过 URI 暴露资源时,会强调不要在 URI 中出现动词。比如:
实际上,这四个动词实际上就对应着增删改查四个操作,这就利用了HTTP动词来表示对资源的操作。
通过HTTP状态码体现动作的结果,不要自定义
200 OK 400 Bad Request 500 Internal Server Error
在 APP 与 API 的交互当中,其结果逃不出这三种状态:
这三种状态与上面的状态码是一一对应的。如果你觉得这三种状态,分类处理结果太宽泛,http-status code还有很多。建议还是要遵循KISS(Keep It Stupid and Simple)原则,上面的三种状态码完全可以覆盖99%以上的场景。这三个状态码大家都记得住,而且非常常用,多了就不一定了。
改变数据的事交给POST、PUT、DELETE
/dogs 而不是 /dog
GET /cars/711/drivers/ 返回 使用过编号711汽车的所有司机
GET /cars/711/drivers/4 返回 使用过编号711汽车的4号司机
HATEOAS
:Hypermedia as the Engine of Application State 超媒体作为应用状态的引擎。
RESTful API最好做到HATEOAS,即返回结果中提供链接,连向其他API方法,使得用户不查文档,也知道下一步应该做什么
。比如,当用户向api.example.com的根目录发出请求,会得到这样一个文档。
{"link": {
"rel": "collection https://www.example.com/zoos",
"href": "https://api.example.com/zoos",
"title": "List of zoos",
"type": "application/vnd.yourformat+json"
}}
上面代码表示,文档中有一个link属性,用户读取这个属性就知道下一步该调用什么API或者可以调用什么API了。
强制性增加API版本声明,不要发布无版本的API。如:/api/v1/blog
面向扩展开放,面向修改关闭:也就是说一个版本的接口开发完成测试上线之后,我们一般不会对接口进行修改,如果有新的需求就开发新的接口进行功能扩展。这样做的目的是:当你的新接口上线后,不会影响使用老接口的用户。如果新接口目的是替换老接口,也不要在v1版本原接口上修改,而是开发v2版本接口,并声明v1接口废弃!
//注意并不要求@RequestBody与@ResponseBody成对使用。
public @ResponseBody AjaxResponse saveArticle(@RequestBody ArticleVO article)
如上代码所示:
在使用@ResponseBody注解之后程序不会再走视图解析器,也就不再做html视图渲染,而是直接将对象以数据的形式(默认JSON)返回给请求发送者。那么我们有一个问题:如果我们想接收或XML数据该怎么办?我们想响应excel的数据格式该怎么办?我们后文来回答这个问题。
@RequestMapping注解是所有常用注解中,最有看点的一个注解,用于标注HTTP服务端点。它的很多属性对于丰富我们的应用开发方式方法,都有很重要的作用。如:
@RequestMapping(value = "/article", method = POST)
@PostMapping(value = "/article")
上面代码中两种写法起到的是一样的效果,也就是PostMapping等同于@RequestMapping的method等于POST。同理:@GetMapping、@PutMapping、@DeleteMapping也都是简写的方式。
@Controller注解是开发中最常使用的注解,它的作用有两层含义:
@RestController相当于 @Controller和@ResponseBody结合。它有两层含义:
PathVariable用于URI上的{参数},如下方法用于删除一篇文章,其中id为文章id。如:我们的请求URL为“/article/1”,那么将匹配DeleteMapping并且PathVariable接收参数id=1。而RequestParam用于接收普通表单方式或者ajax模拟表单提交的参数数据。
@DeleteMapping("/article/{id}")
public @ResponseBody AjaxResponse deleteArticle(@PathVariable Long id) {
@PostMapping("/article")
public @ResponseBody AjaxResponse deleteArticle(@RequestParam Long id) {
有一些朋友可能还无法理解RequestBody注解存在的真正意义,表单数据提交用RequestParam就好了,为什么还要搞出来一个RequestBody注解呢?RequestBody注解的真正意义在于能够使用对象或者嵌套对象接收前端数据
仔细看上面的代码,是一个self对象里面包含了一个friend对象。这种数据结构使用RequestParam就无法接收了,RequestParam只能接收平面的、一对一的参数。像上文中这种数据结构的参数,就需要我们在java服务端定义两个类,一个类是self,一个类是friend.
@NoArgsConstructor
@Data
public class Self
{
@JsonProperty("name")
private String name;
@JsonProperty("age")
private Integer age;
@JsonProperty("friend")
private FriendDTO friend;
@NoArgsConstructor
@Data
public static class FriendDTO {
@JsonProperty("name")
private String name;
}
}
@RestController
public class TestController
{
@GetMapping("/test")
public Object test(@RequestBody Self self )
{
System.out.println(self);
return self;
}
}
大家现在使用JSON都比较普遍了,其方便易用、表达能力强,是绝大部分数据接口式应用的首选。那么如何响应其他的类型的数据?其中的判别原理又是什么?下面就来给大家介绍一下:
当我们在Spring Boot应用中集成了jackson的类库之后,如下的一些HttpMessageConverter将会被加载。
实现类 | 功能说明 |
---|---|
StringHttpMessageConverter | 将请求信息转为字符串 |
FormHttpMessageConverter | 将表单数据读取到MultiValueMap中 |
XmlAwareFormHttpMessageConverter | 扩展与FormHttpMessageConverter,如果部分表单属性是XML数据,可用该转换器进行读取 |
ResourceHttpMessageConverter | 读写org.springframework.core.io.Resource对象 |
BufferedImageHttpMessageConverter | 读写BufferedImage对象 |
ByteArrayHttpMessageConverter | 读写二进制数据 |
SourceHttpMessageConverter | 读写java.xml.transform.Source类型的对象 |
MarshallingHttpMessageConverter | 通过Spring的org.springframework,xml.Marshaller和Unmarshaller读写XML消息 |
Jaxb2RootElementHttpMessageConverter | 通过JAXB2读写XML消息,将请求消息转换为标注的XmlRootElement和XmlType连接的类中 |
MappingJacksonHttpMessageConverter | 利用Jackson开源包的ObjectMapper读写JSON数据 |
RssChannelHttpMessageConverter | 读写RSS种子消息 |
AtomFeedHttpMessageConverter | 和RssChannelHttpMessageConverter一样能够读写RSS种子消息 |
根据HTTP协议的Accept和Content-Type属性,以及参数数据类型来判别使用哪一种HttpMessageConverter。当使用RequestBody或ResponseBody时,再结合前端发送的Accept数据类型,会自动判定优先使用MappingJacksonHttpMessageConverter作为数据转换器。但是,不仅JSON可以表达对象数据类型,XML也可以。如果我们希望使用XML格式该怎么告知Spring呢,那就要使用到produces属性了。
@GetMapping(value ="/demo",produces = MediaType.APPLICATION_XML_VALUE)
这里我们明确的告知了返回的数据类型是xml,就会使用Jaxb2RootElementHttpMessageConverter作为默认的数据转换器。当然实现XML数据响应比JSON还会更复杂一些,还需要结合@XmlRootElement、@XmlElement等注解实体类来使用。同理consumes属性你是不是也会用了呢。
其实绝大多数的数据格式都不需要我们自定义HttpMessageConverter,都有第三方类库可以帮助我们实现(包括下文代码中的Excel格式)。但有的时候,有些数据的输出格式并没有类似于Jackson这种类库帮助我们处理,需要我们自定义数据格式。该怎么做?
下面我们就以Excel数据格式为例,写一个自定义的HTTP类型转换器。实现的效果就是,当我们返回AjaxResponse这种数据类型的话,就自动将AjaxResponse转成Excel数据响应给客户端。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
@Service
public class ResponseToXlsConverter extends AbstractHttpMessageConverter<AjaxResponse> {
//数据返回给前端的时候,会携带该响应头
private static final MediaType EXCEL_TYPE = MediaType.valueOf("application/vnd.ms-excel");
ResponseToXlsConverter() {
super(EXCEL_TYPE);
}
//处理前端传过来的inputstream,封装为ajaxreponse对象
@Override
protected AjaxResponse readInternal(final Class<? extends AjaxResponse> clazz,
final HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
return null;
}
//针对AjaxResponse类型返回值,使用下面的writeInternal方法进行消息类型转换
@Override
protected boolean supports(final Class<?> clazz) {
return (AjaxResponse.class == clazz);
}
//将数据从ajaxResponse中取出,以outputstream流的形式返回给前端
@Override
protected void writeInternal(final AjaxResponse ajaxResponse, final HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
final Workbook workbook = new HSSFWorkbook();
final Sheet sheet = workbook.createSheet();
final Row row = sheet.createRow(0);
row.createCell(0).setCellValue(ajaxResponse.getMessage());
row.createCell(1).setCellValue(ajaxResponse.getData().toString());
workbook.write(outputMessage.getBody());
}
}
@NoArgsConstructor
@Data
@Builder
public class Self
{
@JsonProperty("name")
private String name;
@JsonProperty("age")
private Integer age;
@JsonProperty("friend")
private FriendDTO friend;
@NoArgsConstructor
@Data
@Builder
public static class FriendDTO {
@JsonProperty("name")
private String name;
@JsonProperty("createTime")
private LocalDateTime createTime;
}
}
我们实现一个简单的RESTful接口
下面代码中并未真正的进行数据库操作,为简化操作,只是进行模拟。
@Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleController {
//获取self,使用GET方法,根据id查询
//@RequestMapping(value = "/selfs/{id}",method = RequestMethod.GET)
@GetMapping("/selfs/{id}")
public AjaxResponse getArticle(@PathVariable("id") Long id){
Self.FriendDTO friendDTO = Self.FriendDTO.builder().name("小朋友").createTime(LocalDateTime.now()).build();
//使用lombok提供的builder构建对象
Self self = Self.builder().age(18).name("大忽悠")
.friend(friendDTO).build();
log.info("self:" + self);
return AjaxResponse.success(self);
}
//增加selfs ,使用POST方法(RequestBody方式接收参数)
// @RequestMapping(value = "/selfs",method = RequestMethod.POST)
// @PostMapping("/selfs")
// public AjaxResponse saveArticle(@RequestBody Self self,
// @RequestHeader String aaa){
//
// //因为使用了lombok的Slf4j注解,这里可以直接使用log变量打印日志
// log.info("saveArticle:" + self);
// log.info("请求头:" + aaa);
// return AjaxResponse.success();
// }
//增加self ,使用POST方法(RequestParam方式接收参数)
@PostMapping("/selfs")
public AjaxResponse saveArticle(@RequestParam String name,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam LocalDateTime createTime){
log.info("saveArticle:" + createTime);
return AjaxResponse.success();
}
//更新self,使用PUT方法,以id为主键进行更新
//@RequestMapping(value = "/selfs",method = RequestMethod.PUT)
@PutMapping("/selfs")
public AjaxResponse updateArticle(@RequestParam Integer id){
if(id == null){
//article.name是必传参数,通常根据id去修改
//TODO 抛出一个自定义的异常
}
log.info("updateSlef:" + id);
return AjaxResponse.success();
}
//删除self,使用DELETE方法,参数是id
//@RequestMapping(value = "/selfs/{id}",method = RequestMethod.DELETE)
@DeleteMapping("/selfs/{id}")
public AjaxResponse deleteArticle(@PathVariable("id") Long id){
log.info("deleteSelf:" + id);
return AjaxResponse.success();
}
}
因为使用了lombok的@Slf4j注解(类的定义处),就可以直接使用log变量打印日志。不需要写下面的这行代码。
private static final Logger log = LoggerFactory.getLogger(HelloController.class);
下面这个类是用于统一数据响应接口标准的。它的作用是:统一所有开发人员响应前端请求的返回结果格式,减少前后端开发人员沟通成本,是一种RESTful接口标准化的开发约定。下面代码只对请求成功的情况进行封装,在后续的异常处理相关的章节会做更加详细的说明。
@Data
public class AjaxResponse {
private boolean isok; //请求是否处理成功
private int code; //请求响应状态码(200、400、500)
private String message; //请求结果描述信息
private Object data; //请求结果数据(通常用于查询操作)
private AjaxResponse(){}
//请求成功的响应,不带查询数据(用于删除、修改、新增接口)
public static AjaxResponse success(){
AjaxResponse ajaxResponse = new AjaxResponse();
ajaxResponse.setIsok(true);
ajaxResponse.setCode(200);
ajaxResponse.setMessage("请求响应成功!");
return ajaxResponse;
}
//请求成功的响应,带有查询数据(用于数据查询接口)
public static AjaxResponse success(Object obj){
AjaxResponse ajaxResponse = new AjaxResponse();
ajaxResponse.setIsok(true);
ajaxResponse.setCode(200);
ajaxResponse.setMessage("请求响应成功!");
ajaxResponse.setData(obj);
return ajaxResponse;
}
//请求成功的响应,带有查询数据(用于数据查询接口)
public static AjaxResponse success(Object obj,String message){
AjaxResponse ajaxResponse = new AjaxResponse();
ajaxResponse.setIsok(true);
ajaxResponse.setCode(200);
ajaxResponse.setMessage(message);
ajaxResponse.setData(obj);
return ajaxResponse;
}
}
获取操作:
//获取self,使用GET方法,根据id查询
//@RequestMapping(value = "/selfs/{id}",method = RequestMethod.GET)
@GetMapping("/selfs/{id}")
public AjaxResponse getArticle(@PathVariable("id") Long id){
Self.FriendDTO friendDTO = Self.FriendDTO.builder().name("小朋友").createTime(LocalDateTime.now()).build();
//使用lombok提供的builder构建对象
Self self = Self.builder().age(18).name("大忽悠")
.friend(friendDTO).build();
log.info("self:" + self);
return AjaxResponse.success(self);
}
新增操作:
//增加selfs ,使用POST方法(RequestBody方式接收参数)
//@RequestMapping(value = "/selfs",method = RequestMethod.POST)
@PostMapping("/selfs")
public AjaxResponse saveArticle(@RequestBody Self self,
@RequestHeader String aaa){
//因为使用了lombok的Slf4j注解,这里可以直接使用log变量打印日志
log.info("saveArticle:" + self);
log.info("请求头:" + aaa);
return AjaxResponse.success();
}
以下两种方式针对的是日期类型为Date或者LocalDateTime的解决方案
方式一: 主配置文件指出转换形式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
@RequestBody对于使用了该注解接收的json字符串的请求
方式二: @DateTimeForma注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
//该注解可以加在方法上,字段上,参数上,注解上
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface DateTimeFormat {
....
}
一般使用该注解会用上图右边的写法,或者下面的写法:
//增加self ,使用POST方法(RequestParam方式接收参数)
@PostMapping("/selfs")
public AjaxResponse saveArticle(@RequestParam String name,
@RequestParam String age,
@RequestParam String fname,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam Date createTime){
log.info("saveArticle:" + createTime);
return AjaxResponse.success();
}