How does the API work (novice teaching method)

We have a bank

Think about it if you are running a bank. Are you excited about it? YY is not guilty.
How does the API work (novice teaching method)
There is a sturdy vault in the bank to store money, and a logbook to record the number of guests. There is a very simple (lazy) way to operate this bank: open access to each visitor once, no one will check the identity of the visitor, and the bank believes that people will do the right thing.

In this open bank, if customers want to deposit money, the steps they need to do are as follows:
1: Take money to the bank;

2: Open the vault and put the money in the middle;

3: Write a record on the ledger: I am xxx, and I saved xxx money;

4: Leave the bank.

Obviously, smart you will definitely not use this method to manage your bank, because this method has the following two problems:
1: The door of the vault is difficult to open and requires a certain amount of physical strength. It is not very friendly to disadvantaged groups, which may violate some health and safety regulations. Similarly, if someone has a hand injury or cannot see clearly, they cannot read or write on the ledger.

2: In this method, the bank believes that people are absolutely honest. Obviously, there are always dishonest people in reality. I bet someone will deposit 100 yuan and then write 10,000 yuan on the ledger. You went bankrupt within two days.

Therefore, we need to further design a more complete process for managing banks.

We hired a bank teller

Since we are completely indulging in the above problems, we can consider hiring a smart and strong person to handle all vault visits, so we hired teller Sally to do this work.

Now, the way we manage the bank has improved: there is a wall (Sally) that separates the vault and the ledger from the customer, and the customer cannot directly operate in the ledger or the vault. If they want to deposit and withdraw, they must pass Our friendly teller Sally.
How does the API work (novice teaching method)
Now that customers want to save money, the steps required are more complicated, as follows:
1: Take the money to the bank;

2: Tell teller Sally, I am xxx, and I need to deposit so much money from xxx to my account;

3: Sally takes the money you deposited and puts it in the safe. She is very strong and can do this easily;

4: Sally wrote down this record on the ledger: xxx deposited so much money in xxx;

4: Sally returns to the counter and informs the guest that he can leave;

4: The guest leaves the bank;
now, the guest does not need to open that huge and heavy door, and the whole process has no obstacles for the guest. And Sally is also someone we trust, so the risk of the second problem above is much smaller.

API---application programming interface

Now, we can introduce the concept of API. API is called application programming interface, which is the convention for connecting different components of software system

Simply put, API allows you to easily communicate with other software, which is very important.

In our analogy, the bank has a vault door that is difficult to open. If we let the bank teller open the door, then the customer does not have to bother to open the door, the customer saves time, and the bank is safer.

Similarly, we abstract the implementation details of the operation (such as allocating system memory, or launching a rocket into space), which will help reduce the programmer's cognitive load (the number of things a person must remember at a time), thereby increasing productivity . For example, if we make an API to launch a rocket into space, programmers can use this API. In the blink of an eye, the engine will ignite and the rocket will shoot directly into the sky. Since the implementation details are abstracted out (hidden behind the API), our programmers can send rockets into space without knowing rocket science.

With this information summary, there is another benefit: As long as they follow the same protocol, components can be swapped out and replaced. The bank does not need to know how the customer arrived at the bank, nor does the customer need to know that the bank has transferred all the money to a tax haven. As long as the bank teller is still there and knows how to withdraw money, the entire exchange will continue.

APIs are everywhere: from simple fork() in the operating system to complex APIs (such as Google Maps API), they are all here to make programmers easier.

What's in the bank

Let's look at our bank again.
How does the API work (novice teaching method)
You may have noticed that the bank has two parts: the front area, where customers line up in an orderly manner; the back area, where money is handled. In the middle counter, the front and rear areas are isolated. Interaction can only happen in the window (Sally) on the middle counter.

In API terminology, the middle area of ​​our city is Interface; this is where software components interact. In our bank, both the front and back office are aware of the existence of this place, and they all agree to exchange information here.

Now, suppose Bob comes to withdraw money. Bob said at the counter, "Hi, this is Bob, can I withdraw $500 from my account?" The
bank teller said, "Of course, please wait."

Lisa knew how to withdraw the money, and then she got the money and gave it to Bob, "This is your money, thank you, goodbye."
How does the API work (novice teaching method)
Once, Bob drank high and went to the bank again. He asked the teller Lisa "Curry Why has the 2-point shooting percentage increased to 59% this season?"

Lisa, who is a bank teller and doesn't watch basketball at all, has a dazed face.

In API terminology, a protocol is a set of rules that define how components interact with each other. Both parties must understand and adhere to the same communication agreement to succeed. In this case, the bank teller understands withdrawals and deposits, but she does not understand basketball.

Lisa and Bob communicate in Mandarin, which we call the format: it specifies how to encode the data to be sent to the other party. In other words, the communication format here is Mandarin. As with the agreement, both parties must understand and insist on this one. If Bob thinks his Cantonese is very cool, he says to Lisa, "I want to press five hundred mosquitoes to make a yelling" (I want to take out five hundred Block thanks). Because Lisa couldn't understand, she couldn't do anything, and the information exchange failed.

In the real world, common formats for Web API include XML and JSON. Although JSON is popular because it is lighter and easier to read than XML, XML still occupies an important position in the Java world, especially at the enterprise level (for example, in API for conversation in SOAP). For applications that need to exchange large amounts of data (especially multiplayer games), binary protocols such as ProtoBuf and MsgPack are often used to save space and improve encoding/decoding efficiency.

Finally, we assume that we also want to expand our business to the stock market. We need a special bank teller to handle stock market transactions. We call this new stock trader Tom:
How does the API work (novice teaching method)
In API terminology, API endpoints usually refer to service providers that provide a specific subset of functions in the same interface. In this case, Tom and Sally are both endpoints. Different endpoints can have different protocols and different formats.

To summarize: Interface is where different software components interact. A protocol is a set of rules that define how they interact, and a format defines how they talk to each other. Endpoints provide different functions within the same interface.

What else can the bank teller do

Now that we have introduced some basic concepts of the API, let's talk about some common functions of the API.
This time Bob came to withdraw money again, and he tried to withdraw $10,000.
How does the API work (novice teaching method)
Before withdrawing money to him, the teller will check his account for $10,000. The API can contain verification logic to ensure that all operations are legal.

It turns out that there is only $100 in Bob's account. We can ask the bank teller to tell him that he has insufficient funds. The API can have an error reporting mechanism to indicate errors that have occurred.

Bob thinks this must be a mistake, and asks the bank teller to give all the account documents in his name and how much money he has in each account. It turns out that Bob has 200 accounts. It is not very practical to give him one time, so the teller Sally showed 10 accounts at a time. When Bob finishes reading 10, he can continue to look at the next 10. This is the so-called paging and paging data set, which can save bandwidth and server resources because there is no need to get all the content in the data set at once. If Bob only wants to know the account balance, not how many bonus points the account has, he can ask Sally to display only the balance. This is called filtering, which helps save bandwidth and resources, and makes navigation easier.

After checking all the accounts, Bob found out that he did not have $10,000. But he knew that Alice had bought the stock and made a lot of money (Picture 6), so he left the bank, and after a while pretending to be Alice, he returned to the bank. He told the teller Sally, "I am Alice and I want to withdraw $10,000. ".

We asked Sally to verify the customer’s identity and bank card before withdrawing money. In this case, Bob did not have these proofs and could only leave the bank in a desperate manner. Authorization and access control can be built into an API to ensure that only authorized personnel can access specific data.

Finally, after failing to withdraw $10,000, Bob returned to the bank furiously, withdrawing only $0.01 each time (perhaps in revenge against Sally). If Sally did it, it would take time and effort. We can specify the frequency of withdrawing money. For example, we can only withdraw money once in 10 minutes. If Bob really wants to go to $0.01 each time, he will have to stay in the bank for a period of time. We can control the resource allocation of the server by limiting the speed to ensure that users will not abuse the service.

The API combined with the above functions can act as a firewall to protect resources from being misused while allowing legitimate requests.

The greater the function, the greater the responsibility

API is really good, but if it is not well designed, it will make developers feel uncomfortable. The following are some useful criteria I think when designing API:
Clear the role of each endpoint: Your endpoint should have a basic name, and Clear and concise.

The error should be clear and easy to understand: it is right to tell the customer that they do not have enough balance in the bank. Telling the customer that "error #506340" has occurred is confusing. Although it may be attractive to save a few hundred bytes of data by returning an error code, in fact, this will only hinder customers from choosing your bank;

Record everything: This is very important if you want your developers not to pull their hair out every time they encounter an error. Give them full support, clear and concise records.

Keep it the same: If some of the API endpoints are different from others, your users will go crazy with Google searches before the deadline (spray you by the way). Make sure your naming rules, error handling and other behaviors are consistent across all endpoints;

Hear more feedback: Think about how developers will use your API, and make sure it is as simple and intuitive as possible.

Recommended reading:

Carefully organized | 2017 second half of the article directory
Python learning mind map (with download address)
2018 May and June technical article directory (with all article directories)
Illustrating the sliding window and congestion window of TCP

Focus on server background technology stack knowledge summary sharing

Welcome to pay attention to communication and common progress

How does the API work (novice teaching method)

Coding

The code farmer has the right way to provide you with easy-to-understand technical articles to make technology easier!

Guess you like

Origin blog.51cto.com/15006953/2552118