This article is mainly borrowed from others, but I would like to summarize a set of specifications, for me such a novice use, used to standardize the code, if there is any good proposal, please feel free to comment, this article long-term update!
I. Important Concepts:
REST stands for Representational State Transfer. My translation of this phrase is “presentation level state transitions”.
Resource: A single instance of an object. For example, an animal. It can be a text, a picture, a song, a service, or a concrete reality. You can point to it with a URI (uniform resource Locator), and each resource has a specific URI. To get the resource, access its URI, which becomes the address or unique identifier for each resource.
Collection: A collection of objects. For example, animals.
Third party: developers who use our interface
Representation
“Resource” is a kind of information entity, which can have many forms of external expression. We call a resource’s Representation of a Representation its’ Representation ‘.
State Transfer
Visiting a website represents an interactive process between the client and the server. In this process, data and state changes are inevitably involved. Internet Communication protocol HTTP is a stateless protocol. This means that all state is kept on the server side. Therefore, if the client wants to operate the server, it must somehow make a State Transfer happen on the server side. And this transformation is built on top of the presentation layer, so it is “presentation layer state transformation”.
The client can only use HTTP. Specifically, there are four verbs in the HTTP protocol that denote operations: GET, POST, PUT, and DELETE. They correspond to four basic operations: GET to obtain resources, POST to create resources (which can also be used to update resources), PUT to update resources, and DELETE to DELETE resources.
For example, text can be represented in TXT format, HTML format, XML format, JSON format, and even binary format. Images can be rendered in JPG format or PNG format.
A URI represents only the entity of a resource, not its form. Strictly speaking, the suffix “.html” at the end of some web addresses is not necessary because the suffix represents the format and belongs in the “presentation layer” category, whereas the URI should only represent the location of the “resource.” This representation should be specified in the HTTP request header in the Accept and Content-Type fields that describe the “presentation layer.”
With that explained, let’s summarize what RESTful architecture is:
(1) Each URI represents a resource;
(2) between the client and the server, the transfer of some kind of representation layer of this resource;
(3) The client operates on the server-side resources through four HTTP verbs to achieve “state transformation of the presentation layer”.
2. REST interface specifications
1, the action,
GET (SELECT) : Retrieves a specific resource, or a list of resources, from the server. POST (CREATE) : Creates a new resource on the server. PUT (UPDATE) : Updates the resource on the server, providing the entire resource. PATCH (UPDATE) : Updates resources on the server, providing only the changed properties. DELETE (DELETE) : deletes resources from the server.
First, there are four and a half actions: POST, DELETE, PUT/Patch, and GET. Since PUT/Patch can only be classified as one class, patch is classified as half.
There are also two less well-known HTTP verbs: HEAD – to retrieve metadata about a resource, such as the hash of the data or the last update time. OPTIONS – Retrieves information about what the client is allowed to do with the resource.
2. Path (interface naming)
The path, also known as the endpoint, represents the specific URL of the API.
In a RESTful architecture, each url represents a resource, so there can be no verbs in the url, only nouns, and the nouns usually correspond to the table names in the database. Generally speaking, tables in a database are “collections” of the same records, so nouns in apis should also be plural.
For example, if there is an API that provides information about zoos, as well as information about various animals and employees, its path should look like this.
Use nouns instead of verbs. Here are some examples.
GET /zoos: lists all zoos POST /zoos: creates a new zoo GET /zoos/ID: obtains information about a specified zoo PUT /zoos/ID: updates information about a specified zoo (provides all information about the zoo) PATCH /zoos/ID: DELETE /zoos/ID: deletes a zoo GET /zoos/ID/animals: lists all animals for a specified zoo DELETE /zoos/ID/animals/ID: Deletes a specified animal from a specified zooCopy the code
Example:
/getAllCars
/createNewCar
/deleteAllRedCarsCopy the code
For example, if a URI is /posts/show/1, where show is the verb, the URI is incorrectly written as /posts/1, and the GET method is used to represent show.
If there are actions that cannot be represented by AN HTTP verb, you should make the action a resource. For example, if you send 500 yuan online from account 1 to account 2, the wrong URI is:
POST /accounts/1/transfer/500/to/2
A resource cannot be a verb, but can be a service:
POST HTTP / 1.1 / transaction
Host: 127.0.0.1
The from = 1 & to = 2 & amount = 500.00
Clarify the hierarchical structure of resources. For example, if the scope of business is school, then school will be the first-level resources (/school), teachers (/school/teachers), and students (/school/students) will be the second-level resources.
3. Versioning
You should put the VERSION number of the API in the URL. Such as:
https://api.example.com/v1/Copy the code
The alternative is to put the version number in the HTTP header, but it’s not as convenient and intuitive as putting it in the URL. Github takes this approach.
4. Information Filtering
If there are many records, the server cannot return them all to the user. The API should provide parameters that filter the return results. Here are some common parameters.
? Limit =10: Specify the number of records to return? Offset =10: Specifies the start of the return record. ? Page_number =2&page_size=100: specifies the number of pages and the number of records per page. ? Sortby = name&ORDER = ASC: Specifies by which attribute the return results are sorted, and in what order. ? Animal_type_id =1: The design of the specified filter parameter allows for redundancy, i.e., occasional duplication of API path and URL parameters. For example, GET /zoo/ID/animals versus GET /animals? Zoo_id =ID has the same meanings.Copy the code
5. Status Codes
Status code range
1XX message, request received, continue processing. The scope reserves things for the underlying HTTP that you will most likely never use. 3XX redirect, further action that must be performed to complete the request 4XX client error, request contains syntax error or request cannot be implemented. Scopes are reserved in response to errors made by clients, for example. They provide bad data or demand things that don't exist. These requests should be idempotent rather than changing the state of the server. Status codes in the 5XX range are reserved for server-side errors. These errors are often thrown from the underlying functions and are often beyond the reach of even the developer. The purpose of sending such status codes is to ensure that the client gets some kind of response. When receiving a 5XX response, it is impossible for the client to know the state of the server, so such status codes should be avoided whenever possible.Copy the code
The status code and prompt message returned by the server to the user are as follows (the corresponding HTTP verb is in square brackets).
200 OK - [GET] : the server successfully returns the requested data, which is Idempotent. 201 CREATED - [POST/PUT/PATCH] : Data is CREATED or modified successfully. 202 Accepted - [*] : indicates that a request is queued in the background (an asynchronous task). 204 NO CONTENT - [DELETE] : Indicates that the user deleted data successfully. 400 INVALID REQUEST - [POST/PUT/PATCH] : An error occurs in the REQUEST sent by the user. The server does not create or modify data. The operation is idempotency. 401 Unauthorized - [*] : Indicates that the user does not have permission (the token, user name, or password is incorrect). 403 Forbidden - [*] Indicates that the user is authorized (as opposed to the 401 error), but access is Forbidden. 404 NOT FOUND - [*] : The user requested a record that did NOT exist, the server did NOT perform the operation, the operation is idempotent. 406 Not Acceptable - [GET] : The format requested by the user is Not available (for example, the user requested JSON format, but only XML format). 410 Gone -[GET] : The requested resource is permanently deleted and cannot be retrieved. 422 Unprocesable Entity - [POST/PUT/PATCH] An authentication error occurred while creating an object. 500 INTERNAL SERVER ERROR - [*] : An ERROR occurs on the SERVER, and users cannot determine whether the request is successful. 502 A gateway error 503 Service Unavailable 504 The gateway times outCopy the code
References:
RESTful API design guidelines – nguyen one: http://www.ruanyifeng.com/blog/2014/05/restful_api.html