RESTful architecture (Representational State Transfer resource performance layer state transitions)

1. What is REST

restful

REST name is Representational State Transfer, Chinese meaning expression (Editor's note: Characterization usually translated) State Transfer. It first appeared in 2000, Roy Fielding's doctoral dissertation, Roy Fielding is one of the principal authors of the HTTP specification. He mentioned in the paper: "The purpose of my writing this article, is to, in conformity with the principles of architecture, architecture design to understand and evaluate web-based application software, get a strong function, good performance, suitable for communication architecture .REST refers to a set of architectural constraints and principles. "If a framework and principles consistent with the constraints of REST, we call it RESTful architecture.

REST itself does not create new technologies, components or services, while hiding behind the idea is to use RESTful Web's existing features and capabilities, better use some guidelines and constraints existing Web standards. Although deeply influenced by the REST Web technology itself, but in theory the REST architectural style is not bound to HTTP, but currently only HTTP REST-related instances. So here we describe REST REST HTTP also achieved through.

2. understand RESTful

To understand RESTful architecture, Representational State Transfer need to understand what is the meaning of this phrase in the end, it's what every word some meaning.

Here we combine REST principles, discuss about the resources, resource definition, acquisition, representation, association, state transition perspectives, are some of the key concepts and explain.

  • Resources and URI
  • Uniform Resource Interface
  • Resource representations
  • Links to resources
  • Transfer status

2.1 Resources and URI

REST stands for Representational State Transfer, is that really mean what's the expression? Actually refers to the resource. Anything, as long as it is necessary to be referenced, it is a resource. Resources can be physical (eg phone number), it can be just an abstract concept (eg value). Here are some examples of resources:

  • A user's mobile phone number
  • A user's personal information
  • Up GPRS package subscription
  • Dependencies between the two products
  • A user can apply for a Package
  • The potential value of a cell phone number

To make a resource can be identified, it is necessary to have a unique identification, this unique identification is URI (Uniform Resource Identifier) ​​on the Web.

URI address can either be seen as resources, it can also be seen as the name of the resource. If some of the information is not used to represent URI, then it can not be regarded as a resource, it can only be regarded as some of the information resource only. URI design should follow the principle of addressable, self-descriptive, related to the intuition in the form of giving needs. Here at github site, for example, give some pretty good URI:

  • https://github.com/git
  • https://github.com/git/git
  • https://github.com/git/git/blob/master/block-sha1/sha1.h
  • https://github.com/git/git/commit/e3af72cdafab5993d18fae056f87e1d675913d08
  • https://github.com/git/git/pulls
  • https://github.com/git/git/pulls?state=closed
  • https://github.com/git/git/compare/master…next

Let's look at some tips on design URI:

  • Use _ or - to make better readability URI

URI on the Web who are cold or meaningless string of numbers, but now more and more sites use _ or - to separate some words, let URI looks more human. For example, more famous domestic Chinese open source community, which address the above information on the use of this style, such as http://www.oschina.net/news/38119/oschina-translate-reward-plan.

  • Use / to represent the resource hierarchy

For example, the above / git / git / commit / e3af72cdafab5993d18fae056f87e1d675913d08 he says that a multi-level resources, referring to a particular user's git git commit record project, but also for example / orders / 2012/10 can be used to represent October 2012 Order History.

  • Use? To filter resources

Many people just put? Simple as a parameter is passed, it is likely to cause URI is too complicated to understand. Can be? For filtering of resources, e.g. / git / git / pulls push request to represent all git item, and / pulls? State = closed git used to represent items push request has been closed, this URL usually corresponds to the results of a number of specific conditions or arithmetic operation result.

  • Or; it may be used to indicate the relationship at the same level of resources

Sometimes we need to represent the relationship when the same level of resources can be used, or; to divide. For example github day can be compared in a file feel free to submit differences between the two records, may be able to use the / git / git /block-sha1/sha1.h/compare/e3af72cdafab5993d18fae056f87e1d675913d08;bd63e61bdf38e872d5215c07b264dcc16e4febca as URI. Now, however, github is to use ... to do this thing, for example, / git / git / compare / master ... next.

2.2 Uniform Resource Interface

RESTful architecture should follow the principle of a unified interface, unified interface contains a predefined set of operations is limited, no matter what kind of resources, resources are accessed by using the same interface. Interface should use the standard HTTP methods such as GET, PUT and POST, and the semantics of these methods follow.

If you follow the semantics of HTTP methods to expose resources, the interface will have characteristics of security and power, etc., such as GET and HEAD requests are safe, no matter how many times the request, the server will not change state. The GET, HEAD, PUT and DELETE requests are idempotent, regardless of how many times a resource operation, the result is always the same, subsequent requests and will not have more impact than the first time.

Listed below are the typical use of GET, DELETE, PUT and POST:

GET

  • Safe and idempotent
  • Gets a
  • Gets a (cache) when changing
  • 200 (OK) - represents the response has been sent
  • 204 (No Content) - Available resources represent
  • 301 (Moved Permanently) - the resource URI has been updated
  • 303 (See Other) - Other (eg, load balancing)
  • 304 (not modified) - Resource not changed (cache)
  • 400 (bad request) - refers Bad Request (e.g., parameter error)
  • 404 (not found) - the resource does not exist
  • 406 (not acceptable) - the server does not support the required representation
  • 500 (internal server error) - generic error response
  • 503 (Service Unavailable) - the server is currently unable to handle the request

POST

  • Unsafe not idempotent
  • Examples of the use of server-side management (automatically generated) No. creating a resource
  • Create a child resource
  • Some updates Resources
  • If it has not been modified, but the updated resource (optimistic locking)
  • 200 (OK) - If the existing resource has been changed
  • 201 (created) - If a new resource is created
  • 202 (accepted) - processing request has been accepted but not yet completed (asynchronously)
  • 301 (Moved Permanently) - URI resource is updated
  • 303 (See Other) - Other (eg, load balancing)
  • 400 (bad request) - refers Bad Request
  • 404 (not found) - the resource does not exist
  • 406 (not acceptable) - the server does not support the required representation
  • 409 (conflict) - general conflict
  • 412 (Precondition Failed) - Precondition Failed (conflicts when performing such update condition)
  • 415 (unsupported media type) - received representation is not supported
  • 500 (internal server error) - generic error response
  • 503 (Service Unavailable) - currently unable to handle service requests

PUT

  • But unsafe idempotent
  • Creating a resource with the instance number of the client management
  • Update the resource by way of replacement
  • If not modified, the update resource (optimistic locking)
  • 200 (OK) - If there is a resource already been changed
  • 201 (created) - If a new resource is created
  • 301 (Moved Permanently) - the resource URI has changed
  • 303 (See Other) - Other (eg, load balancing)
  • 400 (bad request) - refers Bad Request
  • 404 (not found) - the resource does not exist
  • 406 (not acceptable) - the server does not support the required representation
  • 409 (conflict) - general conflict
  • 412 (Precondition Failed) - Precondition Failed (conflicts when performing such update condition)
  • 415 (unsupported media type) - received representation is not supported
  • 500 (internal server error) - generic error response
  • 503 (Service Unavailable) - currently unable to handle service requests

DELETE

  • But unsafe idempotent
  • Delete Resource
  • 200 (OK) - Resource has been deleted
  • 301 (Moved Permanently) - the resource URI has changed
  • 303 (See Other) - Other, such as load balancing
  • 400 (bad request) - refers Bad Request
  • 404 (not found) - the resource does not exist
  • 409 (conflict) - general conflict
  • 500 (internal server error) - generic error response
  • 503 (Service Unavailable) - the server is currently unable to handle the request

Let's look at some of the common problems in practice:

  • What is the difference when POST and PUT for creating resources?

POST and PUT difference in creating a resource that the names of resources created (URI) is determined by whether the client. Such as increasing the classification of a java for my blog, the resulting path is the category name / categories / java, then you can PUT method used. But many people directly to the POST, GET, PUT, DELETE directly correspond to the CRUD, for example, in a typical RESTful applications implemented in rails did.

I think that this is because the rails default ID generated using the server as URI's sake, but a lot of people is through the practice of REST rails, so it is easy for this misunderstanding.

  • The client may not support these HTTP methods, right?

Indeed this is the case, especially some of the more ancient browser-based client, can only support GET and POST methods.

In practice, the client and server may need to make some compromises. E.g. frame rails to support transactions to pass through the hidden parameter request method _method = DELETE, and the like MVC client frame transmission such Backbone allows transmission and disposed _method X-HTTP-Method-Override head to avoid this problem.

  • Does that mean a unified interface method can not be extended with special semantics?

Unified interface does not prevent you from extension methods, as long as the method of operation of the resource has a specific, identifiable semantics can be, and be able to maintain the unity of the entire interface.

WebDAV HTTP methods like it to be extended, increasing LOCK, UPLOCK other methods. And github API supports the use PATCH method to issue an update, such as:

PATCH /repos/:owner/:repo/issues/:number

However, it should be noted that, like HTTP PATCH this is not a standard method, the server needs to consider the question of whether the client can support.

  • Uniform Resource Interface What guidance for URI?

Uniform Resource interface requirements using standard HTTP methods to manipulate resources, it should only be URI represents the name of the resource, and should not include operational resources.

Colloquially, URI should not be used to describe the action. For example, here are some do not meet the requirements of the unified interface URI:

  • GET /getUser/1
  • POST /createUser
  • PUT /updateUser/1
  • DELETE /deleteUser/1

If the GET request to increase the counter, which is a violation of safety?

Security does not mean that the request does not cause side effects such as the development platform for many API, it does limit the request flow. Like github, it will limit the request without authentication requests per hour only 60 times.

But the client is not in pursuit of these side effects while issuing a GET or HEAD request, the server side effects are "up front" of.

In addition, the server at design time, should not let the side effects too, because the client believes these requests are no side effects.

  • Direct Cache advisable to ignore it?

Even if you press the original intent of each verb to use them, you can still easily disable caching mechanism. The easiest way is to increase your response in such a HTTP header: Cache-control: no-cache. But, at the same time you also lost the support of efficient caching and revalidation (using Etag mechanisms).

For the client, when a REST-style service program to achieve the client should also make full use of existing caching mechanism, so as not to re-acquire each time representation.

  • Processing the response code necessary?

HTTP response code can be used to deal with different situations, the proper use of these status codes mean that the client and server can communicate with in a rich semantic level on.

For example, 201 ( "Created") response code indicates that you have created a new resource, its URI in the Location response packet in advance.

If you do not use HTTP status codes rich application semantics, then you will miss improve reusability, enhanced interoperability and loose coupling of promotion opportunities.

If these so-called RESTful application must give an error message in response to the entity, then SOAP is one such, and it can meet.

Representation 2.3 resources

As mentioned above, the client can access resources via HTTP method, is not it? No, rather, the client gets only a representation of the resource only. Resources outside the specific presentation can have multiple expressions (or as the expression, representation) form, also expressed resources between the client and server transfer, rather than the resource itself. Such as text resources can be used html, xml, json format, PNG or JPG images can be used to show up.

The representation of the resource data and metadata including description data, e.g., HTTP header "Content-Type" is such a metadata attribute.

So how do you know which form of client-side presentation services it provides?

The answer is by HTTP content negotiation, the client can request a particular presentation format by Accept header, the server through Content-Type tells the form of representation of client resources.

To github, for example, expressed in the form of json format of the request of an organization's resources:

291731048886033

 

 If github can also support output format xml format, then the result is this:

291731045756062

 

 Let's look at some common design practice:

Bring the version number in the URI inside

Some API URI in the inside band version number, for example:

  • http://api.example.com/1.0/foo
  • http://api.example.com/1.2/foo
  • http://api.example.com/2.0/foo

If we put the version number understood as different forms of representation of the resource, then you should just use a URL, and distinguished by the Accept header, or to github, for example, the full format is its Accept: application / vnd.github [. version] .param [+ json]

For v3 version, it is Accept: application / vnd.github.v3. For the above example, the same token can be used using the following header:

  • Accept: vnd.example-com.foo+json; version=1.0
  • Accept: vnd.example-com.foo+json; version=1.2
  • Accept: vnd.example-com.foo+json; version=2.0

Use URI suffix that is output format

像rails框架,就支持使用/users.xml或/users.json来区分不同的格式。 这样的方式对于客户端来说,无疑是更为直观,但混淆了资源的名称和资源的表述形式。 我个人认为,还是应该优先使用内容协商来区分表述格式。

如何处理不支持的表述格式

当服务器不支持所请求的表述格式,那么应该怎么办?若服务器不支持,它应该返回一个HTTP 406响应,表示拒绝处理该请求。下面以github为例,展示了一个请求XML表述资源的结果:

291732082474844

  

2. 4 资源的链接

我们知道REST是使用标准的HTTP方法来操作资源的,但仅仅因此就理解成带CURD的Web数据库架构就太过于简单了。

这种反模式忽略了一个核心概念:"超媒体即应用状态引擎(hypermedia as the engine of application state)"。 超媒体是什么?

当你浏览Web网页时,从一个连接跳到一个页面,再从另一个连接跳到另外一个页面,就是利用了超媒体的概念:把一个个把资源链接起来.

要达到这个目的,就要求在表述格式里边加入链接来引导客户端。在《RESTful Web Services》一书中,作者把这种具有链接的特性成为连通性。下面我们具体来看一些例子。

下面展示的是github获取某个组织下的项目列表的请求,可以看到在响应头里边增加Link头告诉客户端怎么访问下一页和最后一页的记录。 而在响应体里边,用url来链接项目所有者和项目地址。

291731042784620

  又例如下面这个例子,创建订单后通过链接引导客户端如何去付款。

291731052313462

上面的例子展示了如何使用超媒体来增强资源的连通性。很多人在设计RESTful架构时,使用很多时间来寻找漂亮的URI,而忽略了超媒体。所以,应该多花一些时间来给资源的表述提供链接,而不是专注于"资源的CRUD"。

2. 5 状态的转移

有了上面的铺垫,再讨论REST里边的状态转移就会很容易理解了。

不过,我们先来讨论一下REST原则中的无状态通信原则。初看一下,好像自相矛盾了,既然无状态,何来状态转移一说?

其实,这里说的无状态通信原则,并不是说客户端应用不能有状态,而是指服务端不应该保存客户端状态。

2. 5.1 应用状态与资源状态

实际上,状态应该区分应用状态和资源状态,客户端负责维护应用状态,而服务端维护资源状态。

客户端与服务端的交互必须是无状态的,并在每一次请求中包含处理该请求所需的一切信息。

服务端不需要在请求间保留应用状态,只有在接受到实际请求的时候,服务端才会关注应用状态。

这种无状态通信原则,使得服务端和中介能够理解独立的请求和响应。

在多次请求中,同一客户端也不再需要依赖于同一服务器,方便实现高可扩展和高可用性的服务端。

但有时候我们会做出违反无状态通信原则的设计,例如利用Cookie跟踪某个服务端会话状态,常见的像J2EE里边的JSESSIONID。

这意味着,浏览器随各次请求发出去的Cookie是被用于构建会话状态的。

当然,如果Cookie保存的是一些服务器不依赖于会话状态即可验证的信息(比如认证令牌),这样的Cookie也是符合REST原则的。

2. 5.2 应用状态的转移

状态转移到这里已经很好理解了, "会话"状态不是作为资源状态保存在服务端的,而是被客户端作为应用状态进行跟踪的。客户端应用状态在服务端提供的超媒体的指引下发生变迁。服务端通过超媒体告诉客户端当前状态有哪些后续状态可以进入。

这些类似"下一页"之类的链接起的就是这种推进状态的作用——指引你如何从当前状态进入下一个可能的状态。

3. 总结

Now Guangdong XXX version, XXX and other projects in both the use of traditional RPC, Web service SOAP methods, while moving back south XXXX base project, although the use of JSON format to interact, but still belong to the RPC style. From the definition of resources, acquisition, representation, association, state transition perspectives, trying to quickly understand the concepts behind RESTful architecture. RESTful architecture with traditional RPC, SOAP, etc. are very different in concept, I hope this can be helpful for you to understand REST.

Guess you like

Origin www.cnblogs.com/zhangxinglong/p/11113235.html