REST 相关

REST 相关


REST:Representational State Transfer,表现层状态转化(出现在阮一峰的博客 理解RESTful架构 中,但是,很明显,Representational 是形容词。全称是 Resource Representational State Transfer。

  • Resource:资源,即数据(前面说过网络的核心)。比如 newsfeed,friends等;
  • Representational:某种表现形式,比如用JSON,XML,JPEG等;
  • State Transfer:状态变化。通过HTTP动词实现。

出处

Roy Fielding 的毕业论文。
全文:Architectural Styles and the Design of Network-based Software Architectures
REST 章节:Fielding Dissertation: CHAPTER 5: Representational State Transfer (REST)

为什么要 RESTful

移动互联网,各种client层出不穷,前后端分离可以为只提供一套后端服务供不同 client 使用。

?? 不明白的

resource REpresentational State Transfer 有两种理解:

  1. 通过 HTTP 方法(POST、GET等)操作表征层(HTML、JPEG、Json、XML等)。
  2. 第一种理解只是标准的 HTTP 规范,REST 是要在 response 中带有 transfer 当前的 state 。
    state transfer,状态转移。representational,形容词,表述性的、代表的、具象的。HTTP 协议是无状态的(stateless),state transfer 可以把这个状态转移给客户端“保留下来”,Roy Fielding 认为 representational 的 state transfer 好。
    参考季文昊的回答:

HTTP 协议是无状态的——如果第一次请求查询了第一页的资源,接着想查询第二页的话需要告诉服务器查询第二页而不是说给我下一页。REST 是要在 response 中,把state传递给客户端。
查询第一页时,response 中需要包含当前 :

  1. 当前接口地址(,及其含义)
  2. 下一页接口地址(,及其含义)
  3. 用到当前接口的网页地址

版本

有两种方式:

  1. 正宗的是在 request header 的 Accept 中指定版本。如

    Accept: application/vnd.spire-io.session+json;version=1.0

  2. 但是更常见的是在 URI 中写明。

缓存

  • response header 中得到的 ETag(或 Last-Modified),下次请求时在 reqeust header 中放入 If-None-Match(或 If-Modified-Since)中,如果资源没有修改过就会返回 304 Not Modified。
  • response header 主要中通过 Expries(指定绝对时间)和 Cache-Control 的 max-age(指定相对时间,形如 Cache-control: max-age=5)控制客户端的缓存行为。

ETag (entity tag) is an identifier, commonly a hash.

认证(Authorization)

"username:password" base64后,作为 request header 中的 Authorization 参数传给服务端,形如 Authorization: Basic bHJlaTp5ZWFocmlnaHQ=。这种形式必须要用 https, 否则很容易被截获。

OAuth2 is a common way of doing authorization for 3rd party applications using an API。

相关

HTTP: Hypertext Transfer Protocol
REST: resource REpresentational State Transfer

what when
HTTP v0.9 1991
HTTP v1.0 1996
HTTP v1.1 1997
REST 2000
HTTP v2.0 2015

In the case of non-hypermedia resources (e.g. images) the http headers will be the only way to add API metadata to the resource such as state transitions. I think it's generally a good idea to always include the transitions in the headers as it becomes possible to perform a transition without parsing the request body.

examples:

https://api.github.com/
https://dev.twitter.com/rest/public


  1. 关于安全:自己的接口就用https,加上一个key做一次hash放在最后即可。考虑到国情,HTTPS在无线网络里不稳定,可以使用Application Level的加密手段把整个HTTP的payload加密。有兴趣的朋友可以用手机连上电脑的共享Wi-Fi,然后用Charles监听微信的网络请求(发照片或者刷朋友圈)。
    如果是平台的API,可以用成熟但是复杂的OAuth2,新浪微博这篇:授权机制说明
posted @ 2015-10-13 14:25  shang1jk  阅读(170)  评论(0)    收藏  举报