Communication creates value , Sharing brings happiness . Here is the programmer's reading time , Share your reading experience every day , You are welcome to work hard with me every day . Today's topic of discussion with you is how to design a good API Interface ？
author ： Liang Guizhao
Reading ： Zhang Feihong
API It's the core of the software system , And we're designing API Interface will face many challenges ：
From the scene , It is diverse , How to design a Applicable everywhere Of API？
The business we are involved in is evolving , How to design one with Compatibility Of API？
Our software process is co developed , Then how can we achieve the goal of API Of Unified cognition ？
Today I want to discuss with you how to design a good API Interface , I think it's good API The design needs to take these elements into account at the same time ： Standardization 、 Compatibility 、 Abstraction 、 simplicity 、 High performance , It can be said that these elements are indispensable .
about Web API In terms of Standardization , A very good case is Restful API. The current industry Open API Most are based on Restful API Standardized design .
1、 Hierarchical model
It should be noted that Restful API It has a mature model .
among Level 0 It's a normal request response pattern .
Level 1 Introduced the concept of resources , Each resource can be created separately URI, And Level 0 comparison , It deals with complex problems by dividing and ruling resources .
Level 2 Introduced a set of standard HTTP agreement , It is by following HTTP The agreement defines the verb and cooperates with HTTP Response status code to normalize Web API Standards for .
Level 3 in , Using hypermedia can make the protocol self describing .
Usually , Achieve... In the maturity model Level 2 It's already very good .
stay Restful API in , every last URI Represents a resource , Is the unique locator of each resource . Resources , Yes, on the server A passage of text 、 A file 、 A picture 、 A song , Or a service .
Restful API Well , Provides for the passage of get/post/put/patch/delete And other methods to operate the resources of the server .
therefore , We are defining a Web API When , You need to clearly define how it requests 、 edition 、 Resource name and resource ID.
for instance , To view the user code is 101 User information for , I can define get Request method of , And his version is V1, The name of the resource is users, resources ID yes 1001.
Think about it here , What if there are multiple resource combinations ？
In fact, the concept of sub resources can also be introduced , You need to clearly define how it requests 、 edition 、 Resource name and resource ID, And the sub resource name and this resource ID.
for instance , To view the user code is 101 User's permission information , I can define get Request method of . And his version is V1, The primary resource name is Users, Main resources ID yes 1001 The sub resource name is Roles, resources ID yes 101.
occasionally , When a natural change is difficult to use standard Restful API To name , You can consider using some special actions name .
For example, password modification interface , I can define Put Request method of , And his version is V, The primary resource name is users, Main resources ID yes 101 The resource field is password. Then define a action The operation of modify.
3、 Error code and return mechanism
At the same time , It is recommended not to try to create your own error code and return error mechanism .
Many times , We feel that providing more custom error codes will help convey information , But in fact , If it's just a message , The error message field can achieve the same effect .
Besides , For the client , It's hard to focus on so many wrong details , Such a design will only make API The processing of becomes more complex , Difficult to understand .
therefore , My advice is to follow Restful API The specification of , Use HTTP Standard error code . for example , We use it 200 Indicates that the request was successful , use 400 Indicates an incorrect request , and 500 Indicates an internal error in the server .
When Restful API The interface has a non 200 Of HTTP Error code response , The global exception structure can be used to respond to information .
4、 Return body structure
Here is a list of the most Commonly used A few fields of , Tell me what they mean .
among code Field is used to represent the error code of a certain type of error , For example, the invalid request described earlier 、 Lack of parameter 、 Unauthorized resources 、 No resources found 、 An error already exists .
and message Field is used to represent the summary information of the error , Its function is to enable developers to quickly identify errors .
server_time Field , Used to record the server time when sending errors , He can clearly tell the developer the specific time when the error occurs , It is convenient to quickly locate the error information according to the time range in the log system .
Besides , Not commonly used Fields will respond differently according to different situations .
If it's a single piece of data , Returns the of an object json character string ; If it is list data , Returns an encapsulated structure , It covers count Fields and item Field .
count Field represents the total amount of data returned . It should be noted that , If the interface has no paging requirements , Try not to return this count Field , Because querying the total amount of data is a performance consuming operation .
Besides ,item Field represents the list of returned data , He is a json An array of strings .
To sum up , How to understand norms ？ It can be said that he is the standard established by everyone , If we all abide by this set of standards , Naturally, the cost of communication is greatly reduced .
Then let's talk about API Interface compatibility . Because the business we participate in is evolving , Design a compatible API This is particularly important . If the interface is not downward compatible , Business will be greatly affected .
for example ：
Our products cover android、ios、pc Terminal , All run on the user's machine , In this case , Users must upgrade the product to the latest version to better Use .
meanwhile , We may also encounter non-stop upgrade of the server , because API Incompatibility and short service failure .
In order to achieve API The compatibility of , We introduced the concept of version , The previous case URI It is compatible with multiple versions by retaining the version number .
for instance , The user code to view is 1001 User information for , Can be defined separately V1 and V2 Two versions of API Interface , Then let them correspond to two sets of incompatible business logic features .
Usually , Our interface abstractions are Business based The needs of the , Therefore, on the one hand, we should define a clear business problem domain model , Such as data model and domain model , And establish a realistic mapping of a problem , This is good for different roles API Design The unity of cognition .
On the other hand ,API If the design can realize abstraction , It can well shield the specific business implementation details , Provide us with better Extensibility .
The main purpose of simplicity is to abide by Minimum knowledge principle .
How to understand ？ In fact, the client does not need to know so many services API Interface , And these API Interface call details , For example, the appearance pattern and mediator pattern of design pattern are its application cases .
As shown in the figure , The facade interface encapsulates and integrates multiple services , And provides a simple API Call to the client to use , What are the benefits of this design ？ That is, the client only needs to call this appearance interface , Some complicated steps are omitted .
meanwhile , We also need to focus on performance , For example, appearance interface , Although simplicity is guaranteed , But it increases the service complexity , meanwhile , Due to the aggregation between multiple services , As a result, their interface performance is not very good .
Besides , We also need to consider whether various combinations of fields will cause performance problems of the database . Sometimes , We may expose too many fields for external use , This causes the database to have no corresponding index and full table scanning . This situation is very common in query scenarios , Therefore, we can only provide the combination of fields with index to external calls .
Result<Void> agree(Long taskId,Long caseId,Configger configger)
In the above code case , The caller is required taskId and caseId To ensure the use of database indexes , To further ensure the service performance of the service provider .
Today, I will focus on how to design a good API Interface .
well API The design needs us to take into account Standardization 、 Compatibility 、 Abstraction 、 Simplicity and high performance .
among , The key to standardization is to create as few custom specifications and mechanisms as possible , But to abide by industry standards , for example HTTP Normative and Restful API standard .
Usually , We will adopt version number to solve the problem of multi version compatibility .
Abstraction needs to ensure that a clear problem domain model can be defined , Shield specific business implementation details as much as possible .
Simplicity is relative , The principle of minimum knowledge needs to be observed , Let the caller know the internal call details as little as possible , Pay more attention to the details of performance , The business combination and parameter combination scenarios are mainly emphasized here .