Read the restful principle and API interface specification in one article

Restful API is currently a relatively mature API design concept for a set of Internet applications. Rest is a set of architectural constraints and principles. The architecture that conforms to the Rest constraints and principles is called the Restful architecture. The Restful architecture has a clear structure, conforms to Standard, easy to understand and easy to expand, etc., are adopted by more and more websites!

Table of contents

1. Background

2. Basic concepts

2.1 Resources

2.2 Representation

2.3 State Transfer (State Transfer)

2.4 Concept summary

3. Rest design principles

3.1 Each URI represents a resource

3.2 The same resource has multiple manifestations

3.3 All operations are stateless

3.4 Standardized unified interface

3.5 Return a consistent data format

3.6 Cacheable (the client can cache the content of the response)

4. API interface design specification

4.1 URI specification

4.2 Request method

4.3 Filter information

4.4 Status codes


1. Background

Website development can completely adopt the software development model. But traditionally, software and network are two different fields, and there is little intersection; software development is mainly for stand-alone environment, while network is mainly for communication between systems. With the rise of the Internet, these two fields began to merge, and now we must consider how to develop software for use in the Internet environment.

The RESTful architecture is currently the most popular Internet software architecture. It has a clear structure, conforms to standards, is easy to understand, and is easy to expand, so it is being adopted by more and more websites.

However, what exactly is a RESTful architecture is not an easy question to clarify. Next, I will talk about the RESTful architecture I understand.

The word REST was proposed by Roy Thomas Fielding in his 2000 doctoral dissertation. Fielding is a very important person. He is the main designer of the HTTP protocol (version 1.0 and 1.1), one of the authors of the Apache server software, and the first chairman of the Apache Foundation. Therefore, once his paper was published, it attracted attention and immediately had a profound impact on Internet development.

2. Basic concepts

Fielding named his architectural principles for Internet software REST, which stands for Representational State Transfer. My translation of this phrase is "presentation layer state transformation". If an architecture conforms to the REST principles, it is called a RESTful architecture.

To understand the RESTful architecture, the best way is to understand what the phrase Representational State Transfer means, and what each word represents. If you understand the name, it is not difficult to understand what kind of design REST is.

2.1 Resources

In the REST name "Representation Layer State Transformation", the subject is omitted. The "presentation layer" actually refers to the "representation layer" of "Resources".

The so-called "resource" is an entity on the network , or a specific piece of information on the network. It can be a piece of text, a picture, a song, a service, in short, it is a concrete entity. You can point to it with a URI (Uniform Resource Locator), and each resource corresponds to a specific URI. To obtain this resource, just visit its URI, so the URI becomes the address or unique identifier of each resource.

The so-called "surfing the Internet" means interacting with a series of "resources" on the Internet and calling its URI.

2.2 Representation

"Resource" is an information entity that can have various external manifestations. The form in which we specifically present "resources" is called its "representation".

For example, text can be expressed in txt format, HTML format, XML format, JSON format, or even binary format; pictures can be expressed in JPG format or PNG format.

A URI only represents the entity of the resource, not its form. Strictly speaking, the ".html" suffix at the end of some URLs is unnecessary, because this suffix indicates the format and belongs to the category of "presentation layer", and the URI should only represent the location of "resources". Its specific form of expression should be specified in the header information of the HTTP request with the Accept and Content-Type fields, and these two fields are the description of the "presentation layer".

2.3 State Transfer (State Transfer)

Visiting a website represents an interactive process between the client and the server. In this process, data and state changes are bound to be involved.

The Internet communication protocol HTTP protocol is a stateless protocol. This means, all state is kept on the server side. Therefore, if the client wants to operate the server, it must use some means to make the server "state transfer" (State Transfer). And this transformation is based on the presentation layer, so it is "state transformation of the presentation layer".

The method used by the client can only be the HTTP protocol. Specifically, in the HTTP protocol, there are four verbs indicating the operation mode: GET, POST, PUT, DELETE. They correspond to four basic operations: GET is used to obtain resources, POST is used to create new resources (and can also be used to update resources), PUT is used to update resources, and DELETE is used to delete resources.

2.4 Concept summary

Based on the above explanations, let's summarize what a RESTful architecture is:

  (1) Each URI represents a resource;

  (2) Some kind of presentation layer (Representation) of this resource is transferred between the client and the server;

  (3) The client uses four HTTP verbs to operate on the server-side resources to realize "state transformation of the presentation layer".

3. Rest design principles

3.1 Each URI represents a resource

A URI represents only one type of resource.

http://xxx.com/api/users; // Get all user information http://xxx.com/api/teachers; // Get all teacher information http://xxx.com/api/areas; // Get all region information

3.2 The same resource has multiple manifestations

A resource can be returned in multiple formats ( xml, json, etc. ). When the client requests, we can set parameters in the request header and require restful to return the specified type of data. This is the meta-principle that the RESTful interface needs to meet;

Accept:application/xml Set the return form to xml when requesting, if you use ajax request, you need to set contentType:application/xml Accept:application/json set the return form to json, if you use ajax request, you need to set contentType:application /json

3.3 All operations are stateless

The http request itself is stateless, and RESTful is based on the stateless http protocol; therefore, various RESTful requests are also stateless.

It can be understood as follows: the protocol has no memory ability for transaction processing. The lack of state means that if subsequent processing needs previous information, it must be retransmitted, which can lead to an increase in the amount of data transferred per connection. But on the other hand, when the server does not need previous information, its response is faster.

For example, when a browser sends a request to the server, the server responds, but when the same browser sends a request to the server again, it responds, but it does not know that you are the browser just now. Simply put, it is The server will not remember you;

So if you need memory functions such as state, you can use the browser's cookie, session and token technology to achieve it.

3.4 Standardized unified interface

Rest interface constraints are defined as:

  • Resource identification: it means that the resource to be operated is indicated by uri, and verbs indicating operation cannot be included here;

  • Request action: identify the operation to be performed through the request action (http method);

  • Response information;: Indicate the execution result of this request through the returned status code;

Ordinary interfaces that do not meet the RESTful interface specification:

  • http://xxx.com/api/getallUsers; // GET request method to get all user information
  • http://xxx.com/api/getuser/1; // GET request method, get the user information identified as 1
  • http://xxx.com/api/user/delete/1 // GET, POST delete user information marked as 1
  • http://xxx.com/api/updateUser/1 // POST request method to update the user information identified as 1
  • http://xxx.com/api/User/add // POST request method, add new user

Standard unified RESTful style interface specification:

  • http://xxx.com/api/users; // GET request method to get all user information
  • http://xxx.com/api/users/1; // Get the user information identified as 1 by means of GET request
  • http://xxx.com/api/users/1; // DELETE request method to delete user information marked as 1
  • http://xxx.com/api/users/1; // PATCH request method, update the user part information identified as 1
  • http://xxx.com/api/users; // POST request method to add new users

3.5 Return a consistent data format

The returned data format has at least a few fields required by our standard, such as status, code, information, data, etc.

3.6 Cacheable (the client can cache the content of the response )

Now the interface basically provides a cacheable function, that is to say, in the interface development stage, we will set whether the browser can cache, as well as the type of cache and the effective time, etc. For example, strong cache and negotiated cache specifications are server-side settings of.

4. API interface design specification

4.1 URI specification

  • URL names must be in all lowercase

  • The resource (resource) name in the URL must be a noun and must be plural

  • Restful URLs must be preferred

  • - cannot appear in the URL, must be replaced by an underscore _

  • URL must be human readable

  • The URL must not expose the server architecture

http://xxx.com/api/male_users // Get male users.

http://xxx.com/api/male_users&sort=age_desc // Get male users in descending order of age.

  • Avoid multi-level URIs

A common situation is that resources require multi-level classification, so it is easy to write multi-level URLs, such as obtaining a certain category of articles by a certain author.

# GET /authors/12/categories/2

This kind of URL is not conducive to expansion, and the semantics are not clear. It takes a while to understand the meaning.

Better yet, all but the first level are expressed in query strings.

# GET /authors/12?categories=2

4.2 Request method

  • GET (SELECT): query; fetch resources from the server. POST (CREATE): add; create a new resource on the server;

  • POST (CREATE): Create a new resource on the server;

  • PUT(UPDATE): update; update the resource on the server (the client provides the complete resource after the change);

  • PATCH(UPDATE): update; update some resources on the server (client provides changed attributes);

  • DELETE(DELETE): delete; delete resource from server;

  • HEAD: Get the metadata of the resource;

  • OPTIONS: Get information about which properties of the resource the client can change.

4.3 Filter information

If there are a lot of records, it is impossible for the server to return them all to the user. The API will provide parameters to filter the returned results. The common parameters are:

  • ?limit=20: Specifies that the number of returned records is 20;

  • ?offset=8: Specifies that the starting position of the returned record is 8;

  • ?page=1&per_page=50: Specify page 1, and the number of records per page is 50;

  • ?sortby=name&order=asc: Specifies that the returned results are sorted in ascending order according to the name attribute;

  • ?animal_type_id=2: Specify the filter criteria.

4.4 Status codes

The following table lists common HTTP status codes

status code describe
1xx Delegate request has been accepted and needs to continue processing
2xx The request has been successful, and the response header or data body expected by the request will be returned with this response
3xx redirect
4xx Error caused by client
5xx Error caused by the server

In HTTP API design, the frequently used status codes and their specific descriptions are as follows:

Status Code Semantics illustrate
200 OK request was successful
201 Created The request has been completed and caused one or more resources to be created, most commonly used when POST creates resources
202 Accepted The request has been received and processed, but processing has not yet been completed. Generally used in the case of asynchronous processing, the response body should tell the client where to check the status of the task
204 No Content The request has been processed, but there is no information to return. It is often used when PUT updates resources (the client provides all the attributes of the resource, so there is no need for the server to return). If there is important metadata, it can be put in the header and returned
301 Moved Permanently The requested resource has been permanently moved to another location, and all subsequent requests should directly access the new address. The server will write the new address in the Location header field, which is convenient for the client to use. Allows the client to modify a POST request to a GET.
302 Moved Temporarily temporary redirect
304 Not Modified The requested resource is the same as the previous version and has not changed. Used to cache resources and appear together with conditional requests
307 Temporary Redirect The target resource is temporarily moved to a new address, and the client needs to go to the new address to operate, but cannot modify the requested method.
308 Permanent Redirect Similar to 301, except that the client cannot modify the method of the original request
400 Bad Request 1. The semantics are wrong, and the current request cannot be understood by the server; 2. The request parameters are wrong.
401 Unauthorized The current request requires authentication.
403 Forbidden The server has understood the request, but is refusing to honor it. Unlike a 401 response, authentication doesn't help, and the request shouldn't be repeated. If this is not a HEAD request, and the server wants to be able to explain why the request cannot be fulfilled, then the reason for the rejection should be described in the entity. Of course, the server can also return a 404 response, if it does not want the client to get any information.
404 Not Found The request failed because the requested resource was not found on the server.
405 Method Not Allowed The request method specified in the request line cannot be used to request the corresponding resource. The response must return an Allow header indicating the list of request methods accepted by the current resource. Since the PUT and DELETE methods will write to the resources on the server, most of the web servers do not support or do not allow the above request methods under the default configuration, and a 405 error will be returned for such requests.
406 Not Acceptable The content properties of the requested resource do not satisfy the conditions in the request headers, so a response entity cannot be generated.
409 Conflict The request could not be completed due to a conflict with the current state of the requested resource.
429 Too Many Requests Insufficient resource quota or rate limit reached.
499 Client Closed Request The request was canceled by the client.
500 Internal Server Error internal server error
501 Not Implemented The server does not support a feature required by the current request. When the server does not recognize the requested method and cannot support its request for any resource.
502 Bad Gateway A server acting as a gateway or proxy received an invalid response from an upstream server while attempting to fulfill a request.
503 Service Unavailable The server is currently unable to process the request due to temporary server maintenance or overload. This condition is temporary and will recover over time.
504 Gateway Timeout A server working as a gateway or proxy fails to receive a timely response from an upstream server (the server identified by the URI, such as HTTP, FTP, LDAP) or a secondary server (such as DNS) when it attempts to fulfill the request.
505 HTTP Version Not Supported 服务器不支持,或者拒绝支持在请求中使用的 HTTP 版本。

上面这些状态码覆盖了 API 设计中大部分的情况,如果对某个状态码不清楚或者希望查看更完整的列表,可以参考 HTTP Status Code。

Guess you like

Origin blog.csdn.net/caoyuan666/article/details/127226553