How to design a powerful API interface

Time:2021-3-23

In daily development, there are always various interfaces. Front and back end data transmission interface, third-party business platform interface. The front-end and back-end data transmission interfaces of a platform usually communicate in the Intranet environment and use the security framework, so the security can be well protected. This article focuses on how to design the business interface provided to the third-party platform? What should we consider?

How to design a powerful API interface

Mainly from the above three aspects to design a secure API interface.

I. security issues

Security is a specification that an interface must guarantee. If the interface can’t guarantee the security, then your interface is equivalent to being exposed to the public network environment.

1.1 prerequisite for calling interface – token

Generally, several parameters are involved in obtaining the tokenappidappkeytimestampnoncesign. We use the above parameters to obtain the credentials of the calling system.

appidandappkeyIt can be applied online directly through the platform, or it can be issued offline directly.appidIt’s globally unique, everyappidWill correspond to a customer,appkeyIt needs to be highly confidential.

timestampIs the time stamp, using the current UNIX time stamp of the system. The purpose of timestamp is to mitigate DoS attacks. Prevent the request interface from being attempted after the request is intercepted. If the request timestamp and server time exceed the threshold, the response fails.

nonceIt’s a random value. The random value is mainly for increasingsignIt can also protect the idempotency of the interface, adjacent to two requestsnonceDuplicate is not allowed. If it is duplicate, it is considered as duplicate submission and the response fails.

signIs a parameter signature and willappkeytimestampnonceOf course, MD5 encryption is not reversible.

token, using parametersappidtimestampnoncesignTo obtain the token as the only credential of the system call.tokenYou can set one-time validity (which is more secure) or timeliness, which is recommended here. If it works once, the request frequency of this interface may be very high.tokenIt is recommended to add it to the request header, which can be completely distinguished from the business parameters.

1.2 using post as interface request mode

Generally, the two most common ways to call an interface are get and post. The difference between the two is also obvious. The get request will expose the parameters in the browser URL, and there is a limit on the length. For higher security, all interfaces are requested by post.

1.3 client IP white list

IP white list refers to opening the access right of interface to some IP. In this way, other IP access attacks can be avoided. The trouble of setting IP white list is that when your client migrates, you need to contact the service provider again to add a new IP white list. There are many ways to set IP white list. In addition to the traditional firewall, sentinel, a component provided by spring cloud Alibaba, also supports white list setting. In order to reduce the complexity of the API, it is recommended to use firewall rules to set the whitelist.

1.4 single interface for IP current limiting

Current limiting is for better maintenance of system stability. Use redis to count the number of interface calls, IP + interface address as key, access times as value, each request value + 1, set the expiration time to limit the frequency of interface calls.

1.5 record interface request log

AOP is used to record the request log globally, quickly locate the abnormal request location, and investigate the cause of the problem.

1.6 desensitization of sensitive data

In the process of interface call, sensitive data such as order number may be involved. This kind of data usually needs desensitization, and the most common way is encryption. The encryption method is more secureRSAAsymmetric encryption. Asymmetric encryption algorithm has two keys, which are completely different but match. Only by using a pair of matching public key and private key, can the plaintext be encrypted and decrypted.

The problem of two idempotency

Idempotency means that the execution result of any multiple requests has the same impact as that of one request. To put it bluntly, the query operation will not affect the data itself no matter how many times it is queried, so the query operation itself is idempotent. But the new operation, every time the database will change, so it is non idempotent.

There are many ways to solve the idempotent problem. Here is a more rigorous one. It provides an interface to generate random numbers, which are globally unique. The random number is brought in when calling the interface. For the first call, after the business processing is successful, the random number is used as the key and the operation result as the value, which is stored in redis, and the expiration time is set at the same time. The second call queries redis. If the key exists, it is proved to be a duplicate submission and an error is returned directly.

3. Data standardization

3.1 version control

A set of mature API documents, once released, are not allowed to modify the interface. At this time, if you want to add or modify an interface, you need to add version control. The version number can be either integer or floating-point. Generally, the interface address will carry the version number,http://ip:port//v1/list。

3.2 response status code specification

A powerful API, also need to provide a simple and clear response value, according to the status code can roughly know the problem. We use the HTTP status code for data encapsulation. For example, 200 indicates successful request, 4xx indicates client error, and 5xx indicates internal error of server. The design reference of status code is as follows:

classification describe
1xx Message, the server receives the request and needs the requester to continue the operation
2xx success
3xx Redirection, further action is required to complete the request
4xx Client error, request contains syntax error or cannot complete request
5xx Server error

Status code enumeration class:

public enum CodeEnum {

    //Add according to business requirements
    Success (200, "processing success"),
    ERROR_ Path (404, "request address error"),
    ERROR_ Server (505, "server internal error");
    
    private int code;
    private String message;
    
    CodeEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

3.3 unified response data format

In order to facilitate the response to the client, the response data will contain three attributes: status code, message and response data. The client can quickly know the interface according to the status code and information description. If the status code returns successfully, it will start to process the data.

Response result definition and common methods:

public class R implements Serializable {

    private static final long serialVersionUID = 793034041048451317L;

    private int code;
    private String message;
    private Object data = null;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    /**
     *Put response enumeration
     */
    public R fillCode(CodeEnum codeEnum){
        this.setCode(codeEnum.getCode());
        this.setMessage(codeEnum.getMessage());
        return this;
    }

    /**
     *Put in response code and information
     */
    public R fillCode(int code, String message){
        this.setCode(code);
        this.setMessage(message);
        return this;
    }

    /**
     *The processing is successful. Put it into the custom business data collection
     */
    public R fillData(Object data) {
        this.setCode(CodeEnum.SUCCESS.getCode());
        this.setMessage(CodeEnum.SUCCESS.getMessage());
        this.data = data;
        return this;
    }
}

summary

This article discusses the API design specification from the aspects of security, idempotence and data specification. In addition, a good API needs an excellent interface document. The readability of interface documents is very important, although many programmers do not like to write documents, and do not like others not to write documents. In order not to increase the pressure of programmers, it is recommended to use swagger or other interface management tools. Through simple configuration, the connectivity of interfaces can be tested in development, and offline documents can be generated for API management after online.

Pay more attention and don’t get lost

If you think the article is good, welcomefollowgive the thumbs-upCollectionYour support is the driving force of my creation. Thank you.

If there is a problem in the article, please don’t be stingy. Welcome to leave a message, and I will check and revise it in time.

If you want to know more about me, you can search theJava journey“To pay attention. Reply to “1024“To get learning videos and excellent e-books. Push technical articles on time at 7:30 every day, so that your way to work is not lonely, and there are book delivery activities every month to help you improve your hard power!