Restful Interface Design Notes

Introduction
REST (Respresentational State Transfer) architectural style is a style of architecture promoted to the information in the first-class citizens. REST system can be achieved by high-performance, scalable, simplicity, extensibility and modifiability and other characteristics.
1. Introduction
REST architectural style is not a technology that can be purchased, nor is it can be added to a software development project development libraries. First and foremost, REST style is a world view, for the construction of the information infrastructure to enhance the first-class citizens.

To summarize, RESTful choose from a deployment by characteristic architecture of the system to obtain the desired characteristics. Although the details of such constraints defined style and design is not designed for all occasions, but indeed widely used.

Since the web has many important influence on consumer preferences, REST-style advocates encourage organizations to use the same principles within its borders, just as they do on the page as for external customers, this article will discuss the implementation of modern REST web basic constraints and attributes.
1.1 basic concepts of
REST What does it mean? Transmission in a stateless manner, access and manipulate the text data, when properly deployed, the REST provide consistent interoperability between different applications on the Internet. Stateless (Stateless) term is essential, so that it can communicate with the application agnostic manner. RESTful API via a Uniform Resource Locator address (URL) public services, URL names will be assigned to receive either the content or return the content of the resource area.

The actual public is not necessarily in any particular service, but on behalf of consumers valuable information resource. URL as a handle resources, you can request, update, or delete content.

Development of the service to publish somewhere, and then begin interacting with the REST service. Returned content may be XML, JOSN format, or, more precisely, like the Atom or custom MIME type of hypermedia format. While it is generally recommended that as much as possible to reuse the existing format, but the media is the correct type of design is becoming more and more tolerant.

Need to request resources when the client sends a Hypertext Transfer Protocol (HTTP) GET request, for example, type a URL in your browser and hit enter, select a bookmark, or click the reference anchor connection.

API to programmatically interact with RESTful, dozens of client API or tools to choose from, using the cur command-line tool, you can enter the following command:
cur http://www.baidu.com

SOAP: Simple Object Access Protocol (Simple Object Access Protocol). It is a protocol specification data exchange, a lightweight, simple, XML-based protocol. A SOAP message is an ordinary XML document containing the required Envelope element, an optional Header element, required Body element and optional Fault element.
The REST and SOAP equate wrong. Troubled comparison between the two, bring far more than the benefits. In simple terms, they are not the same thing. Although architecture can solve many problems with these two methods, but they can not replace each other.

The confusion is largely due to misunderstanding of the "REST URL by calling Web services," this sentence. This view RESTful architecture with functionality far apart. If not comprehensive in-depth understanding of RESTful architecture implementation, it is easy to misunderstand the intention REST practice.

The best way to take advantage of REST is the production and consumption of information technology in the process of separation of decoupling, and thus better management system, so that architecture has the following characteristics:

1, high-performance

2, extensible

3, GM

4, simple

5, can be modified

This is not to say that the system built on SOAP can not have the above characteristics. But when the complexity of the technology, or process causes tissue can not be completed in a single transaction request life cycle, such a case can exhibit the best results SOAP.

  1. Richardson Maturity Model

Leonard Richardson introduces a maturity model, describes the distinction between the part and the REST SOAP, and to provide a system for different types of frame classification. Many people inappropriately called "REST". This classification can be seen as the tightness of the system in different Web technology component metrics: including information resources, HTTP as an application layer protocol and for hypermedia as the control medium.

Called "maturity model" seems to mean that you should build only "maturity" highest system. This view is not appropriate. Level 2 is valuable from level 2 to level 3 transition usually only uses a new MIME type. However, the transition from level 0 to level 3 much more difficult, so the incremental upgrade will usually change the value.

First, determine what information resources want to open. As an application using HTTP protocol processing these information resources, including content negotiation. Then, when everything is ready, based hypermedia MIME type, so that you can fully enjoy the benefits of REST.

  1. verb

Verbs are used with the method of interactive server resources or operations. RESTful system new to the finite verb allow users confused and frustrated. Seemingly arbitrary and unnecessary restrictions to encourage the provision of predictable form of application-independent behavior. Independent processing by explicitly and clearly define the behavior of these verbs, the client can interrupt or failure in the network.

Well-designed RESTful system mainly uses four HTTP verbs.

4.1 GET

GET requests are the most commonly used Web verb. GET request to name the resource from the server to the client. Although the client does not need to know the contents of the requested resource, but the result of the request is returned with metadata tags byte stream, which indicates that the client should know how to interpret the resource. Usually expressed in Web "text / html" or "application / xhtml + xml". As previously mentioned, the return form as long as the server supports the client can specify the content negotiation advance request.

GET request one of the key points, do not modify any of the content on the server side. This is a basic safety requirements, it is not familiar with REST One of the biggest mistakes developers make. You may encounter this URL:

http://example.com/res/action=update?data=1234

Do not do this! Since GET request to allow security cache requests, it makes're building RESTful system into chaos. GET request idempotency also means that many requests will not have any impact on the system. This is based on an important feature of the distributed infrastructure. It is interrupted if a GET request, because the idempotency, the client can initiate a request again. This point is very important. In a well-designed infrastructure, the client can initiate a request from any application. Although there will be specific behavior associated with the application, but adding more application-independent behavior of the system will be more flexible, and easier to maintain.

4.2 POST

When POST and PUT verb discern intent, the situation began to become less clear. By definition, both of which seem to be used by clients to create or update server resources, but their use varies.

When unpredictable identification request to create a resource, the client uses the POST request. In the new employees, when an order or submit a form, we can not predict how the server will be named resource being created. That's why the resources to submit such a program similar to Servlet process. Next, the server will accept, verification request to verify the user credentials and the like. After successful treatment, the server returns a 201 HTTP response code, wherein the position comprises a "Location" header, the representative newly created resource.

Note: Some people will create a resource of GET POST deemed session. They have the resources created by the body to return 200 instead of returning 201. This seems to be a quick way to avoid a second request, but this practice a mix of POST and GET, so that the potential impact of cache resources become subtle. Try to avoid the cut corners at the expense of the big picture. In the short term it seems to be worth it, but over time, add up these shortcuts may be adversely affected.

Another major use POST verb is "Append (Append)" resource information that is part of the incremental edit or update, rather than submit a complete resource. PUT operation should be used here. Use POST update known resources that can be used to add a new shipping address or update an order quantity of an item shopping cart.

Because it is part of the updated resource information, POST neither safe nor idempotent.

The last common use of POST is to submit queries. After the contents of the query or URL encoded form content submitted to the service to execute the query. POST usually can return results relevant to the query because there is no identity.

Note: It is recommended to such a query into information resources themselves. If POST query, you can consider using a GET request, which supports caching. You can share this link with others.

4.3 PUT

Because HTML forms currently does not support PUT, many developers will basically ignore PUT verb. However, PUT has an important role and is part of a complete vision of RESTful system.

The client can send a PUT request to specify a URL, the server performs overwriting data request. PUT requests in a way such as power, rather than updating POST.

If the client is interrupted while covering PUT request, due to the re-sending operation covering not cause any consequences, it can be sent again. The client has the ability to manage the state, so the direct retransmission coverage command.

Note: This protocol layer handles does not mean that you want to cancel a higher level (such as the Application Layer) transactions, but equally, it is also on an architecture ideal property, the following can be used in the application layer.

If the client can understand the resource identified in advance, it can also be used to create a resource PUT. As we discussed in the POST section, which usually does not occur. However, if the client can control the server information space, so this operation is reasonable.

4.4 DELETE

DELETE verbs are not widely used (thank goodness!) On the public network. However, it is useful to control the information space, it is a very useful resource life cycle part.

DELETE request is intended to achieve equal powers. Possibly due to network failure DELETE request was interrupted, this time we want the client to keep trying. The first request whether successful or not, the resource should return 204 (Not specified content). Of previously deleted resource or non-existent resources may require some additional processing, in both cases should return 404. Some security policy requirements and resources do not exist deleted return 404, so it will not leak DELETE request information about whether the resources exist.

There are three other valuable but not widely used verb.

4.5 HEAD

HEAD verb to request the resource, but does not actually retrieved. The client can check whether there through HEAD resources, and check the related metadata resources.

4.6 OPTIONS

OPTIONS verbs can also be used where the query server resources, and asked what is the resource available for other verb.

4.7 PATCH

The latest PATCH verb until 2010 was officially adopted as part of the HTTP. Aims to provide a standardized way to represent part of the update. PATCH request by a standard format let's intent to interact more clearly. It is recommended to use POST PATCH rather than the cause, although POST can be used for anything. IETF published RFC documents, define XML PATCH operations and JSON.

If a client header request PATCH with If-Match, then this section update idempotent. Interrupt request can be retried, because if the first request is successful, then the If-Match header will be different from the new state. If so, the original request may be applied to untreated PATCH.

  1. Response Code

HTTP response code provides us with a wealth of information at the request status dialogue between the client and the server. Most people are only familiar with 200,403,404 or 500 in the general sense, but there are many more useful code available. Here the table is not comprehensive, but they cover a lot in a RESTful environment should consider the most important code. Digital packet in accordance with the following categories:

1,1XX: Information category

2,2XX: Successful operation

3,3XX: Redirect

4,4XX: Client Error

5,5XX: Server Error

A first set of response codes indicate that the client requested format correctly and successfully processed. Specific operations in the following table:

Table 1 successful client requests

Table 2 - client redirection request

Table 3 The response code indicates that the client request is not valid, if the condition does not change, re-request can not be processed. These failures may have sent a malformed request, an unauthorized request, the requested resource does not exist and so on.

Table 3 client request error

Finally, Table 4 indicates the response code the server is temporarily unable to process a client request (may still be invalid). The client should re-request at some point in the future.

Table 4 server processes the request error

Services with different degrees of extensibility under its own functional requirements.

Note: Try response code 418, it will return a concise reply: "I'm a teapot."

5.1 REST resources

5.1.1 Papers

Thesis Dr. Fielding "architectural style and design of network-based software architecture" is the main idea of ​​the introduction of the RESTful: http: //www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

5.1.2 RFC specification

REST common use of technical specifications defined by the Internet Engineering Task Force ** (IETF), in accordance with the Request for Comment perfect (RFC) ** process. Specifications defined by numbers, and over time the updated version from time to time to replace the outdated files. Currently, here are the latest relevant RFC documents.

5.1.2.1 URI

RFC 3986 defines the generic URI syntax naming scheme. URI is a naming scheme, including such other URL, supports name subspace coding scheme. URL: http: //www.ietf.org/rfc/rfc3986.txt

5.1.2.2 URL

Url is a form of a URI, sufficient information embedded therein (typically an address and access scheme), and locating resources for parsing the Uniform Resource Locator. URL: http: //www.ietf.org/rfc/rfc1738.txt

5.1.2.3 IR

Character identifier of world languages ​​Internationalized Resource Identifier (IRI) is conceptually a Unicode encoded URI, for use on the Web in support. IETF choose to create a new standard, rather than changing the URI scheme itself, in order to avoid disrupting existing systems and a clear distinction between the two methods. Those who support the IRI did it on purpose. Also defines the mapping scheme for converting between IRI and URI. URL: http: //www.ietf.org/rfc/rfc3987.txt

5.1.2.4 HTTP

HTTP 1.1 version defines an application protocol for operating information resources are usually expressed in hypermedia format. Although it is an application-level protocol, but usually do not bind with the application, which had a significant structural advantage system. Most people think of HTTP and HTML text (HTML) is the "Web", but in a non-HTTP document-oriented system development is also useful. URL: http: //www.ietf.org/rfc/rfc2616.txt

5.1.2.5 PATCH format

JavaScript Object Notation (JSON) Patch URL: https: //www.ietf.org/rfc/rfc6902.txt

XML Patch URL: https: //www.ietf.org/rfc/rfc7351.txt

5.2 Description Language

People use a variety of languages ​​to describe the API is very interested in, makes it easier to write client and server document description language, and even generate skeleton code. Some of the more popular, interesting description languages ​​include:

5.2.1 RAML

RAML a YAML / JSON language, API Class 2 can be defined maturity. It supports reusable patterns and characteristics, standardized API functions designed by modes and features. URL: http: //raml.org

5.2.2 Swagger

Swagger is another YAML / JSON language, the API defines support level 2 maturity. It contains the code generator, editor, API documentation, visualization capabilities, can be integrated with other services. URL: http: //swagger.io

5.2.3 Apiary.io

Apiary.io is a collaborative hosting site. It supports Markdown format API documentation can be designed around the social process, and supports the realization of a managed simulation data, in order to test it out before the API. URL: http: //apiary.io

5.2.4 Hydra-Cg

Hydra-Cg hypermedia is a description language, and to realize the interaction data associated with other data sources, and easily by such as JSON-LD standard. URL: http: //www.hydra-cg.com

5.3 realized

There are used to build libraries and frameworks, generating and using RESTful system. Although any Web server can be configured to provide a REST API, but with these frameworks, libraries, and the environment can make the process easier.

The following outlines some of the mainstream environment:

5.3.1 JAX-RS

JAX-RS specification adds support for REST for JEE environment. URL: https: //jax-rs-spec.java.net

5.3.2 Restlet

Restlet API is to build one of the pioneer Java API for RESTful systems of production and consumption. It focuses on generating some very clean, powerful API for client and server.

Restlet Studio is a free tool, capable of converting between the swagger RAML based API and described, support the Restlet, JAX-RS and the backbone Node server and client and Stub code. URL: http: //restlet.org

5.3.3 NetKernel

Netkernel is a more interesting RESTful system. It is based on micro-kernel, it supports a variety of architectural styles on behalf of the environment. Netkernel economic benefit from using Web property in software architecture. You can think of it as "the introduction of REST inside." While any REST-based systems look the same on the outside, but it looked the same in an operational environment inside NetKernel. URL: http: //netkernel.org

5.3.4 Play

One of the two main Scala REST framework. URL: https: //www.playframework.com

5.3.5 Spray

One of the two main Scala REST framework. It is designed to fit Akka actor model to work with. URL: http: //spray.io

5.3.6 Express

One of the two main Node.js REST framework. URL: http: //expressjs.com

5.3.7 step

One of the two main Node.js REST framework. URL: http: //hapijs.com

5.3.8 Sinatra

Sinatra is a domain-specific language (DSL), used to create RESTful applications in Ruby, URL: http: //www.sinatrarb.com

5.4 Client

REST API calls through the browser is feasible, but there are other client systems can be used to test and build a resource-oriented.

5.4.1 curl

curl is one of the popular library and command-line tools, support for various protocols call on a variety of resources. URL: https: //curl.haxx.se

5.4.2 httpie

httpie is a very flexible and easy to use client, support and resources to interact via HTTP. URL: https: //httpie.org

5.4.3 Postman

Sound API tests need to be able to capture and replay request, support various authentication and authorization schemes. The previous command-line tool allowed to do so, but the Postman is a newer desktop applications, make these job easier for development teams. URL: https: //www.getpostman.com

Published 21 original articles · won praise 4 · Views 504

Guess you like

Origin blog.csdn.net/weixin_39617728/article/details/105017639