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
# Specify the user with id 1
# Too much data, just top 10
# Starting from the 10th data (not the first 10 data)

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


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


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

        <!--Specifies the profile used to generate the document,Profile in your own project-->
        <!--Specify project name-->
        <!--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-->
            <!--The format is: groupId:artifactId;Refer to the following-->
            <!--If you do not need to start at compile time smart-doc´╝îWill phase Annotate-->

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": " / 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


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

    private String username;

     * ID number
    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
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
public List<User> selectAll(@RequestParam(required = false) Integer limit) {
    if (limit == null) {
        return userMapper.selectList(null);
    } else {
        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

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

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