当前位置:网站首页>Understanding restful API

Understanding restful API

2020-12-07 21:47:25 itread01

# RESTful Interface combat > Original public number :bigsai Reprint please contact bigsai > > Articles are collected in [ Return to class ](https://ke.boxuegu.com/detail/3327.html) ### Preface Learning RESTful Before the style interface , Even if you don't know what it is , But you're sure to wonder what it solves ? 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 completely popular , Mobile terminals are not so popular , Page requests and concurrency are not high , At that time, people didn't have such a high demand for interfaces , Some dynamic pages (jsp) Can meet the vast majority of use needs . ![image-20201204001441126](https://bigsai.oss-cn-shanghai.aliyuncs.com/img/image-20201204001441126.png) But with the development of the Internet and mobile devices , People are interested in Web The demand for applications has also increased , The traditional dynamic page is gradually being HTML+JavaScript(Ajax) The front and back ends of the , And Android 、IOS、 Small programs and other forms of clients emerge in endlessly , The types of clients are diversified ,** The client and server need the interface to communicate **, But the interface ** Normative ** It's a problem again : ![image-20201204001702612](https://bigsai.oss-cn-shanghai.aliyuncs.com/img/image-20201204001702612.png) So a set of ** Clear structure 、 Meet the standards 、 Easy to understand 、 The expansion kit is convenient ** It becomes more and more important for most people to understand and accept the interface style , and RESTful The interface of style (RESTful API) Just have the above characteristics , It has gradually become popular by practical application . ![image-20201204001618944](https://bigsai.oss-cn-shanghai.aliyuncs.com/img/image-20201204001618944.png) Now ,RESTful The most popular interface design is currently , It is widely used in many companies , among [Github Of API Design ](https://developer.github.com/v3/) It's very standard RESTful API, You can refer to learning . In development practice, many of us may still use tradition API Request interaction , Many people don't really know RESTful API, Yes RESTful API The cognition of may stay in : - Resource oriented - It's a style - ( Misunderstandings ) Interfaces pass arguments using slashes (/) Split up without a question mark (?) Chuan Shen . In fact, a big mistake is not to think that no query string is RESTful API, Don't think that the query string is not RESTful API, Don't think it's used JSON Transmitted API Namely RESTful API. This tutorial will take you to understand RESTful And use SpringBoot Actual combat RESTful API, Before implementing this case , You need to make sure that on your computer - Possess IDEA Used to write project code - Possess Postman Simulate requests for testing - Have a relational database MySQL 5.7 - Possess navicat Yes MySQL Manage ### One 、REST Introduce REST There may be more conceptual things involved , In actual combat RESTful API Before , Right REST The relevant knowledge has a systematic cognition . #### REST The birth of REST( english :Representational State Transfer, Abbreviation REST, The state transition of the representation layer ) It's a software architecture style 、 Design style , Not the standard , It just provides a set of design principles and constraints . It is mainly used for client and server interactive software . Software designed in this style can be more concise , More layers , It is easier to implement mechanisms such as caching . It first appeared in 2000 year Roy Thomas Fielding In his doctoral dissertation , This paper defines and describes in detail the expressive state transition (Representational State Transfer,REST) Architecture style of , And it describes How to use REST To guide the modern Web Architecture design and development . In his own words : > My purpose in writing this article is : In accordance with the principle of Architecture , Understand and evaluate the architecture design of web based applications , Get a powerful 、 It works well 、 Appropriate communication architecture . It should be noted that **REST There is no clear standard , It's more like a design style **, A program or interface that meets this design style is called RESTful( Literally, it's an adjective ). therefore RESTful API It's satisfaction REST Architecture style interface . ![ Insert picture description here ](https://img-blog.csdnimg.cn/20200923192141691.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwNjkzMTcx,size_1,color_FFFFFF,t_70) Fielding What the doctor put forward at that time was REST Architecture didn't get much attention in a long time , In recent years REST It's becoming more and more popular in China . Let's start learning in detail REST Architecture features . #### REST Architecture features Since I know REST and RESTful The connection and difference of , Now it's time to get to know RESTful Some of the constraints and rules of ,RESTful It's a style, not a standard , And this style has the following main ** Features **: ** Resource based ** : A resource can be a picture 、 Music 、 One XML Format 、HTML Format or JSON An entity on the network, such as format , In addition to some binary resources, ordinary text resources are more to JSON As a carrier 、 A set of data for users ( Usually from the database query to get ). ** Unified interface **: Operations on resources include obtaining 、 establish 、 Modify and delete , These operations correspond to HTTP The agreement provides GET、POST、PUT and DELETE Method . In other words, we know , Use RESTful But from the interface you may only be able to locate its resources , But it's impossible to know exactly what it's doing , You need to know what kind of operation happened. You should learn from it HTTP Request method type to determine . Specifically HTTP The meaning of method and method is as follows : - GET(SELECT): Get resources from server ( One or more ). - POST(CREATE): Create a new resource on the server . - PUT(UPDATE): Update resources on server ( The client provides complete resource information ). - PATCH(UPDATE): Update resources on server ( The client provides the resources that need to be modified ). - DELETE(DELETE): Remove resources from server . Of course, there are many in the specific use of PUT Update . From the request process ,RESTful API And tradition API The general structure is as follows : ![image-20201204001311359](https://bigsai.oss-cn-shanghai.aliyuncs.com/img/image-20201204001311359.png) **URI Point to resources **:URI = Universal Resource Identifier Uniform resource identifier , A compact string used to identify abstract or physical resources .URI Include URL and URN, More often than not, it means URL( Uniform resource locator ).RESTful It's resource oriented , Each resource may consist of one or more URI Correspondence , But one URI Point to only one resource . ** Stateless **: The server cannot store client information , Every time a request is sent from the client , Include all necessary status information , Session information is stored by the client , The server processes the request based on the status information . Send request information when client can switch to a new state , 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 Architecture constraints Fielding Put forward in the paper REST Architecturally 6 One ** Restrictions **, It can also be called RESTful 6 Big principles , Standard REST The constraint should satisfy the following 6 Principles : ** Client - Server-side (Client-Server)**: This is more focused on the separation of client and server , Independent server can better serve the front end 、 Android 、IOS Wait for the client device . ** Stateless (Stateless)**: The server does not store client state , The client stores the state information and carries the state information every time it requests . ** Cacheability (Cacheability)** : The server needs to reply whether it can be cached, so that the client can identify whether the cache is efficient . ** Unified interface (Uniform Interface)**: Design the interface by certain principles to reduce coupling , Simplify system architecture , This is RESTful The basic starting point of design . Of course, in addition to the above features, there are more specific contents mentioned in this article [REST The content of the paper is ](https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm). ** Layered systems (Layered System)**: The client cannot directly know whether the connection is to the terminal or the intermediate device , Layering allows you to deploy server side projects flexibly . ** On demand code (Code-On-Demand, Optional )**: On demand code allows us to flexibly send some seemingly special code to the client, such as JavaScript Code . REST Some of the architectural styles and constraints will be introduced here , It's right behind RESTful Style API In particular . ### Two 、RESTful API Design specifications Now that I understand RESTful Some of the rules and features of , So how to design a RESTful API Well ? From URL Path 、HTTP Request verb 、 The status code and return results are considered in detail . To other aspects such as error handling 、 Filtering information and other specifications will not be introduced in detail here . #### URL Design specifications URL For unified resource locator , The interface belongs to the server resource , First of all, through URL~~ This ~~ Only by locating the resource can you access it , And usually a complete URL The composition consists of the following parts : ``` URI = scheme "://" host ":" port "/" path [ "?" query ][ "#" fragment ] ``` scheme: The underlying protocol , Such as http、https、ftp host: Server's IP Address or domain name port: Port ,http The default is 80 Port path: Access to resources , It's all kinds of web Defined in the framework route route query: Query string , Is the argument sent to the server , Here's more paging for transfer data 、 Sort the arguments . fragment: Anchor point , Locate resources on the page We're designing API When URL Of path It needs serious consideration , and RESTful Yes path The design has made some specifications , Usually a RESTful API Of path The composition is as follows : ``` /{version}/{resources}/{resource_id} ``` version:API Version number , Some version numbers can be placed in the header information , By controlling the version number, it is advantageous to apply iteration . resources: Resources ,RESTful API The plural form of lower case English words is recommended . resource_id: Of resources id, Access or manipulate the resource . Of course , Sometimes the resource level may be higher , It can also be subdivided into many sub resources and can be flexibly designed URL Of path, for example : ``` /{version}/{resources}/{resource_id}/{subresources}/{subresource_id} ``` Besides , Sometimes, it may be added, deleted, modified or checked to meet the business requirements , Can be in URL Add... At the end action, for example ``` /{version}/{resources}/{resource_id}/action ``` among action It is the operation of resources . Learn from the general pattern URL After the path is composed , For RESTful API Of URL The specific design specifications are as follows : 1. Don't use capital letters , All words are in English and lower case . 2. The hyphen uses the middle bar `"-"` Instead of going down the bar `"_"` 3. Use... Correctly `"/" ` Represents a hierarchical relationship ,URL Don't be too deep , And the higher the level, the more stable it should be 4. Don't end with a forward slash separator `"/"` 5. URL There is no verb in , To express an action in the form of a request 6. Resources are expressed in the plural, not in the singular 7. Don't use extensions #### HTTP Verb stay RESTful API in , Different HTTP Request methods have their own meanings , Here we show GET,POST,PUT,DELETE Several requests API Design and meaning analysis of . For different operations , The specific meaning is 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: Remove resources from server ``` In Africa RESTful Style API in , We usually use GET Request and POST Request to complete addition, deletion, modification and other operations , Query and delete are generally used GET Way request , Update and insert are generally used POST Ask for . You can't know from the way you ask API What exactly is it for , All in URL There will be operational verbs to indicate API The action that's going on , for example :query,add,update,delete wait . and RESTful Style API The requirement is URL They all appear in the form of nouns , You can see the desired operation from several request modes , This and the wrong RESTful Style API In sharp contrast . Talking about GET,POST,PUT,DELETE When , We have to mention the interface of ** Security and idempotency **, Security means that the method does not modify the state of the resource , That is to say, what is read is safe , Write operations are not secure . Idempotency means that the final effect of one operation is the same as that of multiple operations , Repeated calls from the client only return the same result . These four HTTP The security and idempotency of the request method are as follows : | HTTP Method | Security | Idempotence | Explain | | ----------- | :----- | :----- | ---------------------------------------- | | GET | Security | Idempotent | Read operation security , The results of the query are consistent | | POST | Non safety | Non idempotent | Writing is not secure , Every time you insert a new result | | PUT | Non safety | Idempotent | Writing is not secure , The results of one and many updates are consistent | | DELETE | Non safety | Idempotent | Writing is not secure , One and many deletions are consistent | #### Status code and return data After the server completes processing, the client may not know whether it has succeeded or failed , When the server responds , contain ** Status code ** and ** Return data ** Two parts . ** Status code ** First of all, we should correctly use all kinds of status codes to represent the processing and execution results of the request . Status codes are mainly divided into five categories : >1xx: Related information >2xx: Successful operation >3xx: Redirect >4xx: Client error >5xx: Server error Each large class has several small categories , There are many kinds of status codes , The main common status codes are listed below : 200 `OK - [GET]`: The server successfully returned the data requested by the user , The operation is idempotent (Idempotent). 201 `CREATED - [POST/PUT/PATCH]`: The user created or modified the data successfully . 202 `Accepted - [*]`: Indicates that a request has entered the background queue ( Asynchronous task ) 204 `NO CONTENT - [DELETE]`: User successfully deleted data . 400 `INVALID REQUEST - [POST/PUT/PATCH]`: There is an error in the user's request , The server is not creating or modifying data , The operation is idempotent . 401 `Unauthorized - [*]`: Indicates that the user does not have permission ( token 、 User name 、 Password error ). 403 `Forbidden - [*]` Indicates that the user is authorized ( And 401 Mistakes are relative to ), But access is forbidden . 404 `NOT FOUND - [*]`: The user's request is for a record that doesn't exist , The server is not operating , The operation is idempotent . 406 `Not Acceptable - [GET]`: The format of the user's request is not available ( Such as user request JSON Format , But only XML Format ). 410 `Gone -[GET]`: The resource requested by the user is permanently deleted , And it won't come back . 422 `Unprocesable entity - [POST/PUT/PATCH]` When an object is created , A validation error occurred . 500 `INTERNAL SERVER ERROR - [*]`: Server error , The user will not be able to determine whether the request was successful . ** Return the result ** For different operations , The server returns data to the user , The return entity classes encapsulated by different teams or companies are also different , But they all returned JSON Format data to client . ### The third level One RESTful API Case study It says RESTful Theoretical knowledge , Let's start to implement a small case ! #### Preparation In the actual combat of this case , We visited RESTful Interfaces are real operations on databases , New database , Build a database and tables ( According to one's own preference ). Choice Maven When you depend on , Just check it Spring Of Web Module 、MySQL Drive and MyBatis frame . In this case POJO establish Dog.java Physical objects , Its concrete structure is : ```java package com.restfuldemo.pojo; public class Dog { private int id;// only id Identification private String name;// Name private int age;// Age // Omit get set } ``` It creates a project , We started building RESTful Style API. In concrete construction RESTful API When , Need to have a more detailed understanding of the various requests , Of course , In this case, when implementing various requests, for the convenience of demonstration, it does not fully follow RESTful API Regulate , Information such as version number will not be added here , The case is more focused on use SpringBoot Implement this interface . This case realizes to dog Addition, deletion, modification and search of resources , The following is true and false RESTful and RESTful Interface comparison : | API name | Not RESTful | RESTful | | -------- | :---------------------- | :---------------------- | | Get dog | `/dogs/query/{dogid}` | GET: `/dogs/{dogid`} | | Insert dog | `/dogs/add` | POST: `/dogs` | | to update dog | `/dogs/update/{dogid}` | PUT:`/dogs/{dogid}` | | Delete dog | `/dods/delete/{dogid} ` | DELETE:`/dogs/{dogid}` | In addition, we are using postman When making a transfer request , There are three common file types that are passed to the back end : ![ Insert picture description here ](https://img-blog.csdnimg.cn/20201009210738355.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwNjkzMTcx,size_1,color_FFFFFF,t_70) **form-data** : Namely form In the form multipart/form-data, Information will be processed for a form , Separate pieces of information with specific tags , This file type is usually used to upload binary files . **x-www-form-urlencoded**: Namely application/x-www-form-urlencoded, yes form Form default encType,form The form will convert the data in the form into key value pairs , This format can't upload files . **raw**: You can upload text in any format , It can be uploaded Text,JSON,XML etc. , But most of them are still uploading JSON Format data . When the back end needs to receive JSON Format data processing , You can use this format to test . Because GET The request query argument is in URL On , Other types request to use x-www-form-urlencoded Back end mode . #### GET POST PUT DELETE Ask for **GET Requests are used to get resources **:GET The request will send a request for information to the database , In order to get resources , The request is like a database of select The operation is the same , It's just for information , It doesn't affect the content of the resource . No matter how many operations , The results are the same . And GET The request appends the argument of the request to URL Behind , But different browsers have different size and length restrictions . In this case , We designed two GET Requested API. `GET /dogs` : To return to dog List of resources . `GET /dogs/{dogid}` : To query this id The individual dog Resources . **POST The request is used to add a resource ** : POST Request to send data to the server , But the request changes the content of the data ( New addition ), It's like the database `insert` The operation is the same , Will create new content . And POST The request arguments of the request are all in the body of the request , There is no limit to its size . In this case , We design the following POST Requested API. `POST /dogs` : Add a new server dog Resources . **PUT Requests are used to update resources **,PUT The request is to send data to the server , And POST The difference between requests is ,**PUT The request focuses on the modification of the data ** , It's like in the database update The same thing , and POST The request focuses on the addition of information . In this case , We design the following POST Requested API. `PUT /dogs/{dogid}` : To update this id The individual dog Resources . **DELETE Requests are used to delete resources **,DELETE The purpose of the request is consistent with its literal meaning , Used to delete resources . And in the database delete Correspond to . In this case , We design the following DELETE Requested API. `DELETE /dogs/{dogid}` : Used to delete this id The individual dog Resources . Corresponding Mapper The file is : ```java 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")

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207214620650p.html