Welcome toTencent Cloud + community, get more Tencent mass technology practice dry goods oh ~
This post was posted by Sam Shen on cloud + Community
REST apis have become increasingly popular in recent years, especially as the concept of microservices has become widely accepted and adopted, and many Web services use REST apis.
REST was proposed by Roy Fielding, one of the principal authors of the HTTP specification, and stands for Representational State Transfer, which can be translated as Representational State Transfer in Chinese. It is not an architecture, but an architectural style. REST proposes a set of architectural constraints and principles. Any architecture that meets REST constraints and principles is called a RESTful architecture.
REST is popular, but the industry has mixed results. Many systems claim to be REST apis without actually meeting REST’s architectural constraints. These systems, as they understand it, take some forms similar to REST apis (such as CURD with GET/POST/PUT/DELETE), but design more arbitrarily, resulting in REST-RPC-style and even RPC-style apis. Such apis not only fail to reflect the advantages of REST apis, but also become “different” and increase development and maintenance costs.
How to Understand REST
To standardize the use of RESTful architectures, you first need to understand what REST is. We can understand REST by understanding “presentation” and “state transition” respectively.
1) describe
Representation refers to the representation of a resource. RESTful Architecture is a resource-oriented Architecture (ROA) in which objects are processed as resources. Any object that needs to be referenced is a resource. A resource is represented as a specific URI.
The so-called expression refers to some form of representation of resources, which is not necessarily all information, but only part of the information concerned. And there can be multiple representations of the same resource. For example, a scenic spot can be represented as a JPEG photo, or as JSON or XML with location, introduction, and so on, respectively.
In REST, the communication between the client and the server is all about the representation of the resource.
2) State transfer
State should be divided into application state and resource state.
Application status, such as session status, is saved and maintained by the client. The client transfers the application state through the representation returned by the REST API and the URI in the representation.
But REST focuses more on resource state. The resource status is stored on the server. The client can add, delete, and modify the resource status by specifying the request method, resource path, and resource expression (including application status) using the REST API. Resource status change is caused by adding, deleting, checking, and modifying resources.
3) conclusion
In combination with the preceding two points, the client can add, delete, and check the resources on the server through the REST API, resulting in resource status transfer. And this transition is embodied in the representation, so it is called the declarative state transition.
What is a REST architectural style
Roy Fielding in his paper derived the REST architectural style by continually imposing constraints on an empty architecture. Therefore, to conform to the REST architectural style, constraints need to be met.
Those of you who are interested in the derivation can refer to Roy Fielding’s paper.
REST constraints are:
- Unified interface
- stateless
- The cache
- Client-server
- Layered system
- On-demand code (optional)
Among them, unified interface is the most intuitive, but also the biggest deviation in the application, the following will focus on. The other constraints are explained briefly.
1. Unified interfaces
The unified interface is embodied in several aspects:
- Resource uris
- Request parameters
- Request method
- Return code
- Returns the content
- …
1) resource uris
A RESTful architecture is a resource-based architecture where everything you operate on is a resource. Therefore, a resource needs to be explicitly located, and URI technology fills this need, so resources are located through URIs in REST.
A resource is an object, so urIs should generally contain only nouns (usually plural), not verbs. When you need to locate a specific resource, the URI usually contains the unique ID of the resource. Such as:
/ / satisfy the REST architectural style of the URI http://www.example.com/books the resource collection of all the books / / http://www.example.com/books/123 / / / / ID of 123 books resources Does not meet the REST architectural style of the URI http://www.example.com/books/query http://www.example.com/buyCopy the code
2) Request parameters
Because REST requires a URI to uniquely locate a resource (or resource), various resource ids are typically placed in the URI rather than in the request parameters when querying a resource. The request parameters usually contain fields such as paging information of filtering conditions. Such as:
/ / satisfy the REST architectural style URI http://www.example.com/books/123 / / ID of 123 books resources http://www.example.com/Fielding/books?page=1&per_page=10 / / authors for Fielding of the top 10 books resource collection / / does not meet the REST architectural style URI http://www.example.com/books?id=123 http://www.example.com/books?author=FieldingCopy the code
3) Request method
REST conventions use request methods such as GET, POST, PUT, and DELETE to perform CURD operations. However, the use of GET/POST/PUT/DELETE is not a standard for judging whether a system conforms to the REST architectural style. For example, some systems that use GET and POST methods for all interfaces may be reST-compliant if they only provide query and create operations. However, if the system also provides modification and deletion operations, the system does not conform to the REST architecture style.
Some people think that GET/POST/PUT/DELETE has a one-to-one relationship with CURD, but it’s not.
Specifically, each request method is as follows:
- GET: Used to query resources.
- POST: Used to create resources. POST method to create resource URI is determined by the server, such as: POST www.example.com/Fielding/bo… And created a book resources, resource URI is www.example.com/Fielding/bo… , where :id is the id generated by the server, which may be a self-increment ID or hash value, etc. The POST www.example.com/Fielding/bo… , creates a resource of a certain category, such as a book comment, under the book resource with ID 123. The URI of the comment also contains a server-generated ID.
- PUT: Used to create or modify resources. The PUT method to create resource URI is decided by the client, such as: PUT www.example.com/Fielding/bo… If the book resource whose ID is 123 exists, the system will modify the resource. Otherwise, create a vm.
- DELETE: Deletes resources.
In addition, there are other request methods that are less commonly used, and it is important to note that some browsers may not support them.
- HEAD: The meta information used to get the resource. The HEAD method is similar to the GET method in that it queries for meta information about the resource (put in the Header of the HTTP Response), but does not return a representation of the resource. For example, to check whether a resource exists.
- PATCH: Used to modify resources. Unlike the PUT method, the PATCH method transmits only part of the changed resource expression, whereas the PUT method transmits the entire resource expression.
4) return code
REST uses HTTP return codes to represent the result of a request. If you use a canonical REST API, you can determine a lot of information based on the HTTP return code. Common HTTP return codes are as follows:
- 200 (OK) : The request is successful.
- 201 (Created) : a resource is Created successfully.
- 204 (No content) : The resource is empty.
- 301 (Moved Permanently, Permanently) : The URI of the resource has been changed, and a new URI needs to be obtained in the response.
- 302 (Moved Temporarily) : Indicates that the URI of the resource has been Temporarily changed and a new URI needs to be obtained in the response.
- 400 (Bad Request) : indicates that the Request is faulty, for example, the parameter is incorrect.
- 403 (Forbidden) : Indicates that the authentication fails and you cannot access the resource.
- 404 (Not Found) : The resource does Not exist.
- 405 (Method Not Allowed) : Indicates that the resource does Not support the current request Method.
- 409 (Conflict) : a prerequisite condition of the current request is not met.
- 500 (Internal Server Error) : indicates a common Internal Error.
- 502 (Bad Gateway) : The Gateway is incorrect, and an invalid response is received from the upstream server.
- 504 (Gateway Timeout) : indicates that the Gateway times out. No response is received from the upstream server within the expected time.
- …
There are other HTTP return codes that you can refer to the HTTP standard.
As long as the canonical REST architectural style is used, it is possible to make a clear response to the HTTP standard without the need for a separate proprietary protocol. This reduces proprietary protocol compatibility issues and can be used as a standard for all RESTful architectures.
5) Return content
The content returned by the REST API should be a representation of the resource.
As mentioned earlier, the same resource can be represented in many different formats, such as JSON and XML, so the returned content should be self-describing. That is, the HTTP response Header must contain content-Type attributes such as Application /json, Application/XML, text/ HTML, and so on.
In addition, REST is a “programmable” Web service, meaning that a program can take the next step based on what the REST API returns. For example, to query an author resource, the next step might be to query the Book resource for that author’s work. So, if the expression of the author resource contains the URI of the author’s book resource, the client can act accordingly. Another example is to query a map resource. If the map resource expression contains adjacent map resources in each direction, when the client mouse moves to the edge of the screen, the map resource in this direction can be obtained. Or the map resource expression contains resource URIs such as scenic spots and restaurants, you can perform corresponding operations.
Uris that contain other resources in the expression implement connectivity. Connectivity can serve as a state engine for client application state, guiding the client to the next step, bringing great convenience.
6) other
There are other aspects of unified interfaces that I won’t cover in detail in this article, but you can read Fielding’s paper.
2. No state
Stateless constraints mean that there is no dependency between two requests and each request contains complete state information. The state refers to the state of communication between the client and the server, and has nothing to do with the resource state.
For a stateful example, in order to check wages, you need to log into the system (first request) and then enter the query password (second request). If the previous two requests pass, then the query interface is called to query the salary; Otherwise, an unauthenticated error is reported when the query interface is invoked. The return result of the query salary interface is associated with the state of the previous two requests, so it is a stateful service.
For stateless services, the interface for querying wages is directly invoked. Authentication information is contained in the request (usually in the Header). If the authentication succeeds, the wages can be queried; if the authentication fails, an error is reported. The request does not depend on any prior request and is called stateless.
REST uses stateless constraints to ensure independence and simplicity of requests, reducing much of the cost of maintaining state across requests. The trade-off, of course, is that each request may require the transfer of redundant information.
3. The cache
Cache constraints are primarily used to improve network efficiency. A cache constraint requires that the data in the response to a request be marked either implicitly or explicitly as cacheable or non-cacheable. If the response is cacheable, the client cache can reuse the data for that response for future identical requests, reducing network interaction and improving efficiency, scalability, and user-perceived performance.
4. Client-server
This constraint is mainly to separate user interface and data storage, on the one hand to improve the portability of user interface across platforms, on the other hand to simplify server components and improve system scalability.
5. Hierarchical systems
Hierarchical system architecture constraints divide the architecture into several layers, delimiting the boundaries of each layer, thereby reducing the complexity of the design of each layer. At the same time, layers can abstract the heterogeneity of the bottom layer, provide unified interfaces for the upper layer, and simplify the logic of the upper layer.
6. On-demand code
Code on demand constraints refer to situations in which the client does not know how to handle a resource and requests the server for the appropriate handling code to perform it. This simplifies client development and allows functional code to be downloaded after deployment to improve system scalability. However, it is an optional architectural constraint of REST because the transfer is an agent, which reduces visibility.
Question and answer
In Java REST
reading
Experience the Django REST Framework and interpret the REST architecture style
How do I step by step find pressure measurement performance bottlenecks with GO
MySQL > select * from mysql_pool
Machine learning in action! Quick introduction to online advertising business and CTR knowledge
This article has been authorized by the author to Tencent Cloud + community, more original text pleaseClick on the
Search concern public number “cloud plus community”, the first time to obtain technical dry goods, after concern reply 1024 send you a technical course gift package!
Massive technical practice experience, all in the cloud plus community!