Is the API interface design unreasonable? Individuals and companies have problems

foreword

In the process of software product or project development, a large number of API interface development tasks are often involved. And if the birth of an interface is puzzling, painful, and has serious sequelae, the root cause is that the design of the API interface is not clear, reasonable, and lacks long-term considerations. I will talk about the topic of API interface design based on the questions and answers of many colleagues, practical work experience and various auxiliary tools.

I limit the scope of what I want to talk about today to the front-end and back-end RESTful APIinterface development of small and medium-sized business functions in a narrow sense. The content beyond the scope may not be accurate and profound enough due to insufficient level. The main content includes the problems I often encounter in my work and my personal reflections.

definition

" The API interface can enable seamless communication and interaction between different software components, thereby improving the efficiency and flexibility of software development. " The typical software components are between the front end and the back end, and the efficiency and flexibility are One of the goals we want to pursue.

So did the API we actually developed achieve the goal? If the goal is to realize the business function, then I believe that most developers can pat their chests to ensure that the API I wrote can definitely realize the function, and I am extremely confident that there is no possibility of bugs. But if it is judged by whether it is efficient and flexible enough, then:

  • One is that there is no practical standard to measure (various development languages ​​and tool standards are quite different)
  • The second is that there is no authoritative referee to judge (generally, the front and rear ends shirk each other, argue and finally even use force!)
  • The third is that there is not enough time and motivation for me to realize the difference between feasible and better and "I have never seen a better design than mine, so mine should be the best".

question

Next, let's take a look at the following questions. Do you feel the same way?

  1. Some APIs seem to be full of parameters from the documentation at a glance, with almost no comments or instructions, and nothing about usage, scenarios, exception handling, etc. If a newcomer takes over, they have no idea what these are for, and can only barely find the answer by asking orally or looking through the source code.

  2. Some API styles are not uniform, and the naming, input parameters, output parameters, and error messages are different between different businesses, or even within the same business. The reasonable explanation is that different APIs come from different engineers, and it was already like this when I took over the code.

  3. The response time of the interface suddenly changed from tens of milliseconds to tens of seconds or even timed out; the error message was thrown out in a large number of English; the API performance index was out of the question, and I didn’t pay attention to this because most of our business is toB , There is no actual situation of high concurrency at all.

  4. With the evolution of business, the number of open APIs continues to increase, but there are many similar ones. Sometimes there are multiple interfaces for querying the same content, but they do one thing. The reason may be that I don’t know that there is already an interface with the same function; or I dare not touch the interface written by others. What should I do if it is changed? So to be on the safe side, I'll start a new interface!

The above problems may happen to us every day, but we have long been used to numbness, until the emergence of AI programming, it will mercilessly point out our shortcomings, radically refactor our code, and write Very good quality API, finally replace our work and destroy our rice bowl! Sounds terrible, so let's understand what are the characteristics of a good API:

An excellent API should have characteristics such as ease of use, scalability, security, stability, compatibility, documentation, testability, and good performance and efficiency to meet the needs of developers and customers.

We can understand these characteristics in words, but many students still don't know how to do it. What are the principles of API design?

API design should follow the principles of simplicity, consistency, predictability, scalability, security, high performance, scalability, testability, documentability, and resource-oriented to provide easy-to-use, reliable, efficient and Secure API service.

Through these words, we realized that many API interfaces in our work did not follow these principles, for example: simplicity and documentability correspond to problem 1, consistency and predictability correspond to problem 2, high performance and scalability correspond to Question 3, scalability corresponds to question 4.

Principles are dead, people are alive, we have not yet evolved to the point where we can write codes intelligently through AI, although that is the trend, but I am curious when AI reads our shit mountain code, what will it say sigh! Or when we train an AI with a mountain of shit codebase, will it write it better than us?

analyze

Next, I will give examples and summarize the thoughts and methods in the API interface design stage, and the key points are expressed in bold. Please criticize and correct where there may be biases.

1. What is the reason for doing it?

It is not necessary to have an interface for any function, nor is it necessary to add an interface for any requirement.

Every time a new interface is created, there must be sufficient reasons and considerations, that is, the existence of this interface is very meaningful and valuable. Meaningless interfaces not only increase the difficulty of maintenance, but more importantly, the controllability of the program is greatly reduced, and the interface will be very bloated.

2. Start with an elegant name

When designing an interface, the angle of analysis should be unified. Otherwise, the interface structure will be confused. Each API interface should only focus on one thing, and do it well. The product concept is simple and the relationship is clear. The functions are ambiguous, and APIs with many special logics are definitely not an elegant API, and will cause APIs with similar functions and duplicates.

Note: If the API is difficult to name, then this may be a bad sign, good names can drive development, and just split and merge modules.

avoid:/api/getdata、/api/servicexyz、/api/action1、/api/action2、/api/action3

recommend:get('/api/users/:id/orders')、put('/api/users/:id')、post('/api/users')、delete('/api/users/:id')

A large and full-featured API must be stretched in terms of flexibility and simplicity. Before defining the granularity of the API, it is recommended to divide the business into domains and boundaries to extract business objects, and then design a single-function API based on the use cases of the business objects.

3. Simplify parameters and shrink parameters

The interface design is simple and clear. The functions performed by the API can be very rich and powerful, but the API declaration and usage must be as simple as possible, and the richness of functions cannot be realized through complex usage, which will lead to more than one API function and uncontrollable evolution.

  • Are you forcing callers to care/provide options/configurations they don't care about?
  • Are there any worthless extra steps?

Code example:

function generatePDF(html, orientation = "portrait", format = "A4", margin = "0.5in") {
  // 根据给定的HTML生成PDF文件,可以指定方向、格式和边距
  ...
}

In this example, the generatePDF function accepts four parameters, three of which (orientation, format, and margins) are optional. However, the problem with this function is that it enforces these three options into the function signature, which means that callers have to care about these options, even if they don't care about them or don't need them at all.

The solution to this problem is to encapsulate the options in an object and pass it as a single argument, eg generatePDF(html, options). This way, callers can focus on only the options they need, improving code readability and maintainability.

Also, if you need to add more options in the future, you can simply add new properties in the individual objects without changing the function's signature. This improves the scalability of the code.

4. Data model!==Interface input/output parameters

The objects and attributes described in the input and output parameters of the API must be entities abstracted according to business characteristics, and do not mistakenly reflect the concept of the underlying data model on the API. Abstract APIs and abstract object entities are more macroscopic, with better applicability, compatibility, and scalability.

// 错误的代码
function createUser(username, password, role_id) {
  // ...
}
// 底层数据模型
class User {
  constructor(username, password, role_id) {
    // ...
  }
}

In this example, the API uses the concepts of the underlying data model to define createUserthe parameters of the function, namely username, , passwordand role_id. This makes the API difficult to use and maintain, as callers may not know how to use these parameters, and when the underlying data model changes in the future, these parameters will also need to change.

// 更好的代码
function createUser(user) {
  // ...
}
// 更好的底层数据模型
class User {
  constructor(username, password, role) {
    // ...
  }
}

This makes it possible to define the parameters of the API as an object containing user information, which makes it easier for callers to use the API, and also makes it easier to update the API when the underlying data model changes.

5. Reduce the frequency of being "frightened"

The API code should surprise or scare the reader as little as possible. Have you ever exclaimed " Fuck " when you saw a bunch or a line of weird code? Surprised is a derogatory term in the world of programmers. The business API only needs to be designed according to the needs, and there is no need to deliberately design complex, useless, flashy APIs to avoid self-defeating.

Adding more comments, error handling, and documentation to key processing logic or conditional judgment can help callers use this interface correctly, and also help remind authors of some technical details that they have forgotten after a period of time. You never know who will be the next person to use your code. Write interface descriptions and comments unpretentiously to reduce the possibility of future successors sighing and the frequency of "asking east and west" to find you from far away.

The following is the API interface document of ChatGPT chat. It can be seen that the interface is quite satisfactory, unremarkable and even a bit simple, so that any junior developer can write it out. The two model+messagesrequired parameters are enough to meet the requirements, but the technology behind the interface seems to be leading the way. A technological revolution. What is amazing is not the interface itself, but the capabilities that the interface can provide.

 

6. Reduce coupling

APIs should reduce dependencies on other business code. Low coupling is often a sign of a well-structured system and good design.

Types of coupling:

  • The code realizes the business reverse call. (Using the three major features of object-oriented programming - encapsulation, inheritance, polymorphism)
  • Conditional logic depends on coupling. (use strategy pattern or table driven approach to refactor code)
  • Coupling API-independent business behavior. (extract individual functions or classes)

7. Testing is our good friend, not a tool man

For API callers, the API should be testable and easy to test. The test API does not need to rely on additional environments, containers, configurations, public services, etc.

A testable-friendly API is also a prerequisite for effective integration testing. In addition, unit testing, integration testing and automated testing tools are also very important. We may have heard of test cases but never wrote them, but this is not important. The important thing is that you have to try to execute the interface after writing it? Is it really appropriate to throw it directly to the user/tester regardless of anything? When encountering an interface that is not fully self-tested, the inner activity of the user/tester is: the second battalion commander! Where's your fucking Italian gun? Pull me!

Say the important thing three times: "Must interface self-test! Must interface self-test! Must interface self-test!"

8. Unification

The API should have unified naming, unified input/output parameter specification, unified exception specification, unified error code specification, unified version specification, etc.

Advantages of a unified and standardized API:

  • Easy to be integrated and processed by the framework
  • Helps API callers and API providers to reuse development experience
  • avoid mistakes, avoid misuse

Comrades, the task is still arduous, let us complete the great cause of reunification together !

The above 8 items are not only applicable to the API interface between the front end and the back end, but also between the front end and the front end, and between the back end and the back end.

think

In fact, there are a lot of examples, experiences and lessons mentioned above on the Internet. As an era of such advanced information technology, it is easy to find some content about interface design, but why people don’t like to follow What about API design principles for API interface development?

There are some possible reasons why people don't like to follow API design principles for API interface development:

  1. Lack of experience or knowledge: Some developers may lack experience or knowledge of API design, or do not understand the importance of API design principles. In this case, they may write low-quality APIs instead of following best practices.

  2. Time and cost pressure: Sometimes, developers may face time and cost pressure and need to complete API development as soon as possible. In this case, they may sacrifice the quality of the API design principles to meet short-term goals.

  3. Unaware of the audience of the API: Developers may overlook the audience of the API, i.e. other developers using the API. They may feel that the API they write is the best, regardless of other people's needs and usage.

  4. Company culture and management: Some companies may not pay attention to API design principles, or provide relevant training and support. In this case, developers may lack knowledge and practice of API design principles, resulting in poor quality APIs.

In general, following the API design principles can improve the quality and maintainability of the API, but this requires developers to have certain experience and knowledge, and needs to be supported and valued in the company's culture and management.

Audiences who lack experience or knowledge and do not understand the API can be resolved through subjective initiative, but time and cost pressures, company culture and management are not subject to the developer's will.

Summarize

Well, if someone can patiently see the end here, he must be a person with a very high technical awareness!

To sum up one sentence: an interface without design is soulless!

Guess you like

Origin blog.csdn.net/APItesterCris/article/details/131560590