Detailed straightaway RESTful API Practice (including code)

Source: click here

Click on the link above, better layout

 

First, what is RESTful

        REST is resource-oriented, the concept is very important, and the resource is exposed through the URI, URI design as long as the charge of the resources exposed by a reasonable way out of it, the operation of resources nothing to do with it, the operation is to reflect over HTTP verbs. So when the URI exposed through REST resources, it will emphasize the verb do not appear in the URI, but rather a kind of resources only provide a url, to specify the operation to be performed by the GET, POST, PUT, DELETE request.

       (Verb exist in multiple url and url) non-RESTful usage

    http://127.0.0.1/order/query/1 GET query orders based on the order id
    new orders POST http://127.0.0.1/order/save
    HTTP: //127.0.0.1/order/update POST modify the order information
    http://127.0.0.1/order/delete GET / POST delete order information

       RESTful usage (same url, specific operation is specified by the HTTP request method)

    HTTP: / /127.0.0.1/order/1 GET query orders based on the order id
    orders http://127.0.0.1/order POST new
    http://127.0.0.1/order PUT modify the order information
    http://127.0.0.1/order dELETE to delete the order information

        REST good use of some features of HTTP itself, such as HTTP verbs, HTTP status codes, HTTP headers, and so on.
        REST API is based on HTTP, so you should go to the API to use some of the standard HTTP. So that all HTTP clients (such as browsers) to be able to directly understand your API.

        REST return value is a standard, and we do not define individual packages the status code returned, but the use of direct HTTP status code, the non-return RESTful example:

    {
      "code": "0",
      "MSG": "success"
    }

    {
      "code": "1",
      "msg": "failed"
    }

        in this way they want us to resolve themselves, but also the front and rear ends to negotiate your return 0 what do you mean.
Second, the key RESTful

        key RESTful is to define the object may represent process elements / resources. In REST, each object is represented by a URL, the user is responsible for the objects packed into the status information of each message to be processed is always stateless. Before and after the end of the separation project is basically stateless, we are often judged by the signature of the current request is legitimate.

        The so-called stateless, that is, all the resources are available through a URI, and this has nothing to do with locating other resources, other resources will not change because of change.

        Here is a simple example to explain state and non-state differences, such as a query staff wages, wages are needed if the query log in, enter the page inquiry wages, implementation of the relevant steps to obtain the wages, then this case is stateful, because every step of the wage query operations are dependent on the previous step of the operation, as long as the pre-operation is not successful, subsequent operations can not be executed; if you enter a url to get the specified wage employees, then this case is stateless , as access to pay does not depend on other resources or state, and in this case, a resource is wages, url corresponds thereto by one, the resource can be obtained by the HTTP GET method, which is a typical RESTful style.

Three, RESTful API code examples

    Package com.ldy.sboot.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.ldy.sboot.demo.entity.OrderEntity;
    import com.ldy.sboot.demo.service.OrderService;
     
    @RequestMapping("restful/order")
    @RestController
    public class OrderController {
     
        @Autowired
        private OrderService orderService;
     
        /**
         * @描述: 根据ID查询<br>
         * @param id
         * @return
         */
        @GetMapping(value = "{id}")
        //@RequestMapping(method = RequestMethod.GET)
        public ResponseEntity<OrderEntity> queryOrderById(@PathVariable("id") Long id) {
            try {
                OrderEntity entity = orderService.queryOrderById(id);
                if (null == entity) {
                    // 资源不存在,响应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);
        }
     
        /**
         * @描述: 新增<br>
         * @param entity
         * @return
         */
        @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);
        }
     
        /**
         * @描述: 修改<br>
         * @param entity
         * @return
         */
        @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);
        }
     
        /**
         * @描述: 删除<br>
         * @param id
         * @return
         */
        @DeleteMapping
        //@RequestMapping(method = RequestMethod.DELETE)
        public ResponseEntity<Void> deleteOrder(@RequestParam(value = "id") Long id) {
            try {
                OrderEntity entity = orderService.queryOrderById(id);
                if (null == entity) {
                    // 不存在返回404
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
                }
                orderService.deleteOrderById (ID);
                // 204
                return ResponseEntity.status (HttpStatus.NO_CONTENT) .build ();
            } the catch (Exception E) {
                e.printStackTrace ();
            }
            // 500
            return ResponseEntity.status (HttpStatus.INTERNAL_SERVER_ERROR) .body (null);
        }
    }
     

four, HTTP status code Description
status code status code Description Chinese English name
beginning a status code
100 continue continue. The client should continue its request
101 Switching Protocols Switching protocols. The protocol server switching request from a client. Only to switch to higher-level protocols, such as switching to a new version of the HTTP protocol
at the beginning of 2 status code
200 OK request succeeded. GET and POST requests are generally used for
201 Created been created. Request and successfully created a new resource
202 Accepted Accepted. We have accepted the request, but is processed
203 Non-Authoritative Information unauthorized information. Request was successful. But returned meta information not in the original server, but a copy of the
204 No Content empty. The server successfully processed, but did not return content. In the case of a web page is not updated, you can ensure that the browser continues to display the current document
205 Reset Content Reset content. Server processing is successful, the user terminal (for example: a browser) should reset the document view. This return code can clear the browser's form fields
206 Partial Content part. Server successfully processed a partial GET request
at the beginning of the status code 3
300 Multiple Choices choice. Resource request may include a plurality of positions, a list of the corresponding return address and resource for a user terminal (e.g.: Browser) select
301 Moved Permanently Moved Permanently. The requested resource has been permanently moved to a new URI, return information will include new URI, the browser will automatically be directed to the new URI. Any future new request should use the new URI instead of
302 Found temporary move. Similar to the 301. But the resource only temporarily moved. The client should continue to use the original URI of the
303 See Other View other addresses. Similar to the 301. Use GET and POST requests to view
304 Not Modified unmodified. When the requested resource is not modified, the server returns this status code does not return any resources. The client typically caches resource visited by a header information indicates that the client wishes to return only resources modified after the specified date
305 Use Proxy to use a proxy. Requested resource must be accessed through a proxy
code 306 Unused has been abandoned HTTP status
307 Temporary Redirect temporary redirection. Similar to the 302. Use a GET request to redirect
the beginning of the 4 status code
syntax error 400 Bad Request client requests, the server can not understand
401 Unauthorized request requires user authentication
402 Payment Required reserves for future use
403 Forbidden The server understood the request to the client's request, but is refusing to perform this request
404 not found the server can not find the resources (web) at the request of the client. By this code, web designers can set "you have requested resources can not be found" personalized page
method 405 Method Not Allowed client request is prohibited
406 Not Acceptable The server was unable to complete based on the content characteristics requested by the client request
407 Proxy Authentication required request requires authentication agent, and 401 are similar, but the agent should be used to authorize the requestor
408 request time-out server waits for a request sent by the client is too long, the timeout
409 Conflict PUT requests the server to complete the client may return this code There was a clash when the server processes the request
410 Gone client requested resource does not exist. Unlike 410 404, if the resource has previously been permanently removed now available 410 codes, the website designer can specify the resource by the code 301 the new location
request information without the Content-Length 411 Length Required server can not process client sent
412 precondition Failed prerequisites for client requests information error
413 request entity too large Since the request is too large for the server to process, and therefore reject the request. In order to prevent continuous request of the client, the server may close the connection. If only temporarily unable to process the server, a response message will contain the Retry-After
414 Request-URI URI is too long (URI typically a URL) Too Large request, the server can not handle
415 Unsupported Media Type server can not handle the request comes media format
invalid 416 requested range not satisfiable client requests range
417 Expectation Failed the server can not satisfy the request header Expect the
beginning of the 5 status code
500 internal server error server internal error and can not fulfill the request
501 not Implemented the server does not support the requested function could not be completed request
502 Bad gateway acting as a gateway or proxy server, it is received from the remote server to request an invalid
503 Service Unavailable due to an overload or system maintenance, the server is temporarily unable to handle the client's request. The length of the delay may be included in the server in the Retry-After header
504 Gateway Time-out as a gateway or proxy server, not timely acquisition request from a remote server
505 HTTP Version not supported server does not support the version of the HTTP protocol request, not complete treatment

recommendation document: HTTPS: //blog.igevin.info/posts/restful-architecture-in-general/
----------------
Disclaimer: This article is CSDN blogger "Yi Yu Zi" in the original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/LDY1016/article/details/85112631

Guess you like

Origin www.cnblogs.com/asplover/p/12236512.html