In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to correctly understand RESTful". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand RESTful correctly".
Preface
Before you learn the RESTful-style interface, even if you don't know what it is, you must wonder what it can solve. What are the application scenarios? After listening to the following description, I think you will understand:
In the early days when the Internet was not fully popular, the mobile side was not so popular, and the number of page requests and concurrency was not high. At that time, people's requirements for interfaces were not so high, and some dynamic pages (jsp) could meet the vast majority of user needs.
However, with the development of the Internet and mobile devices, the demand for Web applications is also increasing. Traditional dynamic pages are gradually replaced by the separation of front and back ends of HTML+JavaScript (Ajax) due to inefficiency, and Android, IOS, Mini Program and other forms of clients emerge in endlessly, and the types of clients are diversified, while the client and server need interfaces to communicate, but the standardization of the interface has become a problem:
Therefore, a set of interface style which is clear, standard, easy to understand and easy to expand so that most people can understand and accept the interface style becomes more and more important, and the RESTful-style interface (RESTful API) just has the above characteristics, so it is gradually applied in practice and becomes popular.
Now, RESTful is the most popular interface design specification, which is widely used in many companies, in which the API design of Github is a very standard RESTful API, you can refer to and learn.
In development practice, many of us may still use traditional API for request interaction. In fact, many of us do not know much about RESTful API, and our understanding of RESTful API may stay at:
Resource type oriented
It's a style.
(misunderstanding) the interface passes parameters using a slash (/) instead of a question mark (?) Pass parameters.
In fact, a big misunderstanding is not to think that there is no query string is RESTful API, and do not think that the query string is not RESTful API, let alone that the API transmitted by JSON is RESTful API.
1. Introduction of REST
REST involves some conceptual things may be more, before the actual RESTful API, it is necessary to have a systematic understanding of REST-related knowledge.
The birth of REST
REST (Representational State Transfer, abbreviated as REST, literally translated presentation layer state transition) is a kind of software architecture style and design style, not a standard, but provides a set of design principles and constraints. It is mainly used for client and server interaction class software. Software designed based on this style can be more concise, more hierarchical, and easier to implement caching and other mechanisms.
It first appeared in Roy Thomas Fielding's doctoral thesis in 2000, which defines and introduces in detail the architectural style of declarative state transition (Representational State Transfer,REST), and describes how to use REST to guide the design and development of modern Web architecture. In his own words:
My purpose of writing this article is to understand and evaluate the architecture design of web-based application software under the premise of architecture principle, and get an architecture with strong function, good performance and suitable for communication.
It should be noted that REST does not have a clear standard, but is more like a design style, and the program or interface that satisfies this design style is called RESTful (literally an adjective). So RESTful API is an interface that meets the architectural style of REST.
Dr Fielding replied
What Dr. Fielding proposed at that time is that REST architecture has not been paid much attention for a long time, while REST has become more and more popular in China in recent years. Let's learn more about the architectural features of REST.
REST architecture characteristics
Now that you know the connection and difference between REST and RESTful, it's time to understand some of the constraints and rules of RESTful. RESTful is a style rather than a standard, and this style roughly has the following main features:
Based on resources: resources can be an entity on the network, such as a picture, music, a XML format, HTML format or JSON format. In addition to some binary resources, ordinary text resources are more JSON-based, user-oriented data (usually queried from the database).
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 an RESTful-style interface, but you may only be able to locate its resources from the interface, but you don't know exactly what it does, and you need to know exactly what happens to it, depending on its HTTP request method type. The specific HTTP methods and methods are as follows:
GET (SELECT): fetch a resource (one or more) from the server.
POST (CREATE): create a new resource on the server.
PUT (UPDATE): update the resource on the server (the client provides complete resource data).
PATCH (UPDATE): update the resource on the server (the client provides the resource data that needs to be modified).
DELETE (DELETE): removes resources from the server.
Of course, there are also many people who use PUT to indicate updates when they are in specific use. From the point of view of the request process, RESTful API and traditional API are roughly structured as follows:
URI points to a resource: URI = Universal Resource Identifier uniform resource identifier, a compact string used to identify abstract or physical resources. URI includes URL and URN, which may refer to URL (uniform resource locator) more often. RESTful is resource-oriented, and each resource may correspond to one or more URI, but a URI points to only one resource.
Stateless: the server cannot save the information of the client. Every request sent from the client should contain all the necessary state information. The session information is saved by the client, and the server processes the request according to these state information. Request information is sent when the client can switch to a new state, and 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 initialize the next state transition.
REST schema constraints
In this paper, Fielding puts forward six restrictions of REST architecture, which can also be called RESTful six principles. The standard REST constraints should meet the following six principles:
Client-server (Client-Server): this is more focused on the separation of the client and the server, and the server can better serve the front end, Android, IOS and other client devices.
Stateless: the server does not save the client state, and the client saves the status information and carries the status information with each request.
Cacheability (Cacheability): the server needs to reply whether it can be cached to allow the client to identify whether caching can improve efficiency.
Unified Interface (Uniform Interface): reduce coupling and simplify system architecture by designing interfaces with certain principles, which is the basic starting point of RESTful design. Of course, this content in addition to the above characteristics mentioned part of the specific content more detailed understanding can refer to the content of this REST paper.
Hierarchical system (Layered System): the client cannot directly know whether it is connected to a terminal or an intermediate device, and tiering allows you to deploy server-side projects flexibly.
On-demand code (Code-On-Demand, optional): on-demand code allows us the flexibility to send seemingly special code to clients such as JavaScript code.
Some of the styles and limitations of the REST architecture are introduced here, followed by a specific introduction to the RESTful style API.
II. RESTful API Design Specification
Now that you know some of the rules and features of RESTful, how do you design a RESTful API? It should be considered in detail in terms of URL path, HTTP request verb, status code, and return result. As for other aspects such as error handling, filtering information and other specifications will not be described in detail here.
URL design specification
URL is a unified resource locator. APIs belong to server resources. You must first locate the resource through URL before you can access it. Usually, a complete URL consists of the following parts:
URI = scheme ": / /" host ":" port "/" path ["?" Query] ["#" fragment]
Scheme: refers to the underlying protocols, 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 defined in various web frameworks
Query: query string, which is the parameter sent to the server, where more parameters such as data paging, sorting, and so on are sent.
Fragment: anchor point, navigate to the resource on the page
The path of URL needs to be carefully considered when designing API, and RESTful has made some specifications for the design of path. Usually, the path composition of a RESTful API is as follows:
/ {version} / {resources} / {resource_id}
Version:API version number, some version numbers can also be placed in the header information, by controlling the version number to facilitate the application of iteration.
Resources: resources, RESTful API recommends the plural form of lowercase English words.
Resource_id: the id of a resource that accesses or manipulates it.
Of course, sometimes the resource level may be large, and many sub-resources can be subdivided under it, and the path of URL can be designed flexibly, for example:
/ {version} / {resources} / {resource_id} / {subresources} / {subresource_id}
In addition, sometimes additions, deletions, changes and queries may not meet the business requirements. You can add action at the end of the URL, for example
/ {version} / {resources} / {resource_id} / action
Where action is the operation of resources.
After understanding the composition of URL paths from the general style, the specific design specifications for RESTful API URL are as follows:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
No uppercase letters, all words are in English and lowercase.
Hyphens use the middle bar "-" instead of the lower bar "_"
Correctly use "/" to indicate hierarchical relationship. The level of URL should not be too deep, and the higher the level, the more stable it should be.
Do not include the forward slash delimiter "/" at the end
The verb does not appear in URL, and the action is expressed by request.
Resource representation is plural, not singular.
Do not use file extension
HTTP verbs
In RESTful API, different HTTP request methods have their own meanings. Here we show the design and meaning analysis of several GET,POST,PUT,DELETE request API. For different operations, the specific meanings are as follows:
GET / collection: query the list of resources from the server (array) GET / collection/resource: query a single resource from the server POST / collection: create a new resource on the server PUT / collection/resource: update server resources DELETE / collection/resource: delete resources from the server
In non-RESTful-style API, we usually use GET requests and POST requests to complete additions, deletions, modifications and other operations. Queries and deletions usually use GET requests, updates and inserts usually use POST requests. It is impossible to know exactly what API does from the way the request is made. All verbs that operate on URL denote the actions performed by API, such as query,add,update,delete and so on.
On the other hand, RESTful-style API is required to appear as nouns on URL, and you can see what you want to do from several request methods, which is in sharp contrast to non-RESTful-style API.
When talking about GET,POST,PUT,DELETE, we must mention the security and idempotency of the interface, where security means that the method does not modify the resource state, that is, the read is secure and the write operation is non-secure. Idempotency means that the final effect of one operation is the same as that of multiple operations, and repeated calls by the client only return the same result.
The security and idempotency of the above four HTTP request methods are as follows:
Status code and return data
After the server-side processing is completed, the client may not know whether it has succeeded or failed. When the server responds, it includes two parts: the status code and the returned data.
Status code
First of all, we should correctly use all kinds of status codes to represent the processing and execution result of the request. Status codes are mainly divided into five categories:
1xx: related information 2xx: operation succeeded 3xx: redirect 4xx: client error 5xx: server error
There are several subcategories in each category, and there are many types of status codes, and the main commonly used status codes are listed below:
200 OK-[GET]: the server successfully returned the data requested by the user, which is idempotent (Idempotent).
201 CREATED-[POST/PUT/PATCH]: the user created or modified data successfully.
202 Accepted-[*]: indicates that a request has entered the background queue (asynchronous task)
204NO CONTENT-[DELETE]: user deleted data successfully.
400 INVALID REQUEST-[POST/PUT/PATCH]: the request made by the user is incorrect and the server does not create or modify data, which is idempotent.
Unauthorized-[*]: indicates that the user does not have permissions (token, user name, password error).
Forbidden-[*] indicates that the user is authorized (as opposed to the 401 error), but access is prohibited.
404 NOT FOUND-[*]: the request made by the user is for a record that does not exist, and the server does not operate, which is idempotent.
Not Acceptable-[GET]: the format of the user request is not available (for example, the user requests the JSON format, but only the XML format).
410 Gone-[GET]: the resource requested by the user is permanently deleted and will not be obtained again.
422 Unprocesable entity-[POST/PUT/PATCH] A validation error occurred while creating an object.
500 INTERNAL SERVER ERROR-[*]: an error occurred on the server and the user will not be able to determine whether the request was successful or not.
Return the result
The server returns data to the user for different operations, and the return entity classes encapsulated by each team or company are also different, but all return data in JSON format to the client.
The third level is a RESTful API case.
Above talked about the theoretical knowledge of RESTful, let's start to achieve a small case!
ready
In the actual combat of this case, the RESTful interfaces we access are all real operations on the database, creating a new database, creating a database and tables (according to your preferences).
When selecting Maven dependencies, you only need to check the Web module, MySQL driver and MyBatis framework of Spring.
The POJO in this case creates a Dog.java entity object, which is constructed as follows:
Package com.restfuldemo.pojo; public class Dog {private int id;// unique id identification private String name;// name private int age;// age / omitting get set}
Once the project is created above, we begin to build a RESTful-style API. When building RESTful API, you need to have a more detailed understanding of various requests. Of course, this case does not fully follow the RESTful API specification for the convenience of demonstration when implementing various requests. For example, information such as version number is not added here, and the case focuses more on using SpringBoot to implement this API.
This case implements the addition, deletion, modification and query of dog resources. The following is the comparison of non-RESTful and RESTful APIs:
In addition, when sending a request using postman, three common file types are passed to the backend:
Form-data: the multipart/form-data in the form form processes the form data into a piece of information and splits the pieces of information with specific tags, and this file type is usually used to upload binary files.
X-www-form-urlencoded: application/x-www-form-urlencoded, the default encType,form form for form forms converts the data in the form into key-value pairs, and files cannot be uploaded in this format.
Raw: you can upload text in any format, you can upload Text,JSON,XML, etc., but most of them still upload data in JSON format. When the back end needs to receive data processing in JSON format, it can be tested in this format.
Because the GET request query parameter is on URL, other types of requests use x-www-form-urlencoded to pass values to the backend.
GET POST PUT DELETE request
GET request is used to obtain resources: the GET request sends a request for data to the database to obtain the resource. Just like the select operation of the database, the request is only used to query the data and does not affect the content of the resource. No matter how many operations are performed, the result is the same.
And the GET request appends the requested parameters to the URL, but different browsers have different size and length limits.
In this case, we design two API for GET requests.
GET / dogs: used to return a list of dog resources.
GET / dogs/ {dogid}: a single dog resource used to query this id.
The POST request is used to add a resource: the POST request sends data to the server, but the request changes the content of the data (new), just like the insert operation of the database, creating new content. And the request parameters of the POST request are all in the request body, and their size is unlimited.
In this case, we design the API for the following POST request.
POST / dogs: add a dog resource to the server.
PUT requests are used to update resources, and PUT requests send data to the server. Unlike POST requests, PUT requests focus on data modification, just like update in the database, while POST requests focus on the increase of data.
In this case, we design the API for the following POST request.
PUT / dogs/ {dogid}: a single dog resource used to update this id.
The DELETE request is used to delete the resource, and the purpose of the DELETE request is literally used to delete the resource. Corresponds to the delete in the database.
In this case, we design the API for the following DELETE request.
DELETE / dogs/ {dogid}: a single dog resource used to delete this id.
The corresponding Mapper files are:
Package com.restfuldemo.mapper; import com.restfuldemo.pojo.Dog; import org.apache.ibatis.annotations.*; import java.util.List; @ Mapper public interface DogMapper {@ Select ("select * from dog") List getAllDog (); @ Select ("select * from dog where id=# {id}") Dog getDogById (@ Param ("id") int id) @ Insert ("insert into dog (name,age) values (# {name}, # {age})") boolean addDog (Dog dog); @ Update ("update dog set name=# {name}, age=# {age} where id=# {id}") boolean updateDog (Dog dog); @ Delete ("delete from dog where id=# {id}") boolean deleteDogById (int id);}
The corresponding controller files are:
Package com.restfuldemo.controller; import com.restfuldemo.mapper.DogMapper; import com.restfuldemo.pojo.Dog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.List; @ RestController public class TestController {@ Autowired (required = false) DogMapper dogMapper; @ GetMapping ("dogs") public List getDogs () {return dogMapper.getAllDog () } @ GetMapping ("dogs/ {id}") public Dog getDogById (@ PathVariable ("id") int id) {Dog dog=dogMapper.getDogById (id); return dog;} @ PostMapping ("dogs") public boolean addDog (Dog dog) {return dogMapper.addDog (dog) } @ PutMapping ("dogs/ {id}") public boolean updateDog (@ PathVariable ("id") int id,@RequestParam ("name") String name,@RequestParam ("age") int age) {Dog dog=dogMapper.getDogById (id); dog.setName (name); dog.setAge (age); return dogMapper.updateDog (dog) } @ DeleteMapping ("dogs/ {id}") public boolean deleteDog (@ PathVariable ("id") int id) {return dogMapper.deleteDogById (id);}}
After the author's test, everything is ok.
Summary
It is true that RESTful-style API is very good and standardized, but most Internet companies do not design according to or completely follow its rules, because REST is a style, not a constraint or rule, too ideal RESTful API will pay too much cost.
For example, RESTful API also has some shortcomings.
For example, the mode of operation is tedious. RESTful API usually distinguishes the actions of operating resources according to GET, POST, PUT and DELETE, while HTTP Method itself is not directly visible and is hidden, but if the actions are put on the path of URL, they are clearly visible, which is more conducive to team understanding and communication.
And some browsers are not friendly to requests outside of GET,POST and require special extra processing.
Too much emphasis on resources, while the actual business API may have a variety of complex needs, just using the addition, deletion, modification and query of resources may not effectively meet the needs, forcing the use of RESTful-style API will only increase the difficulty and cost of development.
So, when you or your technical team are designing API, if the use scenario matches the REST style, then you can use the RESTful style API. However, if the business requirements do not match the RESTful-style API or it is troublesome, you can also use the RESTful-style API or learn from it. After all, no matter which style API is for the convenience of team development, negotiation and management, you can't stick to the rules.
This is the end of the introduction and actual combat of RESTful API, this article first introduces some of the characteristics of RESTful, and then to the SpringBoot actual combat RESTful API, and finally says some places where RESTful API is not perfect. I believe that the wise you must have a deep understanding of RESTful. The API design of the project will be optimized in the future.
Different people may have different understanding of RESTful API, but it is reasonable to exist. RESTful API has its distinct advantages and characteristics, and it is also one of the main choices of API design, so it is very important to master and understand RESTful API!
Thank you for your reading, the above is the content of "how to correctly understand RESTful". After the study of this article, I believe you have a deeper understanding of how to correctly understand RESTful, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.