尝试理解Roy Fielding dissertation

REST是一种架构,URI、HTTP、WWW都是在这个架构思想的指导下研发的。

Representational State Transfer这个词组非常晦涩难懂,直接翻译的话,“表现层状态转移”,根本不知道在说什么。

看了一遍论文有了大概理解。那就是一个系统有很多状态,状态之间可以发生转换(virtual “state-machine”),同时用户可以观察到这些状态在表现层的形态。

在我们最常见的网页浏览情景下,其实REST描述的就是用户在浏览器里点击超链接的过程。

当你进入一个网站的首页,这是初始状态,点击进入一个页面,这就进入了另一个状态。这些状态的背后,是客户端和服务器内部状态的转换,同时用户也能观察到这些状态的转换。

使用了客户端连接到服务器,这体现了REST的C/S;首次登录没有建立登录状态,服务器不认识你,登录完浏览器会存储cookie或token等身份信息,如果你丢掉了本地的身份信息(比如使用无痕模式)再来访问,服务器还是不认识你,这体现了REST的Stateless;网站有更新之后,可能出现浏览器刷新但实际没有再次请求,直接使用本地缓存的情况,这就是REST的Cache。

C/S、Stateless、Cache都是REST架构提出的constraint。constraints集合形成了架构风格。(dissertation 5.1.2-5.1.4)

RESTful指的是设计和实现符合REST这种架构。

REST架构风格还包括:统一的接口,分层的系统,Code-On-Demand(客户端按需下载代码增强系统能力,optional)

再次强调接口的重要性

Uniform interfaces

Perhaps one of the most fundamental aspects of RESTful systems is the uniform interface, a way to decouple and simplify application architecture so that each component can develop and change on its own. There are four, further constraints involved in uniform interfaces:

  • Requests must contain resource identifiers. As an example, a URI can be contained in a request to enable the resource to be identified. Note that, conceptually, resources are distinct from the results that are returned to a client. For example, no matter what the server’s own method of storing data is, the data sent in answer to a request could be sent as anything from XML to HTML or even JSON.
  • Representations can manipulate resources. Clients might hold a representation of a specific resource – and this could contain metadata. This information is sufficient for the client to be able to change the resource, or to delete the resource.
  • Messages are self-descriptive. Every message sent under a RESTful architecture will contain sufficient information for the recipient to be able to process the message – as an example, a message can use a media type to specify which parser should be used.
  • HATEOAS. Short for “hypermedia as the engine of the application state”, this principle is just like a human having access to the home page of a specific website. The client should then have the option to make use of links provided by the server so that it can automatically understand which activities and resources it will require.