当前位置:网站首页>Before you read this for five minutes, you realize that you don't know restful

Before you read this for five minutes, you realize that you don't know restful

2020-12-08 10:23:29 bigsai

Original official account :bigsai Please contact bigsai
Articles are collected in Return to class and github

Preface

I'm learning RESTful Before the style interface , Even if you don't know what it is , But you're sure to 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 of the Internet, it wasn't completely popular , Mobile is not so popular , Page requests and concurrency are not high , At that time, people's requirements for interfaces were not so high , Some dynamic pages (jsp) Can meet the vast majority of use needs .

image-20201204001441126

But with the development of the Internet and mobile devices , People are right. 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 , And the client and server need the interface to communicate , But the interface Normative It's a problem again :

image-20201204001702612

So a set of The structure is clear 、 Meet the standard 、 Easy to understand 、 Easy to expand So that most people can understand the accepted interface style is becoming more and more important , and RESTful Style interface (RESTful API) Just have the above characteristics , It has gradually become popular by practical application .

image-20201204001618944

Now? ,RESTful It is the most popular interface design specification at present , It's widely used in many companies , among Github Of API Design 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 type oriented
  • It's a style
  • ( myth ) The interface uses slashes to pass parameters (/) Split up without a question mark (?) The ginseng .

In fact, a big mistake is not to think that no query string is RESTful API, Don't think that using the query string is not RESTful API, Don't think it's used JSON Transmission of 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

  • Have IDEA To write project code
  • Have Postman Simulate requests for testing
  • Having a relational database MySQL 5.7
  • Have navicat Yes MySQL Conduct management

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 ) Is a software architecture style 、 Design style , Not the standard , It just provides a set of design principles and constraints . It is mainly used for the software of interaction between client and server . Software designed based on this style can be more concise , More layers , It is easier to implement caching and other mechanisms .

It first appeared in 2000 year Roy Thomas Fielding In his doctoral thesis , This paper defines and describes in detail the expressive state transition (Representational State Transfer,REST) Architectural style , And described 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 、 Good performance 、 Architecture suitable for communication .

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

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 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 a network, such as a 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 、 Modification and deletion , These operations correspond to HTTP Provided by agreement 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 exactly what's going on. You need to learn from it HTTP On the method of request type judgment . Concrete HTTP The meaning of method and method is as follows :

  • GET(SELECT): Get resources from the server ( One or more ).
  • POST(CREATE): Create a new resource on the server .
  • PUT(UPDATE): Update resources on the server ( The client provides complete resource data ).
  • PATCH(UPDATE): Update resources on the server ( The client provides the resource data that needs 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 traditional API The general structure is as follows :
image-20201204001311359

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 Corresponding , But a URI Point to only one resource .

No state : The server cannot save the client's information , Every time a request is sent from the client , Include all the necessary status information , Session information is saved by the client , The server processes the request according to the status information . When the client can switch to a new state, send the request information , 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 individual Limiting conditions , It can also be called RESTful 6 Great principles , The 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 .

No state (Stateless): The server does not save the client state , The client saves the status information and carries the status information every time it requests .

Cacheability (Cacheability) : The server needs to reply whether it can be cached so that the client can identify whether it is cached and improve the efficiency .

Unified interface (Uniform Interface): Design the interface by certain principles to reduce coupling , Simplify system architecture , This is a 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 .

Layered system (Layered System): The client can not directly know whether it is connected 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 Specific introduction .

Two 、RESTful API design code

Now that I understand RESTful Some of the rules and features of , So how to design a RESTful API Well ? From you to URL route 、HTTP Request a verb 、 The status code and return results are considered in detail . As for other aspects, such as error handling 、 Filtering information and other specifications will not be introduced in detail here .

URL design code

URL For unified resource locator , The interface belongs to the server resource , First pass 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: Path to access resources , Is a variety of web As defined in the framework route route
query: Query string , Is the parameter sent to the server , More paging of sending data here 、 Sorting and other parameters .
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 , By controlling the version number, it is easy to apply iteration .
resources: resources ,RESTful API The plural form of lower case English words is recommended .
resource_id: 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 , about 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. Hyphen with 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 a file extension

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 new resources 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 Mode request , Update and insert are generally used POST request . 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 It is required to be in 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 must 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 Idempotency 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 it, a new result appears
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 the 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 states 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]: User created or modified 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 does not create or modify data , The operation is idempotent .
401 Unauthorized - [*]: Indicates that the user does not have permission ( token 、 user name 、 Wrong password ).
403 Forbidden - [*] Indicates that the user is authorized ( And 401 Error relative ), 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]: Format requested by user is not available ( Such as user request JSON Format , But only XML Format ).
410 Gone -[GET]: User requested resource is permanently deleted , And it won't come back .
422 Unprocesable entity - [POST/PUT/PATCH] When creating an object , A validation error occurred .
500 INTERNAL SERVER ERROR - [*]: Server error , The user will not be able to determine whether the request was successful .

Return results

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 !

get set

In the actual combat of this case , We visited RESTful Interfaces are real operations on the database , New database , Create a database and table ( According to one's own preference ).

choice Maven When we depend , Just check it Spring Of Web modular 、MySQL Drive and MyBatis frame .

In this case POJO establish Dog.java Entity object , Its concrete structure is :

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 the 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 standard , For example, the version number and other information will not be added here , The case focuses more on the use of SpringBoot Implement this interface .

This case realizes to dog Add, delete, modify and search resources , The following is true and false RESTful and RESTful Interface comparison :

API name Not RESTful RESTful
obtain 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 sending a request , There are three common file types passed to the back end :

 Insert picture description here
form-data : Namely form In the form multipart/form-data, Will process the form data as a piece of information , Separate pieces of information with specific tags , And this file type is usually used to upload binary files .

x-www-form-urlencoded: Namely application/x-www-form-urlencoded, yes form The form defaults to encType,form The form will convert the data in the form into key value pairs , This format cannot upload files .

raw: You can upload text in any format , 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 parameters are in URL On , Other types of requests use x-www-form-urlencoded Mode to transfer value to the back end .

GET POST PUT DELETE request

GET Requests are used to get resources :GET The request will send a request for data to the database , In order to get resources , The request is like a database of select Same operation , It's just for querying data , It doesn't affect the content of the resource . No matter how many operations , The results are the same .

also GET The request will attach the parameters of the request to URL Back , But different browsers have different size and length restrictions .

In this case , We designed two GET Requested API.
GET /dogs : Used to return 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 Same operation , Will create new content . And POST The request parameters of the request are all in the request body , 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 request is different ,PUT Requests focus on data modification , It's like in the database update equally , and POST Requests focus on the addition of data .

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 Corresponding .

In this case , We design the following DELETE Requested API.
DELETE /dogs/{dogid} : Used to delete this id The individual dog resources .

Corresponding Mapper File for :

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<Dog> 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);
}

Corresponding controller File for :

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<Dog> 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 tests, everything is ok Of , If you want the project source file, please contact the author to send you ha !

summary

RESTful Style API Of course, it's very good and standard , But most Internet companies don't design by their rules or by their rules , because REST It's a style , It's not a constraint or a rule , Too idealistic RESTful API It will cost too much .

such as RESTful API There are also some disadvantages

  • For example, the operation is complicated ,RESTful API Usually according to GET、POST、PUT、DELETE To distinguish the actions that operate resources , and HTTP Method It can't be seen directly in itself , It's hidden , And if you put the action in URL Of path On the contrary, it is clear that , More conducive to team understanding and communication .
  • And some browsers are right for GET,POST It's not very friendly to ask for support , Special extra handling is needed .
  • Over emphasis on resources , And the actual business API There may be complex requirements , The use of resources alone may not meet the needs , Force to use RESTful style API It will only increase the difficulty and cost of development .

therefore , When you or your technical team are designing API When , If you use scenarios and REST The style matches , So you can use RESTful style API. But if RESTful style API It doesn't match or is troublesome , You don't have to RESTful style API Or we can learn from , After all, whatever the style API All for the convenience of team development 、 Negotiation and management , Don't stick to the rules .
 Insert picture description here
Come here RESTful API The introduction and actual combat are over , This article starts with RESTful Some of the characteristics of , Until then SpringBoot actual combat RESTful API, Finally, I also said some RESTful API It's not perfect , I believe you are wise to RESTful There must be a deep understanding . In future projects API There must be some optimization in design .

Different people are right RESTful API There may be different understandings , But existence is reasonable ,RESTful API It has distinct advantages , At present, it is also a kind of API One of the main types of design , So master and understand RESTful API It's still quite important !
 Insert picture description here

Originality is not easy. ,bigsai I'd like you to help me with two things :

  1. give the thumbs-up support , Your affirmation is the source of my creation .
  2. WeChat search 「bigsai」, Follow my public number ( New people ask for support ), It will be the first time to share knowledge and technology in official account . You can punch in together LeetCode.

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