Learning notes of Spring framework -- API interface design related knowledge and specific coding implementation

Recently, we need to design an API server. If we want to standardize the API interface, we have collected some information on the Internet. Here are some of our own understandings and specific implementation

This paper adopts the scheme of spring boot+maven

restful specification

I'm not going to explain this standard in a long way here. How can I say it? Some people like it and others hate it, and I don't want to argue about it, because I don't have much experience and have different opinions from the big guys.

The restful specification is simply to define the url interface through some keywords, so as to make the url more readable, as shown in the following example

# Query all users
http://localhost:9200/shunbang/api/user/users
# Specify the user with id 1
http://localhost:9200/shunbang/api/user/users/1
# Too much data, just top 10
http://localhost:9200/shunbang/api/user/users?limit=10
# Starting from the 10th data (not the first 10 data)
http://localhost:9200/shunbang/api/user/users?offset=10

I think restful is standardized and the readability of url is better

Several ways of using restful specification

mode Explain
get Get resource from server (select)
put Update resources on the server
post Store incoming resources on the server (insert)
delete Delete resources on the server

Introduction to url request protocol

mode Explain Example
application/x-www-form-urlencoded By default, the client passes data through key value pairs http://localhost:9200/shunbang/api/user/update?id=1&name=xx
application/json Client sends json data through body
application/xml Client sends xml data through body
application/octet-stream Client sends Binary data (Binary file) through body
multipart/form-data Client sends a form through body

API document generation framework smart doc

introduce

Here, I used smart-doc This framework can implement the annotation of API interface without intrusion. It needs to add annotation in Controller and entity class

Use

Using this open source library is very simple. We just need to add the dependency of plug-ins in maven project

<plugin>
    <groupId>com.github.shalousun</groupId>
    <artifactId>smart-doc-maven-plugin</artifactId>
    <version>1.0.2</version>
    <configuration>
        <!--Specifies the profile used to generate the document,Profile in your own project-->
        <configFile>./src/main/resources/smart-doc.json</configFile>
        <!--Specify project name-->
        <projectName>test</projectName>
        <!--smart-doc Realize automatic analysis of the source code of the third-party dependency loaded by the dependency tree. If some framework dependency libraries fail to load, resulting in an error, please use the excludes Get rid of-->
        <excludes>
            <!--The format is: groupId:artifactId;Refer to the following-->
            <exclude>com.alibaba:fastjson</exclude>
        </excludes>
    </configuration>
    <executions>
        <execution>
            <!--If you do not need to start at compile time smart-doc´╝îWill phase Annotate-->
            <phase>compile</phase>
            <goals>
                <goal>html</goal>
            </goals>
        </execution>
    </executions>
</plugin>

After that, create a new smart-doc.json file in the resources folder and make some configuration

{
  "outPath": "Q:\\JavaWebProject\\shunbang\\target", //Specify the output path of the document
  "serverUrl": "http://Localhost: 9200 / running ", / / set server address, not required
//  "Serverurl": "http://47.101.148.199:9200 / running", / / set server address, not required
  "isStrict": false, //Whether to turn on strict mode
  "allInOne": true  //Whether to merge documents into one file is generally recommended as true
}

Strict mode is not enabled here. If strict mode is enabled, an error will be reported when calling plug-ins

Then directly find it in the next plug-in and select the corresponding generated document

After that, you can find the html file in the output folder

Open the web page and you will have detailed documents

supplement

JsonIgnore annotation

If there are some sensitive fields that do not need to be returned, add the JsonIgnore annotation to the fields of the entity class (Note: this JsonIgnore annotation comes with the spring boot built-in jackson framework)

public class JacksonAnnotation {

    /**
     * User name
     */

    @JsonProperty("name")
    private String username;


    /**
     * ID number
     */
    @JsonIgnore
    private String idCard;
}

Fastjson uses @ JSONField(serialize = false), and the key is serialize = false

mock annotation

Smart doc will automatically assign random values in the generated document example, as shown in the following figure

If you don't want random assignments, you can use the mock annotation to specify the data in the example

ignore annotation

This is the annotation of smart doc. When it is written on the annotation of entity class field, the generated API document will ignore this field

For more details, please refer to Official documents

Specific encoding

In spring boot, GetMapping, PostMapping, PutMapping and DeleteMapping are built-in, which correspond to different request methods. If the above annotation is used, the url request method should also correspond, otherwise the server will not return data

1. specify id

You want to query the user information of the specified id through http://localhost:9200/shunbang/api/user/users/1

Using the PathVariable annotation

/**
 * Query the user information of the specified id
 *
 * @param id User id
 * @return User information
 */
@GetMapping("{id}")
public User selectByPk(@PathVariable("id") Integer id) {
    return userMapper.selectOne(new QueryWrapper<User>().eq("user_id", id));
}

2.limit limit

To obtain the first few records through http://localhost:9200/shunbang/api/user/users?limit=10, this parameter is optional, and use the RequestParam annotation

When the user does not input the limit parameter, the display will return all the data. If so, the data will be limited. The same is true for offset, which will not be mentioned later

/**
 * Query all users
 *
 * @return json of user list
 */
@GetMapping("users")
public List<User> selectAll(@RequestParam(required = false) Integer limit) {
    if (limit == null) {
        return userMapper.selectList(null);
    } else {
        System.out.println(limit);
        return userMapper.selectList(null);
    }
}

3. Transfer entity class

Originally, I wanted to pass the json data of entity class through http://localhost:9200/shunbang/api/user/update?jsonData=xx. After that, I would receive the json data from the background, and then convert the json data into entity class objects, call the update method, and update the table record

In fact, there is a method that is simpler than the above one. Use the RequestBody annotation, and then make the put request, and pass the json data directly through the body

@PutMapping("update")
public boolean updateUser(@RequestBody User user) {
    return user.updateById();
}

Java sends url request

HttpURLConnection conn =new URL("address").openConnection();
conn.setRequestMethod("PUT"); // You can submit the functions provided by http, such as GET, POST, DELETE, and PUT, as required
conn.setRequestProperty("Content-Type", " application/json");//Set the request format json, or the xml format

The above is native. After that, I will supplement the relevant interface application data using the okhttp framework

I use postman for API testing

Reference resources

smart-doc
Spring boot restful style API interface development
What is the difference between Post method parameters written in body and url? Reply from Zhihu Yan Zhenjie

Tags: Java JSON Spring Maven xml

Posted on Thu, 13 Feb 2020 10:23:11 -0500 by pyc