Reprinted by bigsai please contact Bigsai

Articles are saved in carriage return class

preface

Before you learn RESTful style interfaces, even if you don’t know what it is, you must wonder what problems it solves. What are the application scenarios? After hearing the following description, I think you’ll understand:

At the beginning of the Internet is not completely popular, mobile terminal is not so popular, page request and concurrency is not high, at that time people’s interface requirements are not so high, some dynamic pages (JSP) can meet the vast majority of use needs.

However, with the development of the Internet and mobile devices, people’s demand for Web applications is also increasing. Due to low efficiency, the traditional dynamic page is gradually replaced by the separation of the front and back ends of HTML+JavaScript(Ajax). Besides, android, IOS, small programs and other forms of clients emerge in an endless stream, and the types of clients are diversified. The client and server need interfaces to communicate, but the standardization of interfaces becomes a problem:

Therefore, a set of interface styles that are clear in structure, conform to standards, easy to understand, easy to expand and acceptable to most people are becoming more and more important. As RESTful apis just have the above characteristics, they are gradually applied in practice and become popular.

Nowadays, RESTful is the most popular interface design specification, which is widely used in many companies. Among them, Github API design is a very standard RESTful API, you can refer to it.

In development practice, many of us may still use traditional apis for request interaction. Many of us don’t really know RESTful apis very well, and our knowledge of RESTful apis may stop at:

  • Resource-oriented
  • It’s a style
  • Interface pass parameters are separated by slash (/) instead of question mark (?) The refs.

A big mistake is not to think that a RESTful API is one that doesn’t have a query string, or one that uses a query string, or one that uses JSON transport.

This tutorial will take you through RESTful apis and use SpringBoot in action. Before implementing this case, you need to ensure that RESTful apis are on your computer

  • Have IDEA to write project code
  • Have a Postman mock request to test
  • Have a relational database MySQL 5.7
  • Navicat to manage MySQL

I. Introduction to REST

REST may involve a lot of conceptual things, so before practicing RESTful apis, you should have a systematic understanding of REST related knowledge.

The birth of the REST

REST (Representational State Transfer) is a software architecture style, a design style, rather than a standard, that provides a set of design principles and constraints. It is mainly used for client and server interaction class software. Software designed in this style can be simpler, more hierarchical, and easier to implement mechanisms such as caching.

It first appeared in Roy Thomas Fielding’s doctoral thesis in 2000, which defined and detailed the architectural style of Representational State Transfer (REST), It also describes how REST can be used to guide the design and development of modern Web architectures. In his own words:

The purpose of this article is to understand and evaluate the architecture design of network-based application software under the premise of conforming to the architecture principles, and to obtain an architecture with strong functions, good performance and suitable for communication.

It is important to note that REST does not have a specific standard, but rather a style of design, and programs or interfaces that meet this style are called RESTful(literally an adjective). So a RESTful API is an interface that meets the REST architectural style.

Dr. Fielding was pointing out that REST architecture had not received much attention for a long time, and that REST had become increasingly popular in China in recent years. Let’s start studying REST architectural features in detail.

REST architecture Features

Now that you know how REST and RESTful are related and different, it’s time to start to understand some of the constraints and rules of RESTful. RESTful is a style, not a standard, and this style has the following main characteristics:

Resource-based: A resource can be an image, music, an ENTITY in XML format, HTML format, or JSON format on the network. In addition to some binary resources, common text resources are a group of user-oriented data based on JSON (usually obtained from the database). Unified interface: Operations on resources include obtaining, creating, modifying, and deleting resources. These operations correspond to the GET, POST, PUT, and DELETE methods provided by HTTP. In other words, with RESTful interfaces, you might be able to locate its resources, but you don’t know exactly what it’s doing. You need to know exactly what it’s doing based on its HTTP request method type. Specific HTTP methods and their meanings are as follows:

  • GET (SELECT) : Retrieves one or more resources from the server.
  • POST (CREATE) : Creates a resource on the server.
  • PUT (UPDATE) : Updates resources on the server (the client provides complete resource data).
  • PATCH (UPDATE) : updates resources on the server (the client provides the resource data to be modified).
  • DELETE (DELETE) : deletes resources from the server.

Of course, there are many cases where PUT is used to indicate updates. The general architecture of RESTful apis and traditional apis is as follows:

URI refers to a Resource: URI = Universal Resource Identifier a compact string used to identify an abstract or physical Resource. Uris include urls and UrNs, which in this case are more likely to refer to urls (Uniform resource Locators). RESTful is resource-oriented, and there may be one or more URIs for each resource, but one URI points to only one resource.

Stateless: The server cannot save client information. Each request sent from the client contains all necessary status information. Session information is saved by the client, and the server processes the request based on the status information. Requests are sent when the client can switch to a new state, and when one or more requests are sent, the client is in a state transition process. Each application’s state description can be used by the client to initiate the next state change.

REST architecture constraints

In his paper, Fielding proposed six constraints on REST architecture, also known as the six RESTful Principles. Standard REST constraints should meet the following six principles:

Client-server: It focuses on the separation of Client and Server. The independent Server can better serve front-end, Android, IOS and other Client devices.

Stateless: The server does not save the client status. The client saves the status information and carries the status information with each request.

Cacheability: The server must reply whether it can be cached to allow the client to determine whether caching improves efficiency.

Uniform Interfaces: Design interfaces based on certain principles to reduce coupling and simplify system architecture. This is the basic starting point of RESTful design. Of course, this content in addition to the above characteristics mentioned part of the specific content more detailed understanding can refer to the REST paper content.

Layered System: Clients cannot directly know whether to connect to terminals or intermediate devices. Layered System allows you to deploy server projects flexibly.

On-demand Code (optional) : On-demand Code allows us the flexibility to send seemingly special Code to clients such as JavaScript Code.

Some of the styles and limitations of the REST architecture are covered here, and RESTful style apis are covered later.

RESTful API design specifications

Now that you know the rules and features of RESTful apis, how do you design a RESTful API? Think in terms of URL paths, HTTP request verbs, status codes, and return results. Other aspects of the specification such as error handling and filtering information are not covered in detail here.

URL design specification

URL is a unified resource locator, and the interface belongs to the server resource. The first thing to access is to locate the resource through the URL. Usually, a complete URL consists of the following parts:

URI = scheme "://" host  ":"  port "/" path [ "?" query ][ "#" fragment ]
Copy the code

Scheme: indicates the underlying protocols, such as HTTP, HTTPS, and FTP. Host: indicates the IP address or domain name of the server. Port: indicates the port number, which is 80 by default. Query string, for the parameters sent to the server, here more send data paging, sorting and other parameters. Fragment: Anchor point that locates resources on a page

We need to consider the PATH of URL when designing API, and RESTful has made some specifications for the path design, usually a RESTful API path composition is as follows:

/{version}/{resources}/{resource_id}
Copy the code

Version: API version number. Some version numbers can also be placed in header information. Controlling the version number facilitates application iteration. Resources: the RESTful API is recommended to use the plural of lowercase words. Resource_id: indicates the ID of a resource that can be accessed or operated on.

Of course, sometimes the resource level may be large, and many sub-resources can be subdivided under it, and the URL path can be flexibly designed, for example:

/{version}/{resources}/{resource_id}/{subresources}/{subresource_id}
Copy the code

In addition, there may be times when adding, deleting, or modifying a URL does not meet business requirements. You can add an action to the end of the URL, for example

/{version}/{resources}/{resource_id}/action
Copy the code

An action is an operation on a resource.

After knowing the composition of URL paths from the general style, the specific specifications for RESTful API URL design are as follows:

  1. Use all words in English and lower case instead of capital letters.
  2. A hyphen is used with a middle bar"-"You don’t have to go down"_"
  3. The correct use of"/" Represent the hierarchy, the URL level should not be too deep, and the higher the level should be relatively stable
  4. Do not include a forward slash delimiter at the end"/"
  5. There are no verbs in the URL and the action is requested
  6. Use plural rather than singular resources
  7. Do not use file extensions

HTTP verbs

In RESTful apis, different HTTP request methods have their own meanings. Here we show the design and meaning analysis of GET,POST,PUT, and DELETE request apis. Specific meanings for different operations are as follows:

GET/Collection: queries a list (array) of resources from the server. GET/Collection/Resource: queries a single resource from the server. POST/Collection: Create new resources on the server. PUT/Collection /resource: Updates server resources. DELETE /collection/resource: deletes resources from the serverCopy the code

In non-restful apis, we usually use GET and POST requests to add, delete, modify, check, and other operations. GET requests are used for query and delete, and POST requests are used for update and insert. There is no way to know what the API does from the request mode. All urls have action verbs to represent the actions of the API, such as: query, add, update, delete, etc.

In contrast to non-restful apis, which require that all urls appear as nouns, you can see what you want to do in several request ways.

When talking about GET,POST,PUT, and DELETE, it is necessary to mention the security and idempotency of the interface. Security means that methods do not modify the state of the resource, that is, read operations are safe and write operations are not safe. Idempotent means that an operation performed once will have the same effect as an operation performed many times, and the client will only return the same result after repeated calls.

The security and idempotency of the above four HTTP request methods are as follows:

HTTP Method security idempotence explain
GET security Power etc. The read operation is secure. The result is the same after multiple queries
POST The security The power etc. Write operations are unsafe, with new results for each additional insert
PUT The security Power etc. The write operation is unsafe. The result of one update is the same as that of multiple updates
DELETE The security Power etc. The write operation is unsafe. The result is the same as that of multiple deletions

Status code and return data

After the server processing is complete, the client may not know the specific success or failure. When the server responds, it contains two parts: status code and returned data.

Status code

We first need to correctly use various status codes to represent the processing results of the request. Status codes are classified into five types:

1xx: related information 2xx: Operation succeeded 3xx: redirection 4xx: client error 5xx: server error

Each category has several sub-categories, and there are many types of status codes. The main commonly used status codes are listed below:

200 OK – [GET] : the server successfully returns the requested data, which is Idempotent. 201 CREATED – [POST/PUT/PATCH] : Data is CREATED or modified successfully. 202 Accepted – [*] : indicates that a request is queued in the background (an asynchronous task). 204 NO CONTENT – [DELETE] : Indicates that the user deleted data successfully. 400 INVALID REQUEST – [POST/PUT/PATCH] : An error occurs in the REQUEST sent by the user. The server does not create or modify data. The operation is idempotency. 401 Unauthorized – [*] : Indicates that the user does not have permission (the token, user name, or password is incorrect). 403 Forbidden – [*] Indicates that the user is authorized (as opposed to the 401 error), but access is Forbidden. 404 NOT FOUND – [*] : The user requested a record that did NOT exist, the server did NOT perform the operation, the operation is idempotent. 406 Not Acceptable – [GET] : The format requested by the user is Not available (for example, the user requested JSON format, but only XML format). 410 Gone -[GET] : The requested resource is permanently deleted and cannot be retrieved. 422 Unprocesable Entity – [POST/PUT/PATCH] An authentication error occurred while creating an object. 500 INTERNAL SERVER ERROR – [*] : An ERROR occurs on the SERVER, and users cannot determine whether the request is successful.

Returns the result

The server returns data to the user for different operations, and each team or company encapsulates a different return entity class, but each returns data in JSON format to the client.

The third chapter is a RESTful API case

Above RESTful theoretical knowledge, let’s start to realize a small case!

prepare

In this case, the RESTful interfaces we access are all real operations on the database, creating a new database, and creating a database and table (according to your preferences).

To select Maven dependencies, you only need to check the Spring Web module, MySQL driver, and MyBatis framework.

The POJO in this case creates the dog.java entity object, which is constructed as follows:

package com.restfuldemo.pojo;

public class Dog {
    private int id;// Unique ID
    private String name;/ / name
    private  int age;/ / age
    // omit get set
}

Copy the code

With the project created above, let’s start building RESTful apis. In the specific construction of RESTful API, it is necessary to have a more detailed understanding of various requests. Of course, this case does not completely follow RESTful API specifications for the convenience of demonstration when implementing various requests. For example, the version number and other information are not added here, and the case focuses on implementing this interface with SpringBoot.

In this example, you can add, delete, modify, and query dog resources as follows:

API name The RESTful RESTful
Get dog /dogs/query/{dogid} The GET:/dogs/{dogid}
Insert the dog /dogs/add POST:/dogs
Update the dog /dogs/update/{dogid} PUT:/dogs/{dogid}
Delete the dog /dods/delete/{dogid} DELETE:/dogs/{dogid}

In addition, there are three common file types that are passed to the back end when sending requests using Postman:

form-data: is the multipart/form-data type in the form form, which processes the form data into a single piece of information, separated by specific tags. This file type is usually used to upload binary files.

X-www-form-urlencoded: Application/X-www-form-urlencoded, the default encType of form forms, which convert data into key-value pairs, cannot upload files in this format.

Raw: You can upload Text in any format. You can upload Text, JSON, XML, etc. But most of the data is in JSON format. When the back end needs to receive jSON-formatted data processing, this format can be used for testing.

Because GET requests query parameters on urls, other types of requests use X-www-form-urlencoded back-end transfer.

GET POST PUT DELETE request

GET request is used to obtain resources: GET request sends data request to the database, so as to obtain resources, this request is just like the database select operation, is used to query data, does not affect the content of resources. No matter how many times you do it, the result is the same.

And GET requests append the request parameters to the URL, but different browsers have different size and length restrictions.

In this case, we design two GET request apis. GET /dogs: Used to return a list of dog resources. GET /dogs/{dogid} : queries a single dog resource with this ID.

A POST request is used to add a resource: A POST request sends data to the server, but the request changes the content of the data (a new addition), just as an INSERT operation in a database creates new content. And the request parameters of the POST request are in the request body, its size is unlimited.

In this case, we design the API for the following POST request. POST/Dogs: Adds a dog resource on the server.

PUT requests are used to update resources. PUT requests send data to the server. Unlike POST requests, PUT requests focus on data modification, like updates in a database, whereas POST requests focus on data addition.

In this case, we design the API for the following POST request. PUT /dogs/{dogid} : The single dog resource used to update this ID.

A DELETE request is used to DELETE a resource. Corresponds to a delete in the database.

In this case, we design the API for the following DELETE request. DELETE /dogs/{dogid} : Deletes a single dog resource with this ID.

The corresponding Mapper file is:

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(a);

    @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);
}
Copy the code

The corresponding controller file is:

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(a)
    {
        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)
    {
        returndogMapper.deleteDogById(id); }}Copy the code

After the author tests everything is OK, if you want to project source files please contact the author to send you ha!

conclusion

RESTful apis are nice and formal, but most Internet companies don’t design according to or entirely according to their rules, because REST is a style, not a constraint or rule, and an overly desirable RESTful API can be too costly.

RESTful apis, for example, have some drawbacks

  • For example, the operation mode is cumbersome. RESTful apis usually distinguish resource operations based on GET, POST, PUT, and DELETE. However, the HTTP Method itself cannot be seen directly and is hidden.
  • And some browsers are not very friendly to requests other than GET and POST, requiring special extra processing.
  • Excessive emphasis is placed on resources, and actual business apis may have complex requirements. Adding, deleting, modifying, and querying resources alone may not effectively meet the requirements. Forced use of RESTful apis will only increase the difficulty and cost of development.

So, when you or your technical team are designing an API, you can use a RESTful STYLE API if the usage scenario matches the REST style. However, if the business needs and RESTful apis don’t match or are too cumbersome, then you can either use RESTful apis or learn from them. After all, apis of that style are for team development, negotiation, and management.

To here RESTful API introduction and actual combat is over, this article first from some of the characteristics of RESTful introduction, then to SpringBoot actual RESTful API, finally also said some RESTful API is not perfect, I believe that you have a very deep understanding of RESTful. The API design of future projects will definitely be optimized.

Different people may have different understanding of RESTful API, but the existence is reasonable, RESTful API has its distinct advantages and characteristics, is currently one of the main selection of API design, so it is quite important to master and understand RESTful API!

Original is not easy, Bigsai I ask you to help me with two things:

  1. Give me a thumbs up and your comments will definitely be my inspiration in the nuggets community.

  2. Wechat search “bigsai”, follow my public account (new people for support), not only free ebook for you, I will be the first time to share knowledge and technology in the public account. Plus I can pull you into the buckle punch group together punch LeetCode.

If there is help harvest, also please point a thumbs-up!