Application Programming Interface (API) is a convention that provides specific business output capabilities and connects different systems. This includes the interaction points between external systems and systems that provide services (mid- and back-end systems) or between different back-end systems. Including external interfaces, internal interfaces, and internal interfaces include: upper-layer service and lower-layer service interfaces, and peer interfaces.
If you don't want to be regarded as a demand porter who doesn't understand anything in the eyes of technical bosses, it is necessary to have clear knowledge about interfaces.
Common web interfaces are http/https protocol interfaces, which are mostly used for calls to external systems or front-end systems. Because such interface addresses are exposed to the outside, the security of the interface must be verified to a high degree. There is also a cross-system interface calling interface solution based on open source RPC. This type is mainly used for mutual calls between systems in the intranet of large companies. This type of interface has stronger service management capabilities and faster interface response speed. The following content uses the http interface as an example to discuss.
1. Interface request method type
Common http request methods include: get (check), post (add), in addition to put (change), delete (delete), etc. The type of interface is determined by the business. For example, when you open Taobao, the displayed homepage content needs to use the get interface to obtain page information. If you want to place an order when you like a product, and add your harvest address, you use the post interface. These two are also the two most common interface types.
1) get type interface
Format: The request number parameter is written after the URL and connected with "?". Multiple parameters are connected with "&".
Scenario: The get interface is used to obtain information, and is mostly used to query data, such as menu list display, search display, order query, coupon query, etc. It is used when other systems need to return data. Generally, the amount of data requested is small and the return speed is fast, but the interface is exposed to the outside, so there is a certain risk.
2) post interface
Description: Submit data (such as submitting forms, uploading files) to the specified resource location to make a request. Post requests may lead to the creation of new resources.
Scenario: Functions such as registration, uploading, posting, etc. require a large amount of data and require high security.
Other interface types such as put (change), delete (deletion), patch, etc. have slightly lower usage ratings and will not be described here.
2. Interface response mechanism type
It is distinguished from the return, divided into synchronous interface and asynchronous interface.
1) Synchronous interaction
It means that when sending a request, you need to wait for the return before you can send the next request. There is a waiting process;
For example, in the login interface, when performing a login operation, the user name, password, token and other fields are encrypted and then verified through the interface. The verification result needs to be returned before the login can be successful.
2) Asynchronous interaction
It means sending a request without waiting for a return. You can send the next request at any time, that is, there is no need to wait.
If a user leads a coupon, it only needs to successfully request the user's coupon collection behavior. After receiving the request, the asset system asynchronously operates the user to issue coupons and executes coupon issuance through an asynchronous method. The caller does not need to wait for the call result of each request.
Difference: One requires waiting, and the other does not. As long as it does not affect the user experience, our project development generally gives priority to asynchronous interaction methods that do not require waiting.
In what situations is it recommended to use synchronous interaction? For example, user login, bank transfer system, database saving operation, etc. will all use synchronous interaction operations, and in other cases, asynchronous interaction will be used first.
3. Trigger form type of interface
1) Distribution interface
When a system generates new data, it is distributed to other systems (or multiple).
The core idea of the middle-end system is high cohesion and low coupling, so there are still many usage scenarios for distribution interfaces. For example, there is a main channel system to manage all channel data, and channel data is information that other systems such as product systems and promotion systems often use. Therefore, once a new channel appears or a channel change occurs, it needs to be distributed to all other connected systems to achieve functional support for the latest channel.
2) Subscription interface
A system calls the interface of other systems for data subscription when needed.
For example, when the order system generates an order, many external systems may need to obtain order status information in a timely manner. The order system does not know which systems to distribute to. At this time, the order is generally pushed to a specific message queue, such as KFK. Other systems that need to follow up on the order status can obtain the order completion information immediately after subscribing to the KFK message. Proceed triggers the next action.
4. Basic composition of other API interfaces
Under a given business, after the interface request type, response mechanism, etc. are determined, take the product details interface of the e-commerce data platform as an example to understand the other components of the interface.
1) Application scenario
As the name suggests, this interface is suitable for scenarios that clarify the business purpose of the interface.
- Product recommendation: Recommend related products to users by analyzing users’ purchase history and behavior data to improve sales conversion rate.
- Price analysis: Develop reasonable pricing strategies by analyzing product prices of competitors and the same industry.
- Inventory management: Product selection and inventory management can be carried out based on the sales of goods to ensure sufficient supply of goods and reduce risks such as inventory backlog.
- User portrait: By analyzing user purchase history and behavioral data, the user's interests, preferences and consumption habits are revealed, providing a basis for precision marketing.
- Marketing activities: Based on product data, appropriate promotion plans can be developed to attract users to purchase and increase sales and customer loyalty.
- Customer service: Use product data to conduct customer feedback analysis, understand users’ questions and opinions about products, respond to user needs and problems in a timely manner, and improve customer satisfaction.
People who use API interfaces are divided into the following categories:
Developers: API interfaces provide a convenient way for developers to leverage the functionality of other systems or platforms to build their own applications or websites.
Data Analyst: Data analysts need to collect data from multiple platforms or systems, and API interfaces provide them with a way to quickly obtain data.
Business users: Business users can use API interfaces to integrate transaction information on different platforms to monitor and manage product inventory, market sales and other information.
System administrator: System administrators can use API interfaces to monitor and manage the running status of the system so that problems can be discovered and solved in a timely manner.
2) Input and output
response parameters
name | type | must | Example value | describe |
---|---|---|---|---|
item |
item[] | 1 | Baby details data | |
num_id |
Bigint | 1 | 520813250866 | Baby ID |
title |
String | 1 | Three-blade wooden folding knife that passes security inspection, creative mini keychain, key knife, saber, portable multifunctional knife, free shipping | baby title |
desc_short |
String | 0 | Product Description | |
promotion_price |
Int | 0 | Special price | |
price |
Float | 1 | 25.8 | price |
total_price |
Float | 0 | 0 | |
suggestive_price |
Float | 0 | 0 | |
orginal_price |
String | 0 | 25.80 | original price |
nick |
String | 0 | Happy Shopping Inn | Shopkeeper's nickname |
num |
Int | 0 | 3836 | in stock |
my_num |
Int | 0 | 0 | Minimum purchase quantity |
detail_url |
String | 0 | http://item.taobao.com/item.htm?id=520813250866 | baby link |
pic_url |
String | 1 | //gd2.alicdn.com/imgextra/i4/2596264565/TB2p30elFXXXXXQXpXXXXXXXXXX_!!2596264565.jpg | baby pictures |
brand |
String | 0 | three-blade tree | brand name |
brandId |
Int | 0 | 8879363 | Brand ID |
rootCatId |
Int | 0 | 50013886 | Top level category ID |
cid |
Int | 1 | 50014822 | |
crumbs |
Mix | 0 | [] | Navigation menu |
created_time |
String | 0 | ||
modified_time |
String | 0 | ||
delist_time |
String | 0 | ||
desc |
String | 0 | product details | |
desc_img |
Mix | 0 | [] | Product details pictures |
item_imgs |
Mix | 0 | item_imgs[] | product picture |
item_weight |
String | 0 | ||
item_size |
String | 0 | ||
location |
String | 0 | Place of shipment | |
express_fee |
Float | 0 | 0.00 | Courier fees |
ems_fee |
Float | 0 | EMS cost | |
post_fee |
Float | 0 | Logistics costs | |
shipping_to |
String | 0 | Ship to | |
has_discount |
Boolean | 0 | false | Is there any discount? |
video |
video[] | 0 | Product video | |
is_virtual |
String | 0 | ||
is_promotion |
Boolean | 0 | false | Promotion or not |
props_name |
String | 0 | 1627207:1347647754: Color classification: Rectangular with bottle opener + tool knife card + chain; 1627207: 1347647753: Color classification: Oval with bottle opener + tool knife card + chain; | Product attribute name. The format is pid1:vid1:name1:value1;pid1:vid2:name2:value2. |
prop_imgs |
prop_imgs[] | 0 | Product attribute picture list | |
property_alias |
String | 0 | 20509:9974422:36;1627207:28326:red;20509:9975710:38;1627207:28326:red;20509:9981357:40;1627207:28326:red | Sales attribute value alias. The format is pid1:vid1:alias1;pid1:vid2:alia2. |
props |
Mix | 0 | [{ "name": "Origin", "value": "China" }] | Product attributes |
total_sold |
Int | 0 | ||
skus |
skus[] | 0 | Product specification information list | |
seller_id |
Int | 0 | 2844096782 | Seller ID |
sales |
Int | 0 | 138 | Sales volume |
shop_id |
Int | 0 | 151372205 | Store ID |
props_list |
Mix | 0 | {20509:9974422: Size:36} | Product attributes |
seller_info |
seller_info[] | 1 | 卖家信息 | |
tmall |
Boolean | 0 | false | 是否天猫 |
error |
String | 0 | 错误信息 | |
warning |
String | 0 | 警告信息 | |
url_log |
Mix | 0 | [] | |
favcount |
Int | 0 | 0 | |
fanscount |
Int | 0 | 0 | |
method |
String | 0 | item_tmall:pget_item | |
promo_type |
String | 0 | ||
props_img |
Mix | 0 | 1627207:28326": "//img.alicdn.com/imgextra/i2/2844096782/O1CN01VrjpXt1zyCc9DvERE_!!2844096782.jpg | 属性图片 |
shop_item |
Mix | 0 | [] | |
relate_items |
Mix | 0 | [] |
入参是接口请求所需要的变量参数,其中包括必填参数和非必填参数,非必填并非是可以忽略的。
3)错误码
接口请求并非每次都能成功,所以在接口开发时会对可能失败的情况进行错误码区分,在接口联调时可以根据返回的错误码快递定位问题。如果错误码不够全面,那在接口调用失败的时候,需要反复定位,降低开发效率。
错误码解释
状态代码(error_code) | 状态信息 | 详细描述 | 是否收费 |
---|---|---|---|
0000 | success | 接口调用成功并返回相关数据 | 是 |
2000 | Search success but no result | 接口访问成功,但是搜索没有结果 | 是 |
4000 | Server internal error | 服务器内部错误 | 否 |
4001 | Network error | 网络错误 | 否 |
4002 | Target server error | 目标服务器错误 | 否 |
4003 | Param error | 用户输入参数错误 | 忽略 |
4004 | Account not found | 用户帐号不存在 | 忽略 |
4005 | Invalid authentication credentials | 授权失败 | 忽略 |
4006 | API stopped | 您的当前API已停用 | 忽略 |
4007 | Account stopped | 您的账户已停用 | 忽略 |
4008 | API rate limit exceeded | 并发已达上限 | 忽略 |
4009 | API maintenance | API维护中 | 忽略 |
4010 | API not found with these values | API不存在 | 忽略 |
4012 | Please add api first | 请先添加api | 忽略 |
4013 | Number of calls exceeded | 调用次数超限 | 忽略 |
4014 | Missing url param | 参数缺失 | 忽略 |
4015 | Wrong pageToken | 参数pageToken有误 | 忽略 |
4016 | Insufficient balance | 余额不足 | 忽略 |
4017 | timeout error | 请求超时 | 否 |
5000 | unknown error | 未知错误 | 否 |
五、接口安全性校验
接口完成业务逻辑开发后,接下来要考虑的就是安全性问题了,接口的安全性问题主要来源于几方面考虑:
1)请求来源是否合法?
即接口的伪装攻击,因为接口是对外的,在公网环境中,接口地址是暴露的,收到的请求有可能是恶意非法请求;如果真的是合法请求,也需要知道这个请求的来源,同时这个请求来源不能否认。这里引入“签名”的概念,以及签名的防伪装及抗否认性特性。
近些年各大企业强制使用https替换掉原有的http接口,正是因为https所使用的的证书安全性更高。
2)请求是否会被篡改,返回数据可能会被截取
因为接口是对外的,所以接收请求和返回数据的时候,是不可能使用明文方式传输的,否则一旦被恶意截取,会造成极大风险。所以请求数据及返回数据都是需要加密的,这样即使数据被截取,也不用泄露数据的内容。
3)如何防范接口的重放攻击,防重放攻击是什么呢?
就是把你的请求原封不动地多次发放,请求都会通过验证进入到正常逻辑中,会造成服务端接口拥堵并且会造成实际损失。
防重放一般需在请求参数加上 时间戳 + 随机数,通过时间戳确保接口是最新的请求,而随机数相同则可以认定为是重放攻击。
六、接口性能相关
如果是访问量比较大的接口,再上线前肯定需要进行压力测试。因为普通的开发自测和生产模拟是不能推算出高并发时候接口是否可正常运行。
1)TPS
Transaction Per Second 每秒系统处理的交易或事物的数量,衡量系统处理能力的重要指标。
2)RT
Response time, the time elapsed from the time the client sends a request to the end when the client receives the response result returned from the server, includes three parts: request sending time, network transmission time and server processing time.
3) Throughput
Refers to the total amount of data transmitted on the network during a performance test.
Needless to say, the user's response time is too long and hurts the user experience. Even in a period of high concurrency, the user's response time still needs to be controlled to a minimum, generally no more than 5 seconds;
TPS is an indicator of high concurrency. The interfaces that generally provide services need to take into account the number of concurrencies in the most extreme situations. These numbers generally come from operational activity planning and past data trend estimates. Based on this, you can ensure that you The interface can support the highest number of concurrencies, and stress testing is generally used to verify these. If under normal circumstances the tps can reach 2000 during the stress test and the interface is normal, the actual concurrency of 2000 can be guaranteed.
7. What tests need to be done on the interface?
Interface testing is actually a white-box test. The homepage must clarify the system's capability output and whether the service coverage meets the needs. Use business logic to push interface parameters.
1) If the input parameters do not meet the requirements, clear error codes, error messages and logs are required to facilitate problem reproduction and location.
2) If there is another link to the parameter processing logic, it also needs to be verified. For example, if you purchase a NetEase Cloud Music membership, the order will be weighted by the equity system after the order is generated. After the weighting is successful, a text message will notify the user, but the weighting interface and order information will There is no user mobile phone number, so although there is no user mobile phone number in the input parameter, it is necessary to query the mobile phone number based on the user's username and perform the operation of sending text messages.
Other verification objectives such as: whether the code coverage meets the requirements, whether the performance indicators meet the requirements, and whether the security indicators meet the requirements are more professional test indicators.