RESTful style (detailed introduction + case implementation)

Posted by kumar_ldh on Sun, 20 Feb 2022 17:47:41 +0100

If you are Xiaobai, this set of information can help you become a big bull. If you have rich development experience, this set of information can help you break through the bottleneck
2022web full set of video tutorial front-end architecture H5 vue node applet Video + data + code + interview questions.

Write the catalog title here

Getting started with RESTful

1, What is API (application program interface)

  1. concept

    API, full English name of Application Programming Interface, translated as "Application Programming Interface". It is to encapsulate some functions (logic) into components in order to provide an application program interface for other programs and developers to access, and these visitors can use it directly without accessing the source code and understanding the internal working principle.

  2. give an example

    In the WEB project, application A exposes A request mapping method, and application B obtains the corresponding function (the function given by the request mapping method) by calling the request mapping method

2, Comparison between traditional mode and front and rear end separation mode

1. Traditional development mode

In the application of traditional development mode, the front end writes a static html page and gives it to the back-end development, and the back-end renders or redirects the html to the front-end interface. In this way, the effects seen on the front-end pages are controlled by the back-end, that is, the back-end needs to control the display of the front-end, which will lead to many serious problems.

  • malpractice

[1] The front and rear ends are seriously coupled, and the front end will embed the back-end code, resulting in code confusion and poor maintainability;

[2] The developed software has slow response speed, poor quality and poor user reflection;

[3] Developers need to give consideration to both front and rear ends, resulting in low development efficiency and longer development cycle;

[4] The communication cost with front-end developers is high, and the development progress of front-end and back-end affects each other, which greatly reduces the development efficiency.

2. Front and rear end separation mode

The separation of front end and back end is not only a development mode, but also an architecture mode of web application. In the development stage, the front and rear end personnel agree on the data interaction interface, which can be developed and tested in parallel.

After the front-end development is completed, mock testing can be carried out alone, and the back-end can also be tested with interface testing tools such as postman. Finally, the function joint commissioning test can be carried out.

The popular point is that there is no page (JSP|HTML) in the back-end project. The back-end provides an interface to the front-end, and the front-end calls the REST style interface provided by the back-end. The front-end focuses on writing pages (html|jsp) and rendering (JS|CSS | various front-end frameworks); Just focus on writing code at the back end. The core of front and back end separation: the background provides data and the front end is responsible for display

  • advantage

[1] It can realize the real front and rear end decoupling, and the front and rear ends can be developed and tested in parallel to improve the development efficiency;

[2] Reduce the concurrency / load pressure of the back-end server and improve the performance of the system;

[3] Asynchronous loading method can well deal with complex and changeable front-end requirements;

[4] The front and back end code is no longer confused, which enhances the maintainability of the code.

3, RESTful style

1. Concept

RESTFUL is a design style and development method of network application. It is based on HTTP and can be defined in XML format or JSON format. The most commonly used data format is JSON. Because JSON can be read directly by JavaScript, the REST style API using JSON format is simple, easy to read and easy to use.

2. Resources

REST is resource oriented, and each resource has a unique resource locator (URI). Each URI represents a resource, so there can be no verbs but only nouns in the URI, and the nouns often correspond to the table name of the database. Generally speaking, tables in a database are "collection s" of the same kind of records, so nouns in URIs should also be plural.

For example:

// Query all employees
@RequestMapping(value = "/employees", method = RequestMethod.GET)
@ResponseBody
public List<Employee> list() {
    ...
}

3. Request method

Request mode

meaning

GET(SELECT)

Remove resources (one or more) from the server

POST(CREATE)

Create a new resource on the server

PUT(UPDATE)

Update resource on server (update full resource)

PATCH(UPDATE)

When updating resources on the server, PATCH updates individual attributes

DELETE(DELETE)

Delete resource from server

4. Comparison between traditional pattern URI and RESTful style

[1] Inquiry

query

tradition

REST

REST background reception

Query all

http://localhost:8080/employee/list

http://localhost:8080/employees

@RequestMapping(value = "/employees", method = RequestMethod.GET)

Query single

http://localhost:8080/employee/listid=1

http://localhost:8080/employees/1

@RequestMapping(value = "/employees/{id}", method = RequestMethod.GET)
@ResponseBody
public Employee queryById(@PathVariable Long id) {}

[2] Add

add to

tradition

REST

REST background reception

add to

http://localhost:8080/employee/add

http://localhost:8080/employees

@RequestMapping(value = "/employees", method = RequestMethod.POST)
public Employee add(@ModelAttribute("emp") Employee employee) {}

[3] Modification

modify

tradition

REST

REST background reception

modify

http://localhost:8080/employee/update

http://localhost:8080/employees

@RequestMapping(value = "/employees", method = RequestMethod.PUT)
public Employee update(@ModelAttribute("emp") Employee employee) {}

[4] Delete

query

tradition

REST

REST background reception

delete

http://localhost:8080/employee/delete

http://localhost:8080//employees/{id}

@RequestMapping(value = "/employees/{id}", method = RequestMethod.DELETE)
@ResponseBody
public JsonResult delete(@PathVariable Long id) {}

be careful:
[1] When there are many parameters, the parameter path method is not recommended;
[2] If the parameter name is very sensitive, it is recommended to use the parameter path method, which can hide the parameter name.

5. Return value - determined by demand

GET /collection: returns a list (array) of resource objects
GET /collection/resource: returns a single resource object
POST /collection: returns the newly generated resource object
PUT /collection/resource: returns the complete resource object
PATCH /collection/resource: returns the complete resource object
DELETE /collection/resource: returns an empty document

6. HTTP response status code

Status code

meaning

200 OK - [GET]

The server successfully returned the data requested by the user

201 CREATED - [POST/PUT/PATCH]

User successfully created or modified data

202 Accepted

Indicates that a request has entered the background queue (asynchronous task)

204 NO CONTENT - [DELETE]

User deleted data successfully

400 INVALID REQUEST - [POST/PUT/PATCH]

There is an error in the request sent by the user. The server does not create or modify data. The operation is idempotent

401 Unauthorized - [*]

Indicates that the user does not have permission (wrong token, user name and password)

403 Forbidden - [*]

Indicates that the user is authorized (as opposed to 401 error), but access is prohibited

404 NOT FOUND - [*]

The request sent by the user is for a nonexistent record. The server does not operate. The operation is idempotent

405 Method Not Allowed

Method is not allowed. The server does not have this method

406 Not Acceptable - [GET]

The format of the user request is not available (for example, the user requests JSON format, but only XML format)

410 Gone -[GET]

The resource requested by the user is permanently deleted and will no longer be available

422 Unprocesable entity - [POST/PUT/PATCH]

A validation error occurred while creating an object

500 INTERNAL SERVER ERROR - [*]

If an error occurs in the server, the user will not be able to judge whether the request is successful

7. The same resource has multiple forms (xml,json, etc.)

For example, text can be expressed in txt format, HTML format, XML format, JSON format, or even binary format; Pictures can be expressed in JPG format or PNG format.

Its specific expression form should be specified in the header information of HTTP request with Accept and content type fields, which are the description of "expression".

accept:application/json
content-type:application/json

  • The difference between Accept and content type

    [1] Accept belongs to the request header and content type belongs to the entity header.
    Http header is divided into general header, request header, response header and entity header.
    http header structure of the requester: General header | request header | entity header
    http header structure of the responder: General header | response header | entity header

    [2] Accept represents the data type that the sender (client) wants to accept.
    For example: Accept: application/json;
    It means that the data type that the client wants to accept is json type, and the background returns json data;

    [3] Content type represents the data type of entity data sent by the sender (client | server).
    For example: content type: application/json;
    The data format sent by the sender is json, which is used by the background to receive the data sent by the front end.

8. Use Ajax to send requests of various request methods

$.get('/employees',function(){})

$.post('/employees',params,function(){})

$.ajax({
	url:"/employees/1",
    type:"put",
    data:params
	success:function(){}
})

$.ajax({
	url:"/employees/1",
    type:"DELETE",
	success:function(){}
})
  • SpringBoot 2.2. Put request and Delete request in X do not work

    application. Configuration in properties

    spring.mvc.hiddenmethod.filter.enabled=true

  • Spring MVC does not support processing put requests by default. You need to configure filters for processing put or patch requests

    httpMethodFilter org.springframework.web.filter.HiddenHttpMethodFilter httpMethodFilter /*

delete request in spring MVC

$.ajax({
    type: "post",
    url:url,
    data: {"contentId": id, "_method": "delete"},
    success: function (data) {
        if (data.status == 0) {
            alert("success!");
            location.reload();
        } else {
            alert("Operation failed!" + data.reason);
        }
    }
});

9. Relevant notes

annotation

effect

@RestController

It consists of @ Controller + @ResponseBody (return JSON data format)

@PathVariable

The {xxx} placeholder in the URL can be bound to the formal parameter of the controller processing method through @ PathVariable("xxx")

@RequestMapping

Annotation is used for the resolution of request addresses. It is the most commonly used annotation

@GetMapping

Query request

@PostMapping

Add request

@PutMapping

Update request

@DeleteMapping

Delete request

@RequestParam

Bind the request parameters to the method parameters of your controller (which is the annotation of spring MVC to receive common parameters)

@RequestParam syntax

Syntax:@RequestParam(value="Parameter name,required="true/false",defaultValue="")
 
value: Parameter name
 
required: Whether to include this parameter. The default value is true,Indicates that the parameter must be included in the request path. If it is not included, an error will be reported.
 
defaultValue: Default parameter value. If this value is set, required=true Will fail, automatically false,If this parameter is not passed, the default value will be used

10. Properties of requestmapping tag

  1. value/path: mapping path;

  2. Method: defines the method of the request. Enumeration:
    public enum RequestMethod {
    GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
    }

  3. params: defines the parameters of the request to be processed. Only the request matching this parameter can be processed by this method;

    @GetMapping(value = "list",params="version=1")  
    public Object list() {
        return "ok";  
    }  
    
  4. headers: defines the request header information of the request to be processed. Only the request matching the content of the request header can be processed by this method;
    @GetMapping(value = "/test", headers = "content-type=text/*")

4, Examples

1. Front end interface

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../js/jquery.min.js"></script>
    <script>
        $(function () {
            // Query all
            $('#btn1').click(function () {
                $.get('/employees', function (data) {
                    console.log(data);
                });
            });

            // Query one
            $('#btn2').click(function () {
                $.get('/employees/10', function (data) {
                    console.log(data);
                });
            });

            // add to
            $('#btn3').click(function () {
                $.post('/employees', "id=11", function (data) {
                    console.log(data);
                });
            });

            // modify
            $('#btn4').click(function () {
                $.ajax({
                    url: "/employees",
                    type: "PUT",
                    data: {id: 1, name: "Little fat sheep", age: 10},
                    success: function (data) {
                        console.log(data);
                    }
                });
            });

            // delete
            $('#btn5').click(function () {
                $.ajax({
                    url: "/employees/13",
                    type: "DELETE",
                    data: {id: 1},
                    success: function (data) {
                        console.log(data);
                    }
                });
            });

        });
    </script>
</head>
<body>
<button id="btn1">Query all</button>
<button id="btn2">Query one</button>
<button id="btn3">add to</button>
<button id="btn4">modify</button>
<button id="btn5">delete</button>
</body>
</html>

2. Controller

package com.yy.web.controller;

import com.yy.domain.Employee;
import com.yy.util.JsonResult;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @program: restful-demo
 * @ClassName: EmployeeController
 * @description:
 * @author: YanYang
 * @create: 2021-06-23 15:04
 **/
@RestController
@RequestMapping("employees")
public class EmployeeController {
    /**
     * 2 Both interfaces are designed with the same resources and the same request methods. At this time, spring MVC cannot recognize them,
     * If it is considered to be the same method, an error is reported: Ambiguous mapping [fuzzy mapping]
     *
     * RESTful Solution: use parameter path mode
     *      Specific implementation: take the parameters as part of the request mapping path, [participate in the mapping path differentiation]
     *      For example, the interface design for querying the employee information of the specified id
     *      @RequestMapping(value = "/employees/{id}", method = RequestMethod.GET)
     *      Where "/ employees/{id}" is the path parameter and {id} is the path parameter
     *
     *      When accessing this interface: http:localhost:8080/employees/1, where 1 is the id parameter
     *      Interface receiving path parameters: use @ PathVariable to resolve the parameters on the parameter path and assign values to the specified variables
     *      If the path parameter is inconsistent with the variable name, use @ PathVariable("eid") to specify it explicitly
     *
     */
    // Query all (data is simulated)
//    @RequestMapping(value = "/employees", method = RequestMethod.GET)
    @GetMapping
    public List<Employee> list() {
        return Arrays.asList(new Employee(1L,"Little fat sheep", 10), new Employee(2L, "Xiong Da", 11));
    }

    // Query single (data is simulated)
//    @RequestMapping(value = "/employees/{id}", method = RequestMethod.GET)
    @GetMapping("/{eid}")
    public Employee queryById(@PathVariable("eid") Long id) {
        System.out.println("Query single = " + id);
        return new Employee(3L, "Xiong er", 8);
    }

    // Add (data is simulated)
//    @RequestMapping(value = "/employees", method = RequestMethod.POST)
    @PostMapping
    public Employee add(@ModelAttribute("employee") Employee employee) {
        System.out.println("add to = " + employee.getId());
        return employee;
    }

    // Modification (data is simulated)
//    @RequestMapping(value = "/employees", method = RequestMethod.PUT)
    @PutMapping
    public Employee update(@ModelAttribute("employee") Employee employee) {
        System.out.println("modify = " + employee.getId());
        employee.setId(employee.getId());
        employee.setName(employee.getName());
        employee.setAge(employee.getAge());
        return employee;
    }

    // Delete (data is simulated)
//    @RequestMapping(value = "/employees/{id}", method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Long id) {
        System.out.println("delete = " + id);
        if (id != null && 1 == id) {
            return "Deleted successfully";
        }
        return "Delete failed";
    }
}

3. Output results

  • console output

    Query single = 10
    Add = 11
    Modification = 1
    Delete = 13

  • Browser printing

Topics: Java Front-end html Back-end Interview