当前位置:网站首页>Restful style

Restful style

2022-07-06 03:15:00 Zyyyyu_

RESTful style

What is? Api( Interface )

Api The full name is Application Programming Interface, That's the API , It encapsulates the functions we write into components , The purpose is to provide an application program interface for other program calls or other developers to access , And the calling developer does not need to access the source code and understand the internal logic and working principle , You can use this function directly .


Fore and aft end separation

In front and back separation mode , Front end developers need to call the interface provided by back-end developers , according to Api Document to call ,Api Documents can be accessed through Swagger Generate .
Front end separation is not just a development model , It is also a kind of Web Applied architectural patterns , Before development , The front and back-end personnel will first agree on the data interaction interface , Then develop in parallel , There will be no situation that one party needs to wait for the other party to complete the development before continuing the development .
There will be no page in the back-end project , Only responsible for providing interfaces to the front end , The front end only needs to concentrate on writing and rendering pages , Data call is provided by the backend REST Style interface is OK .
The front and rear separated cores : The front end is responsible for displaying , The back end is responsible for providing data , Mutual interference .


RESTful style

  1. Concept
    RESTFUL It is a kind of design style and development method of network application program , be based on HTTP, have access to XML Format definition or JSON Format definition . The most common data format is JSON. because JSON Can be directly by JavaScript Read , therefore , Use JSON Format REST Style API Simple 、 Easy to read 、 Easy to use features .
    REST It's not about technology , Represents a software architecture style ,REST yes Representational State Transfer For short , Chinese translation for “ Characterization state transfer ” or “ Represent layer state transformation ”.
  2. resources
    REST It's resource oriented , Each resource has a unique resource locator (URI). Every URI Represents a resource (resource), therefore URI There can be no verbs in , Only nouns , And the nouns used often correspond to the table name of the database . Generally speaking , The tables in the database are the same kind of records " aggregate "(collection), therefore URI The nouns in should also use the plural .
  3. Request mode
Request mode meaning
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 ( Update full resources )
PATCH(UPDATE) Update resources on the server , PATCH Update individual properties
DELETE(DELETE) Remove resources from server
  1. And non REST Design comparison
  • Not Rest Design , We used to write like this :
    http://localhost:8080/admin/getUser ( Query the user )
    http://localhost:8080/admin/addUser ( New users )
    http://localhost:8080/admin/updateUser ( Update user )
    http://localhost:8080/admin/deleteUser ( Delete user )
    summary : In different ways URL( It's mainly the use of verbs ) Do different things .

  • Rest framework :
    GET http://localhost:8080/admin/user ( Query the user )
    POST http://localhost:8080/admin/user ( New users )
    PUT http://localhost:8080/admin/user ( Update user )
    DELETE http://localhost:8080/admin/user ( Delete user )
    summary :URL Only specify resources , With HTTP Method verbs do different operations . use HTTP STATUS/CODE Define the operation result .

  1. domain name
    use api Keyword to identify the interface url
    https://api.example.com
    https://example.org/api/
    notes : notice api The word , On behalf of the request url The link is to complete the data interaction between the front and back stations

  2. edition

  • Put the version information in URL in , Such as :
    https://api.example.com/v1/
    https://api.example.com/v2/

v1,v2 Represents the withdrawal of different data versions , The premise is that a data resource has multiple versions

  • Put the version information in the request header .
  1. url route
  • See everything on the Internet as a resource , All use nouns ( It's usually in the plural )
    https://api.example.com/v1/zoos
    https://api.example.com/v1/animals
    https://api.example.com/v1/employees
  • stay url Do not appear verbs that operate resources in the link
    Error model :https://api.baidu.com/delete-user
  • A special interface can have Verbs , Because these interfaces generally do not have a clear resource , Or the verb is the core meaning of the interface
    https://api.baidu.com/place/search
    https://api.baidu.com/login
  1. method Request mode
    GET : Get resources from the server ( One or more )
    POST : Create a new resource on the server
    PUT : Update resources on the server ( The client provides complete resources after the change )
    PATCH : Update resources on the server ( Client provides changed properties )
    DELETE : Remove resources from server

  2. Filter
    By means of url Pass search terms in the form of upload parameters
    https://api.example.com/v1/zoos?limit=10: Specify the number of returned records
    https://api.example.com/v1/zoos?offset=10: Specify where to start the return record
    https://api.example.com/v1/zoos?page=2&per_page=100: Specify page , And the number of records per page
    https://api.example.com/v1/zoos?sortby=name&order=asc: Specifies which attribute to sort the returned results by , And sort order
    https://api.example.com/v1/zoos?animal_type_id=1: Specify filter criteria

  3. Status code

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 .


301: Permanent redirection 
302: Redirect temporarily 


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 .

RESTful Interface code example

package com.zy.demo.controller;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import com.zy.demo.entity.OrderEntity;
import com.zy.demo.demo.service.OrderService;
 
@RequestMapping("restful/order")
@RestController
public class OrderController {
    
 
    @Autowired
    private OrderService orderService;
    
    @GetMapping(value = "{id}")
    //@RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<OrderEntity> queryOrderById(@PathVariable("id") Long id) {
    
        try {
    
            OrderEntity entity = orderService.queryOrderById(id);
            if (null == entity) {
    
                //  Resource does not exist , Respond to 404
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            // 200
            // return ResponseEntity.status(HttpStatus.OK).body(entity);
            return ResponseEntity.ok(entity);
        } catch (Exception e) {
    
            e.printStackTrace();
        }
        // 500
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    @PostMapping
    //@RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<Void> saveOrder(OrderEntity entity) {
    
        try {
    
            orderService.saveOrder(entity);
            return ResponseEntity.status(HttpStatus.CREATED).build();
        } catch (Exception e) {
    
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 500
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
 
    @PutMapping
    //@RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<Void> updateOrder(OrderEntity entity) {
    
        try {
    
            orderService.updateOrder(entity);
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        } catch (Exception e) {
    
            e.printStackTrace();
        }
        // 500
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    @DeleteMapping
    //@RequestMapping(method = RequestMethod.DELETE)
    public ResponseEntity<Void> deleteOrder(@RequestParam(value = "id") Long id) {
    
        try {
    
            OrderEntity entity = orderService.queryOrderById(id);
            if (null == entity) {
    
                //  There is no return 404
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            orderService.deleteOrderById(id);
            // 204
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        } catch (Exception e) {
    
            e.printStackTrace();
        }
        // 500
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
}
 

summary

RESTful It's just a style of software architecture 、 Design style , Not the standard , It just provides a set of design principles and constraints , It is mainly used for client and server interaction software . The software designed based on this style can be more brief , More layers , It is easier to implement caching and other mechanisms .

Use RESful The advantage of style development is

  • Make the request path simpler
  • Pass on 、 It is more convenient to obtain parameter values , The framework automatically casts types
  • Through path variables @PathVariable The type of , Access parameters can be constrained .
  • If the parameter value does not match the definition type , The corresponding method cannot be accessed , Report errors 400 Wrong request .
  • Security , Pass parameter values directly in the request path , With slash / Separate , The parameter variable names passed to the method are not exposed .
  • Efficient , Easier implementation of caching , Make response more efficient .

RESTful Simple style , Efficient , Security , Become web service Standard configuration for development .

原网站

版权声明
本文为[Zyyyyu_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132325185923.html