前言:什么是REST?

一种架构设计风格,提供了设计原则和约束条件,而不是架构。而满足这些约束条件和原则的应用程序或设计就是 RESTful架构或服务。

segmentfault

我理解“就是有了规范/规则/限制/风格”,就能享受到一些”好处“。

Overview(概况)

  • REST: REpresentational State Transfer
  • Resource-based(基于资源)
  • Representations(表述)
  • Six constraints(6点限制)
  • Uniform Interface(统一接口)
  • Stateless(无状态性)
  • Cacheable(可缓存)
  • Client-Server(客户端-服务端结构)
  • Layered System(分层系统)
  • Code on Demand (optional)(按需编码)

Resource Based(基于资源)

  • Things vs. actions
  • Nouns vs. verbs
  • Versus SOAP-RPC(注:SOAP和RPC是另外两种主流的Web服务实现方案)
  • Identified by URIs
    • Multiple URIs may refer to same resource
  • Separate from their representation(s)

Representations(表述)

  • How resources get manipulated(对资源的描述、如何操作资源的)
  • Part of the resource state
    • Transferred between client and server
  • Typically JSON or XML
  • Example:
    • Resource: person(Todd)
    • Service: contact information (GET)
    • Representation:
      • name, address, phone number …
      • JSON or XML format

Uniform Interface(统一接口)

  • Defines the interface between client and server
  • Simplifies and decouples the architecture
  • Fundamental to RESTful design
  • For us this means:
    • HTTP verbs(GET, PUT, POST, DELETE)
    • URIs(resource name)
    • HTTP response(status, body)

Stateless(无状态性)

  • Server contains no client state(服务端不包含任何客户端的状态)
  • Each request contains enough context to process the message(每一个请求都含有足够的内容来进行处理)
    • Self-descriptive messages(自明信息)
  • Any session state is held on the client(任何的状态都由客户端来保存)

Client-Server(客户端-服务端结构)

  • Assume a disconnected system(假设两端不相连)
  • Separation of concerns(关注点分离)
  • Uniform interface is the link between the two(由统一接口将两者链接)

Cacheable(可缓存)

  • Server responses(representations)are cacheable(服务端的响应或者表述是可缓存的)
    • 不准确地
    • 准确地
    • 可谈判地

Layered System(分层系统)

  • Client can’t assume direct connection to server
  • Software or hardware intermediaries between client and server
  • Improves scalability

Code on Demand(按需编码)

  • Server can temporarily extend client(服务端可以临时扩展客户端)
  • Transfer logic to client(将逻辑传给客户端)
  • Client executes logic(客户端来执行逻辑)
  • For example: Java applets; JavaScript
  • The only optional constraiant(唯一可选的)

Summary

  • Violating any constraint other than Code On Demand means service is not strictly RESTful(违反任何除“按需编码”之外的限制,都意味着服务不是严格地RESTful。注:目前REST-like也很流行)
    • Example: Three-legged OAUTH2
  • Compliance with REST constraints allows(好处):
    • Scalability
    • Simplicity
    • Modifiability
    • Visibility
    • Portability
    • Reliability

参考资料: