The original link: www.cnblogs.com/tugenhua070…

RESTful is currently the most popular API design specification, and it is used for the design of Web data interfaces. It’s literally a Rest interface, so let’s take a look at what Rest is.

REST has nothing to do with technology and represents a software architecture style. REST is an acronym for Representational State Transfer, which translates in Chinese as “Representational State Transfer” or “representation-layer State Transfer.” It is based on HTTP, URI, XML, JSON and other standards and protocols, and supports lightweight, cross-platform, cross-language architecture design.

Understand why RESTful API design specifications are used?

A long time ago, if you worked long hours, you must have experienced the use of Velocity syntax to write HTML template code. In other words, our front-end pages were compiled on the server side. The page, data, and template rendering operations are all done on the server side, but there is a major drawback to this: late maintenance is cumbersome, and front-end developers must master the relevant syntax of Velocity. Therefore, in order to solve this problem, the idea of separating the front and back ends gradually emerged: that is, the back end is responsible for the data interface, the front end is responsible for the data rendering, and the front end only needs to request the API interface to get the data, and then display the data. As a result, backend developers need to design API interfaces to unify specifications: The community has developed the RESTful API specification, which has been around for a long time, but has recently gained popularity. RESTful apis can provide services for all Web related aspects through a unified set of interfaces, separating the front end from the back end.

Rest design principles

So how can you design into a REST architectural specification? The following principles need to be met:

  • Each URI represents a resource;
  • Multiple representations of the same resource (XML/JSON);
  • All operations are stateless.
  • Standardize the unified interface.
  • Returns a consistent data format.
  • Cacheable (the client can cache the contents of the response).

An architectural approach that conforms to the REST principles described above is called a RESTful specification.

Understand why all operations need stateless?

HTTP request itself is stateless, which is based on client-server architecture. Each request sent by the client to the server must have sufficient information to be recognized by the server. Some information of the request is usually included in the query parameters or headers of THE URL. The server can directly return data to the client according to the various parameters of the request without saving the state of the client. The advantage of stateless is that it can greatly improve server-side robustness and scalability. A client can use a token to identify the session status. This allows the user to remain logged in.

Understand standardized interfaces

Rest interface constraints are defined as follows: Resource identification; Request action; Response information; It represents the resource to be operated by URI, identifies the operation to be performed by request action (HTTP Method), and represents the execution result of this request by return status code.

Perhaps the above explanation is not enough to understand, the following I through their own understanding to explain the above specific meaning; For example, before I used the Rest specification, we might have had add, delete, change, and search interfaces, so we would have designed interfaces that looked something like this: / XXX /newAdd (add interface), / XXX /delete(delete interface), / XXX /query (query interface), / XXX /uddate(modify interface), etc. There are four different interfaces for add, delete, modify, and query, which can be difficult to maintain, so if we were using the Restful specification now, we would probably only need one interface for development design, such as/XXX /apis. Methods include GET– query (retrieving resources from the server); POST- Add (create a resource from the server); PUT, DELETE, PATCH, PATCH, etc. After using RESTful specifications, we have one interface. If we want to add, DELETE, change, or query, We just need to use different HTTP method to do this, and then the data returned by the server can be the same, but our front end will determine the status value of the successful or failed request according to the status code. And we’ll talk about those status codes.

Understand how to return consistent data formats

The data returned by the server can be in XML, JSON, or a status code. For example, return json data in the wrong format as follows:

{" code ": 401, the" status ":" error ", "message" : 'user without permission, "data" : null}Copy the code

Json data that returns the correct data format can typically be as follows:

{
    "code": 200,
    "status": "success",
    "data": [{
        "userName": "tugenhua",
        "age": 31
    }]
}
Copy the code

URL and parameter design specifications

Uri Design specification

  1. The uri does not need to end with a slash /
  2. The use of slash/in URIs expresses hierarchy.
  3. You can use the hyphen – in the URI to improve readability.

For example, xxx.com/xx-yy is more readable than xxx.com/xx_yy. 4) Do not allow the underscore character _. 5) Use lowercase characters as much as possible in URIs. 6) File extensions are not allowed in the URI. For example, if the interface is/XXX/API, do not write/XXX /api.php, which is illegal. 7) Use plural forms in URIs. Specific can see: (https://blog.restcase.com/7-rules-for-rest-api-uri-design/)

In RESTful architecture, each URI represents a resource, so you can’t use verbs in URI design, only nouns, and plural nouns should be used as much as possible. Users should use the corresponding HTTP verbs GET, POST, PUT, PATCH, DELETE and so on to operate these resources.

So before we used the RESTful specification, we defined the interface in the following way, the form was not fixed, and there was no uniform specification. For example:

http://xxx.com/api/getallUsers; / / GET request, for all the users information http://xxx.com/api/getuser/1; // GET request mode, Identified as 1 user information http://xxx.com/api/user/delete/1 / / the GET and POST to delete logo for 1 user information http://xxx.com/api/updateUser/1 / way/POST request Identified as 1 user information http://xxx.com/api/User/add/update/POST request, add a new userCopy the code

As we can see above, before the use of Restful specifications, interface forms are not fixed, there is no unified specification, let’s take a look at the interface using Restful specifications as follows, a comparison between the two can see the advantages of each.

http://xxx.com/api/users; / / GET request way for all user information http://xxx.com/api/users/1; / / GET request method for identification of 1 user information http://xxx.com/api/users/1; / / DELETE requests to DELETE logo for 1 user information http://xxx.com/api/users/1; // Update user information identified as 1 http://xxx.com/api/users in PATCH request mode; // Add a new user by POST requestCopy the code

As we can see above, we all use the same API interface for addition and deletion, but the request methods of GET(query), POST(new), DELETE(DELETE), and PACTH(partial update) represent the operation methods of addition, deletion, modification, and review. We can then retrieve the request’s header information and know how to request the data.

HTTP Request specification

GET (SELECT): query; Fetching resources from the server. POST (CREATE) : new; Create a new resource on the server. PUT (UPDATE) : UPDATE; Update the resource on the server (the client provides the changed full resource). PATCH (UPDATE) : UPDATE; Update part of the resource on the server (the client provides the changed properties). DELETE (DELETE) : DELETE; Deletes resources from the server.

Parameter naming convention

You are advised to name parameters with underscores (_). For example, demo:

http://xxx.com/api/today_login // Get the user who logged in today. http://xxx.com/api/today_login&sort=login_desc // Obtain the descending order of current login users and login time.Copy the code

4. HTTP status code related

Status code range

The server must respond to each request from the client, which usually consists of HTTP status code and data.

1xx: message, request received, continue processing. 2xx: success. The behavior is successfully received, understood, and adopted. 3xx: redirection. 4xx: client error, request contains syntax error or request cannot be implemented. 5xx: Server side error.

2 xx status code

200 OK [GET]: The server returns the requested data successfully. 201 CREATED [POST/PUT/PATCH]: Data is CREATED or modified successfully. 202 Accepted Indicates that a request has been queued in the background (usually an asynchronous task). 204 NO CONTENT -[DELETE]: The user succeeded in deleting data.

4 xx status code

400: Bad Request – [POST/PUT/PATCH]: Indicates that an error occurs in the Request sent by the user. The server does not understand the Request sent by the client and does not process the Request. 401: Unauthorized; Indicates that the user has no permission (incorrect token, user name, or password). 403: Forbidden: Indicates that a user is authorized, but the access is Forbidden. It can also be interpreted as that the user does not have the permission to access resources. 404: Not Found: The requested resource does Not exist or is unavailable. 405: Method Not Allowed: The user has been authenticated, but the HTTP Method used is Not within its permissions. 406: Not Acceptable: The format of the user’s request is Not available (for example, the user requested JSON format, but only XML format). 410: Gone – [GET]: The resource requested by the user is transferred or deleted. And you won’t get it again. 415: Unsupported Media Type: the return format required by the client is not supported. For example, the API can only return JSON, but the client requires XML. 422: Unprocessable Entity: The request fails because the attachment uploaded by the client cannot be processed. 429: Too Many Requests: The number of Requests from the client exceeded the threshold.

5 xx status code

5XX status code Indicates a server error.

500: INTERNAL SERVER ERROR; An error occurred on the server. 502: Gateway error. 503: Service Unavailable The server cannot process the request currently. 504: The gateway times out.

5. Unified return data format

Requests in RESTful specifications should return a uniform data format. The returned data generally contains the following fields:

  1. Code: indicates the status code of the HTTP response.
  2. Status: contains text, such as’ SUCCESS ‘, ‘fail’, and ‘error’. The HTTP status response code between 500 and 599 is ‘fail’. ‘error’ between 400 and 499, ‘success’ generally. For the response status code is 1XX, 2XX, 3XX and so can be based on the actual situation.

When the value of status is ‘fail’ or’ error’, a message field needs to be added to display error messages.

  1. Data: Data returned when a request is successful. But when the status value is ‘fail’ or’ error’, data only contains information about the cause of the error or the exception.

The JSON format of a successful response is as follows:

{
    "code": 200,
    "status": "success",
    "data": [{
        "userName": "tugenhua",
        "age": 31
    }]
}
Copy the code

The json format of the failed response is as follows:

{" code ": 401, the" status ":" error ", "message" : 'user without permission, "data" : null}Copy the code