Day 3: RESTful service + Swagger

Introduction to RESTful

Overview

RESTful is currently a popular Internet software service architecture design style . REST (Representational State Transfer) defines the architectural principles of Internet software services. If an architecture conforms to the REST principles, it is called a RESTful architecture.
RESTful is not a standard, but more like a set of architectural concepts and design principles for the interaction between clients and servers. Web APIs based on this architectural concept and design principles are more concise, more layered, and more readable.

Features of RESTful

  • Each URI (each link) represents a resource.
  • The client uses GET, POST, PUT, and DELETE to operate on the server resources: GET is used to obtain resources, POST is used to create new resources (it can also be used to update resources), PUT is used to update resources, and DELETE is used to delete resources. (RESTful advocates using different request methods to express different operations, which is more readable)
  • Various request operations on the server side are realized by manipulating the manifestation of resources (that is, the above-mentioned request method).
  • The representation of the resource is JSON or HTML.
  • The interaction between the client and the server is stateless between requests, and each request from the client to the server contains the required information.

RESTful API

A Web API that conforms to the RESTful specification needs to have the following two key features:
Security : A safe method is expected to have no side effects. When we use the GET operation to obtain a resource, it will not cause changes to the resource itself, nor will it cause changes to the state of the server.
Idempotency : The idempotent method ensures that repeated requests have the same effect as one request (it does not mean that the response is always the same, but that the state of the resources on the server does not change after the first request). Mathematically, idempotence means that N transformations are the same as one transformation.

HTTP Method

HTTP provides operation types such as GET, POST, PUT, and DELETE to perform Create, Read, Update, and Delete operations on a web resource.
In addition to using the URI to mark the target resource, an HTTP request also needs to specify the type of operation for the resource through the HTTP Method, some common HTTP methods and their use in the RESTful style:
insert image description here

HTTP status code

The HTTP status code is the status code and prompt information returned by the server to the user. For each request from the client, the server must respond. The response includes two parts: the HTTP status code and the data.
HTTP defines 40 standard status codes that can be used to communicate the result of a client request. Status codes are divided into the following 5 categories:

  • 1xx: information, communication transmission protocol level information
  • 2xx: Success, indicating that the client's request has been successfully accepted
  • 3xx: Redirect, indicating that the client must perform some additional action to complete its request
  • 4xx: client error, this type of error status code points to the client
  • 5xx: Server error, the server is responsible for these error status codes

The HTTP status code is used in the RESTful API to indicate the status of the request execution result, which is applicable to the code designed for the RESTful API and the corresponding HTTP method.
insert image description here

SpringBoot implements RESTful API

The spring-boot-starter-web component provided by SpringBoot fully supports the development of RESTful API, and provides annotations corresponding to REST operation methods (GET, POST, PUT, DELETE) (of course, it can also be implemented using RequestMapping).

  • @GetMapping: Handle GET requests and get resources.
  • @PostMapping: Process POST requests and add resources.
  • @PutMapping: Process PUT requests and update all resources.
  • @DeleteMapping: Handle DELETE requests and delete resources.
  • @PatchMapping: Handle PATCH requests to update some resources.

In the RESTful architecture, each URL represents a resource, so it is recommended not to include verbs in the URI, but only nouns, and all nouns often correspond to the table names of the database.
Example of user management template API:
insert image description here

Example usage scenarios:

删除用户:
传统设计方案:get http://localhost/del?id=10
REST设计方案:delete http://localhost/user/10 (路径是动态变化的)

Code example:

@RestController
public class UserController {
    
    

    @GetMapping("/user/{id}")
    public String getUserById(@PathVariable int id){
    
    
        System.out.println(id);
        return "根据ID获取用户信息";
    }

    @PostMapping("/user")
    public String save(User user){
    
    
        return "添加用户";
    }

    @PutMapping("/user")
    public String update(User user){
    
    
        return "更新用户";
    }

    @DeleteMapping("/user/{id}")
    public String deleteById(@PathVariable int id){
    
    
        System.out.println(id);
        return "根据ID删除用户";
    }
}

Build a RESTful application interface

Generate Web API documentation using Swagger

What is Swagger

Swagger is a standardized and complete framework for generating, describing, invoking and visualizing RESTful-style Web services, and is a very popular API expression tool.
Swagger can automatically generate complete RESTful API documents, and at the same time update them synchronously according to the modification of the background code, and provide a complete test page to debug the API.
Swagger is very conducive to large-scale software developed by multi-person collaboration and improves development efficiency.

Generate Web API documentation using Swagger

Adding dependencies
It is very simple to integrate Swagger in the SpringBoot project, just introduce springfox-swagger2 and springfox-swagger-ui dependencies in the project.

<!--        添加Swagger2相关功能-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
<!--        添加Swagger-ui相关功能-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

Add configuration class SwaggerConfig.java

@Configuration    //告诉Spring容器,这个类是一个配置类
@EnableSwagger2   //启用Swagger2功能
public class SwaggerConfig {
    
    
    //配置Swagger2相关的bean
    @Bean
    public Docket createRestApi(){
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com"))   //com包下所有的API都交给Swagger2管理
                .paths(PathSelectors.any()).build();
    }

    //API文档页面显示信息
    private ApiInfo apiInfo(){
    
    
        return new ApiInfoBuilder()
                .title("演示项目API")   //标题
                .description("演示项目")  //描述
                .version("1.0")   //版本
                .build();
    }
}

Use Swagger2 for interface testing
Start the project and visit http://127.0.0.1:8080/swagger-ui.html to open the automatically generated visual test page. It is very convenient to use Swagger2 for project development. You don't need to use tools such as apiPost or postman to perform interface testing, and you can do it directly on the swagger-ui.html page.
insert image description here
insert image description here
insert image description here

insert image description here
insert image description here
Swagger common annotations
Swagger provides a series of annotations to describe interface information, including interface description, request method, request parameters, return information, etc.
insert image description here
Example usage:
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weixin_46443403/article/details/128895118