Detailed restful API

architectural features

resource-based

​ A resource can be a picture, music, an entity on the network in XML format, HTML format, or JSON format. In addition to some binary resources, ordinary text resources are more of a set of user-oriented data with JSON as the carrier ( Usually retrieved from a database query).

unified interface

​ Operations on resources include acquisition, creation, modification, and deletion, which correspond to the GET, POST, PUT, and DELETE methods provided by the HTTP protocol. In other words, using a restful-style interface, you may locate its resources from the interface, but you cannot know what operations it has performed. You need to know what operations have occurred to judge from the type of its HTTP request method. The specific HTTP methods and crime meanings are as follows:

GET(SELECT):从服务器取出资源(一项或多项)。
POST(CREATE):在服务器新建一个资源。
PUT(UPDATE):在服务器更新资源(客户端提供完整资源数据)。
PATCH(UPDATE):在服务器更新资源(客户端提供需要修改的资源数据)。
DELETE(DELETE):从服务器删除资源。

From the perspective of the request process, the general structure of restful and traditional APL is as follows:

The URL points to the resource

​ URI = Universal Resource identifier (Universal Resource Identifier), a compact string used to identify abstract or physical resources. URL includes URL and URN, which may refer to URL (Uniform Resource Locator) more often here. Restful is resource-oriented. Each resource may be associated with one or more URIs, but a URI only points to one resource.

no status

​ The server cannot save the client's information. Every request sent from the client must contain all the necessary state information. The session information is saved by the client. The server processes the request according to these state information. When the client can switch to a When a new state is sent, the request information is sent. When one or more requests are sent, the client is in a state transition process. The state description of each application can be used by the client to initiate the next state transition.

rest architecture constraints

Standard rest constraints should satisfy the following six principles:

客户端-服务端(Client-Server): 这个更专注客户端和服务端的分离,服务端独立可更好服务于前端、安卓、IOS等客户端设备。

无状态(Stateless):服务端不保存客户端状态,客户端保存状态信息每次请求携带状态信息。

可缓存性(Cacheability) :服务端需回复是否可以缓存以让客户端甄别是否缓存提高效率。

统一接口(Uniform Interface):通过一定原则设计接口降低耦合,简化系统架构,这是RESTful设计的基本出发点。当然这个内容除了上述特点提到部分具体内容比较多详细了解可以参考这篇REST论文内容。

分层系统(Layered System):客户端无法直接知道连接的到终端还是中间设备,分层允许你灵活的部署服务端项目。

按需代码(Code-On-Demand,可选):按需代码允许我们灵活的发送一些看似特殊的代码给客户端例如JavaScript代码。

restful API design specification

URL design specification

URL is a uniform resource locator, and the interface belongs to the resource of the server. You must first locate the resource through the URL to access it. Usually, a complete URL consists of the following parts:

URI = scheme "://" host  ":"  port "/" path [ "?" query ][ "#" fragment ]

scheme: Refers to the underlying protocol, such as http, https, ftp
host: IP address or domain name of the server
port: port, http defaults to port 80
path: the path to access resources, which is the route routing
query defined in various web frameworks: The query string is the parameter sent to the server, where more parameters such as data paging and sorting are sent.
fragment: anchor point, locate the resource of the page

When we design an API, the path of the URL needs to be carefully considered, and RESTful has made some specifications for the design of the path. Usually, the path of a RESTful API consists of the following:

/{version}/{resources}/{resource_id}

version: API version number. Some version numbers can also be placed in the header information. Controlling the version number facilitates application iteration.
resources: resources, RESTful API recommends using the plural form of lowercase English words.
resource_id: the id of the resource, access or operate the resource.

Sometimes the resource level may be large, and many sub-resources can be subdivided under it, and the URL path can be flexibly designed, for example:

/{version}/{resources}/{resource_id}/{subresources}/{subresource_id}

Sometimes adding, deleting, modifying and searching may not meet the business requirements, you can add action at the end of the URL, for example:

/{version}/{resources}/{resource_id}/action

The action is the operation on the resource.

After understanding the composition of the URL path from the general style, the specifications for the specific design of the URL of the restful APL are as follows:

1.不用大写字母,所有单词使用英文且小写。
2.连字符用中杠"-"而不用下杠"_"
3.正确使用 "/"表示层级关系,URL的层级不要过深,并且越靠前的层级应该相对越稳定
4.结尾不要包含正斜杠分隔符"/"
5.URL中不出现动词,用请求方式表示动作
6.资源表示用复数不要用单数
7.不要使用文件扩展名
HTTP verb

In a non-restful API, different HTTP request methods have their own meanings. For different operations, the specific meanings are as follows:

GET /collection:从服务器查询资源的列表(数组)
GET /collection/resource:从服务器查询单个资源
POST /collection:在服务器创建新的资源
PUT /collection/resource:更新服务器资源
DELETE /collection/resource:从服务器删除资源

In non-restful APIs, we usually use GET requests and POST requests to complete additions, deletions, modifications, and other operations. Queries and deletions generally use GET requests, and updates and insertions generally use POST requests. It is impossible to know what the API does from the request method. There are always operational verbs on the URL to represent the actions performed by the API, such as: query, add, update, delete, etc.

The restful-style API requires nouns to appear on the URL, and the desired operation can be seen from several request methods, which is in stark contrast to the non-restful-style API.

When talking about GET, POST, and DELETE, it is necessary to mention the security and idempotency of the interface .

Security means: the method will not modify the resource state, the reading operation is safe, and the writing operation is non-safe.

Idempotence means that the final effect of one operation is the same as that of multiple operations, and the client returns only the same result after repeated calls.

The security and idempotency of the above four HTTP request methods are as follows:

Status code and return data

After the server processing is completed, the client may not know the specific success or failure. When the server responds, it includes two parts : the status code and the returned data .

status code:

First of all, it is necessary to correctly use various status codes to indicate the processing and execution results of the request. Status codes are divided into five categories:

1xx:相关信息
2xx:操作成功
3xx:重定向
4xx:客户端错误
5xx:服务器错误		

Each major category has several subcategories, and there are many types of status codes;

status code illustrate
200 (Success) The server has successfully processed the request.
201 (Created) The request was successful and the server created a new resource.
204 (No Content) The server successfully processed the request, but returned no content.
301 (Moved Permanently) The requested web page has been permanently moved to a new location.
302 (temporarily moved) The server is currently responding to requests from a different location.
400 (Bad Request) The server did not understand the syntax of the request.
401 (Unauthorized) The request requires authentication.
403 (Forbidden) No permission, the server rejects the request.
404 (not found) The server could not find the requested resource
408 (timeout) request timed out
422 (Validation Error) The request parameter did not pass validation
429 (Throttled) Too many requests
500 (Server Internal Error) The server encountered an error and was unable to complete the request.
501 (Not yet implemented) The server is not capable of fulfilling the request.
502 (Bad Gateway) The server, acting as a gateway or proxy, received an invalid response from an upstream server.
503 (Service Unavailable) The server is currently unavailable (due to being overloaded or down for maintenance). Usually, this is only a temporary state.
504 (Gateway Timeout) The server is acting as a gateway or proxy, but did not receive the request from the upstream server in time.
505 (HTTP version not supported) The server does not support the HTTP protocol version used in the request.
Disadvantages of restful APL
  • The operation method is cumbersome. RESTful API usually distinguishes the actions of manipulating resources according to GET, POST, PUT, and DELETE. The HTTP Method itself is not directly visible, but is hidden. If the action is placed on the path of the URL, it will be clearly visible, which is more conducive to Team understanding and communication.
  • And some browsers are not very friendly to requests other than GET and POST, and special additional processing is required.
  • Excessive emphasis on resources, and the actual business API may have various requirements that are more complex. The addition, deletion, modification and query of resources alone may not be able to effectively meet the usage requirements. Forcibly using the RESTful style API will only increase the difficulty and cost of development.

Guess you like

Origin blog.csdn.net/weixin_53156345/article/details/130676526