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 universal API?

  • The business we are involved in is evolving , How to design a compatible API?

  • Our software process is co developed , Then how can we achieve the goal of API Unified cognition of ?

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 , It can be a piece of text on the server 、 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 are some of the most commonly used fields , 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 , Uncommon 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 .

5、 Summary

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 abstraction is based on business requirements , 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 Unity of design 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 scalability .


The main purpose of simplicity is to abide by the principle of minimum knowledge .

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 Design requires us to consider standardization at the same time 、 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 .

How to design a good API Interface ? More articles about

  1. How to design an excellent API

    How to design an excellent API - article - Bole Online How to design an excellent API - Punctuation ...

  2. How to design an excellent API( Reprint )

    Recently, I've been sorting out some of the framework API, I feel it necessary to summarize API Compatibility design . The following figure is my own summary of the moment , Maintain slowly : I searched the Internet , A little over a month ago ,“ Punctuation ” The following article has been published , I think it's very good , Reproduced in ...

  3. How to design an excellent API( turn )

    up to now , Already responsible for API Nearly two years , In the past two years, the existing API There are more and more problems , But many API Once released, it can no longer be modified , Immediate upgrade and maintenance is a must . once API change , It may bring huge costs to the relevant callers , ...

  4. Front end weekly 2.27 - 3.5: How to design an excellent HTML Interface , In depth understanding of line-height

    From this week on , Every Monday I share the technology sites I subscribed to last week , And the articles worth sharing in the process of solving problems , Or a video tutorial , Or books . I think foreign technical articles are of high quality , And the technical information released is also at the forefront of the industry , So I pay more attention to ...

  5. How to design an asynchronous Web service —— Interface part

    The requirements are simple , Provides an asynchronous Web Services are available for users to call . for instance , An application needs to batch add lomo effect . Because of plus lomo The effect of this operation is very consuming CPU resources , So we need to add this to lomo The program logic of the effect is put into a separate ...

  6. A login to browse api Interface ; Other related : Form_with Different ways of writing parameters ; Easy to use curl.

    eeting-up app: Complete a requirement : complete : The fourth step is to realize API Interface Add api base a ...

  7. How to design a powerful API Interface

    In daily development , There are always interfaces . Front and back data transmission interface , Third party business platform interface . The front and back data transmission interfaces of a platform usually communicate in the Intranet environment , And use a security framework , So security can be well protected . This article focuses on the discussion of the topic ...

  8. Integrating wechat apps Web API Interface layer architecture design

    In front of me, there are many essays about Web API Interface layer architecture design , And the official account of WeChat . enterprise . The classification of small programs and other modules . For example, in <C# Develop wechat portal and Application (43)-- The definition and relationship of each project module of wechat > Medium ...

  9. How to design an elegant RESTFUL The interface of

    show me the code and talk to me, What we can do should be more clear I'm bull bl, Your support is the driving force for me to share ! One . introduce Designing interfaces is the daily operation of our developers . When we give the interface to the front-end personnel , ...

  10. First time to know Django —Python API Introduction to interface programming

    First time to know Django —Python API Introduction to interface programming One .WEB A brief introduction to the architecture Django What is it? ? Django Is an open source Web Application framework , from Python It's written in . Our goal is to use Python Language , ...

Random recommendation

  1. android studio Report errors -----R Show all in red ---- .9 Picture error reporting

    Import android After the project ,R All red , The console has the following prompt It means lack of some resources , Like pictures , Then I found that there was indeed a missing picture resource , After importing picture resources , Is still an error , as follows  Error:Execution fai ...

  2. primefaces p:dataExporter filename Support Chinese utf8

    p:fileDownload and p:dataExporter : for p:fileDownload, the Content-Disposition header should be set ...

  3. NAS4Free To configure BT download

    NAS4Free Turn on BT Download function Services|BitTorrent Select the check box in the upper right corner Peer port It's the listening port , Used to accept external connections , You need to configure the port to the server in the router , To mention ...

  4. ( secondary ) HDU 1542 Atlantis, Scan line .

    Problem Description There are several ancient Greek texts that contain descriptions of the fabled is ...

  5. Django Introduction to template language

    One .Django Introduction to the framework 1.MVC frame MVC, The full name is Model View Controller, Is a software architecture pattern in software engineering , Divide the software system into three basic parts : Model (Model). View (View) Harmony control ...

  6. C In language __attribute__ ((at()) Application of absolute positioning

    C Keywords in language __attribute__ , At that time, I was a freshman C Not in the language , Later, I engaged in RFID Bluetooth tag card development , It's using MSP430G2332, The direct use is absolute positioning : 1 const uint8_t f ...

  7. Create... For your machine learning model API service

    1. What is? API When the bartenders have trained a model , The next step is to do code docking with business development group students , So that's all ‘AI The brain ’ They can be used smoothly . However, it is often challenged by different programming languages , For example, it is very common to use Pyt ...

  8. summary ASP.NET MVC The view page uses jQuery There are several ways to transfer asynchronous data

    stay ASP.NET MVC The view page of passes asynchronous data to the controller , It could be an array ,JavaScript object ,json, The form data , wait . About data ,JavaScript Objects are sometimes related to json It looks as like as two peas , Do you have any ? var ...

  9. iOS And PHP/Android AES128 ECB NoPadding encryption

    Preface Talk about AES encryption , There are many versions on the Internet , When I'm not really in front of encryption security , I always thought that Baidu came out of some AES The encryption algorithm can be used directly , In fact, when I really want to do encryption , There were a lot of holes , It's not easy to use it . Write down this article , remember ...

  10. poj3026

    Borg Maze Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 12952   Accepted: 4227 Descri ...