Detailed explanation of api interface (it is enough to read this article)

A detailed explanation of the api interface? Excellent design is the reason why the product becomes excellent. Designing an API means providing an effective interface that can help API users better understand, use, and integrate, while helping people maintain it effectively. Every product needs Manuals, APIs are no exception In the world of APIs, design can be modeled as an agreement between server and client API agreements help internal and external stakeholders understand what should be done, and how to work better together To build an excellent API, today I will talk about the detailed explanation of the api interface? Next, let's study it together !

Detailed explanation of api interface

Good design is what makes a product great. Designing an API means providing an effective interface that can help API consumers better understand, use, and integrate, while helping people maintain it efficiently. Every product needs a manual, and APIs are no exception. In the world of APIs, design can be modeled as an agreement between server and client. An API agreement helps internal and external stakeholders understand what should be done and how to better work together to build a great API.

1. API interface 1. What is an API interface

The application programming interface (Application Programming Interface, API interface) is an important part of the application program, that is, the application program provides an entry for operating data. This entry can be a function or class method, or a url address or a network address. When the client calls this entry, the application will execute the corresponding code operation to complete the corresponding functions for the client.

2. API interface type

At present, the interface implementation specifications used by developers of most companies on the market mainly include: restful and RPC.

RPC (Remote Procedure Call) : Translated into Chinese: Remote Procedure Call [Remote Service Call]. Literally, it means accessing/calling the API interface provided by the remote server. This interface is typically provided as a service or procedural code.

  • The server provides a unique access entry address: http://api.xxx.com/ or http://www.xx.com/api

  • When the client requests the server, all operations are understood as actions. In general web development, it corresponds to the post request of the HTTP request.

  • Through the request body parameters, specify the name of the interface to be called and the parameters required by the interface action=get_all_student&class=301&sex=1m=get_all_student&sex=1&age=22&command=100&sex=1&age=22

    There are too many interfaces, corresponding to more function names and parameters, and the front end is difficult to find when requesting the API interface. Duplicate interfaces are prone to appear

    RESTful:  translated into Chinese: resource state transition. (representational state transition)

    All the data/files provided by the server are regarded as resources, then the operation of requesting data through the API interface is essentially the operation of resources. Therefore, Restful requires that we provide external resources for the current interface. Operation, write the name of the resource in the url address.

    The most common and common way to operate resources in web development is nothing more than adding, deleting, checking and modifying, so restful requires declaring in the address bar what resources are to be operated. Then use the http request verb to indicate which operation to perform on the resource. POST http://www.xxx.com/api/students/ Add student data GET http://www.xxx.com/api/students/ Get all students DELETE http://www.xxx.com/api/students /<pk>/ Delete a student with id=pk PUT http://www.xxx.com/api/students/<pk>/ Modify all information of a student [id, name, sex, age,] PATCH http: //www.xxx.com/api/students/<pk>/ Modify part of a student's information [age]

    In other words, we only need to combine the resource name on the url address with the HTTP request action to explain what the function of the current api interface is.

    Restful is an api interface specification based on resources, which is reflected in the address that resources are expressed in nouns. RPC is an action-based api interface specification, which is reflected in the action of manipulating data often attached to the interface name.

    3. Why write interface documents

    In order to form a consensus within the team and prevent confusion caused by differences in personal habits, we all need to find an interface implementation specification that everyone thinks is good, and this specification can make the interface written by the backend clear at a glance, reducing the need for clients and The cooperation cost between the two parties on the server side. Because the content contained in the interface is relatively detailed, it is often necessary to use the interface document in the project. R&D personnel can develop and collaborate according to the interface documents, testers can conduct tests according to the interface documents, and the system also needs to refer to the interface documents for maintenance.

    2. API Interface Specification 1. Protocol

    The communication protocol between the API and the client user is recommended to use the http protocol, which is also compatible with HTTP to ensure the security of the transmission of interactive data.

    2. Domain name

    The API should be deployed under a dedicated domain name as much as possible. http://api.xxx.com

    If it is determined that the API is very simple and there will be no further expansion, it can be considered to be placed under the main domain name. http://www.xxx.com/api/

    3. Version (Versioning)

    It is recommended to put the version number of the API into the URL.

    http://api.xxx.com/app/v1.0/foohttp://api.xxx.com/app/v1.1/foohttp://api.xxx.com/app/v2.0/foo

    Another way is to put the version number in the HTTP header information, but it is not as convenient and intuitive as putting it in the URL.

    Version number specification: 1) Adopt the method of multi-version coexistence and incremental release. 2) The version number can be divided into integer and floating-point type. v2.2...

    Regarding version compatibility, minor version changes are backward compatible, as long as the major version does not change. 3) For an API or service, you should keep at most 3 most detailed versions in production

    4. Path (Endpoint)

    The path, also known as "endpoint", indicates the specific URL of the API, and each URL represents a resource (resource)

    Interface naming should be a verb-object structure, composed of verbs and nouns, using camel case naming conventions, for example:

    product/v1.0/getProducts get product order/v1.1/saveOrder save order

    Common common verbs for interface naming can be referred to as follows:

    action

    prefix

    Remark

    Obtain

    get

    get{XXX}

    Obtain

    get

    get{XXX}List

    Add

    add

    add{XXX}

    Revise

    update

    update{XXX}

    keep

    save

    save{XXX}

    delete

    delete

    delete{XXX}

    upload

    upload

    upload{XXX}

    send

    send

    send{XXX}

    5. Basic Specifications 5.1 Request Parameters

    The public parameter is a parameter that must be carried by each interface, describes the basic information of each interface, and is used for statistics or other purposes, and is placed in the Header or url parameter.

    The parameter after Query url? stores the parameter data of the request interface.

    Header request header, which stores the following public parameters, APP-side public parameters, etc., and can also store some special encrypted fields.

    Body Body, which stores the parameter data of the request interface.

    Public parameters:

    parameter

    illustrate

    Remark

    app_id

    Uniquely identifies the user ID

    app_id is globally unique, each app_id will correspond to a customer

    app_key

    encryption key

    app_key is used for parameter signature and can be understood as an encrypted salt value. Note that app_key is saved to the client and does not need to be passed as a parameter. Some security processing is required to prevent leakage.

    timestamp

    timestamp

    The timestamp is the current timestamp corresponding to when the client calls the interface, and the timestamp is used to prevent DoS attacks. When a hacker hijacks the requested url to do a DoS attack, every time the interface is called, the interface will judge the difference between the server's current system time and the timestamp transmitted in the interface. If the difference exceeds a certain set time (for example, 5 minutes), Then this request will be intercepted. If it is within the set timeout period, the DoS attack cannot be prevented. The timestamp mechanism can only reduce the time of DoS attacks and shorten the attack time. If a hacker modifies the value of the timestamp, it can be handled through the sign signature mechanism.

    request_id

    Request ID

    The user request ID is a value randomly generated by the client. To ensure global uniqueness, you can refer to the snowflake algorithm and pass it as a parameter. The purpose of adding request_id is to increase the variability of the sign signature on the one hand, and to prevent replay on the other hand. Attacks can also be used as a means of full link tracking and troubleshooting.

    sign

    sign

    It is generally used for parameter signature to prevent parameters from being illegally tampered with. The most common is to modify important sensitive parameters such as the amount. The value of sign is generally to sort all non-empty parameters in ascending order and then splicing token app_key timestamp request_id together, and then use some kind of The encryption algorithm is used to encrypt and pass it as a parameter sign in the interface, or put the sign in the request header. If the interface is hijacked by a hacker during the network transmission process and modifies the parameter value, and then continues to call the interface, although the parameter value is modified, the hacker does not know how the sign is calculated, and does not know what the sign is. Value composition, I don’t know in what order they are spliced ​​together. The most important thing is that I don’t know what the app_key in the signature string is, so hackers can tamper with the value of the parameter, but they can’t modify the value of sign. When the server calls the interface The value of sign will be recalculated according to the rules of sign and then compared with the value of the sign parameter passed by the interface. If they are equal, it means that the parameter value has not been tampered with. If not, it means that the parameter has been illegally tampered with, and the interface will not be executed.

    token

    Unique credentials for system calls

    Access token access token, used in the interface, is used to identify the identity and credentials of the interface caller, and reduce the number of transmissions of user names and passwords. In general, the client (interface caller) needs to apply to the server for an account to call the interface. The server will give an app_id and an app_key, and the app_key is used for parameter signature. Note that the app_key is saved to the client, and some security needs to be done. Handle to prevent leakage.

    The value of Token is generally UUID. After the server generates the Token, it needs to use the token as a key, and save some information associated with the token as a value in the cache server (redis). When a request comes, the server will go to the cache server to query Whether the Token exists, if it exists, call the interface, if there is no return interface error, it is generally implemented through an interceptor or filter.

    Generally, the four parameters of token, timestamp, request_id and sign will be passed as parameters in the interface at the same time. Each parameter has its own purpose. Among them, app_id, timestamp, request_id and sign are required to obtain the token for the first time. After the client obtains the token, it will no longer Need to pass app_id. The APP side requests public parameters

    In addition to the above public parameters, the APP request parameters also require the following additional public parameters:

    parameter

    illustrate

    Remark

    network

    network

    WIFI、4G

    operator

    operator

    China Unicom/Mobile

    platform

    platform

    iOS、Android

    system

    system

    ios 13.3、android 9

    device

    Device model

    iPhone XR, Mi 9

    udid

    Equipment Uniquely Identified

    Filter parameters:

    If the number of records is large, it is impossible for the server to return all records to the user. The API should provide paging parameters and other filtering parameters to filter the returned results.

    Examples of parameters are as follows limit=10: specifies the number of returned records offset=10: specifies the starting position of returned records. page=2&per_page=100: Specify the page number and the number of records per page. sort_by=name&order=asc: Specifies which attribute the returned results are sorted by, and the sort order.

    Notice:

    1)上传/下载上传/下载,参数增加文件md5,用于完整性校验(传输过程可能丢失数据)。2)避免精度丢失缩小单位保存数据,如:钱以分为单位、距离以米为单位。

    5.2 响应数据

    为了方便给客户端响应,响应数据会包含三个属性,状态码(code),信息描述(message),响应数据(data)。客户端根据状态码及信息描述可快速知道接口,如果状态码返回成功,再开始处理数据。array类型数据。通过list字段,保证data的Object结构。

    返回示例:

    { code: “SUCCESS”, // 返回码, 详情后面的【接口返回码】部分会说 data: {} , // 数据 message: “成功” // 存放响应信息提示,显示给客户端用户【须语义化中文提示】 }

    分页类型数据。返回总条数,用于判断是否可以加载更多。返回示例:

    { code: “SUCCESS”, data: { "list":[] "total":10 }, // 数据, message: “成功” }

    响应状态码code统一使用英文组合字符串,多层分级使用“.”分隔,例如:PARAMETER.ILLEGALL

    PARAMETER.ILLEGALL代表参数错误,不推荐使用数字,数字错误码可读性太差。

    注意:1)返回属性名命名时,建议使用驼峰命名,首字母小写。2)返回属性值为空时,严格按类型返回默认值。3)返回金额类型/时间日期类型的属性值,如果仅用来显示,建议后端返回可以显示的字符串。4)返回业务逻辑的状态码和对应的文案,建议后端两者都返回,中间添加“|”分隔,例如“SUCCESS|成功”,SUCCESS表示接口状态成功,显示给客户表示“成功”。5)调用方不需要的属性,不要返回。

    5.3使用GET/POST作为接口请求方式

    一般调用接口最常用的两种方式就是GET和POST。两者的区别也很明显,GET请求会将参数暴露在浏览器URL中,而且对长度也有限制。为了更高的安全性,所有接口都采用POST方式请求。另外不推荐使用rest的PUT和DELETE,因为很多浏览器不支持,很多框架也不支持。

    我们这里用的的GET和POST同RESTFul中的GET、POST是不一样的。通常使用GET、POST的选择点在于,简单的用GET、复杂对象用POST,并没有动作的含义,例如我也可以使用get来执行添加的动作,如果参数很多,我也可以使用POST来执行查询操作;但在REST里,GET对应的是查询一个资源,而POST对应的是新增一个资源,意义是决然不同的。理解这一点非常重要。

    5.4返回格式

    返回响应数据采用JSON,不推荐使用XML,XML是W3C为了替换HTML研发出来的,但是现在很明显失败了。默认情况下要支持gzip

    三、接口安全规范3.1安全设计规范

    获取token一般会涉及到几个参数app_id,app_key,timestamp,request_id,sign。我们通过以上几个参数来获取调用系统的凭证。

  • app_id和app_key可以直接通过平台线上申请,也可以线下直接颁发。app_id是全局唯一的,每个app_id将对应一个客户,app_key需要客户端高度保密。

  • timestamp是时间戳,使用系统当前的unix时间戳。时间戳的目的就是为了减轻DDOS的攻击。防止请求被拦截后一直尝试请求接口。服务器端设置时间戳阀值,如果请求时间戳和服务器时间超过阀值,则响应失败。

  • request_id是随机值。随机值主要是为了增加sign的多变性,也可以保护接口的幂等性,相邻的两次请求reqeust_id不允许重复,如果重复则认为是重复提交,响应失败。

  • sign是参数签名,将所有非空参数按照升续排序、app_key、timestamp、reqeust_id拼接起来进行md5加密(当然使用其他方式进行不可逆加密也没问题)。

    token作为系统调用的唯一凭证,token可以设置一次有效,也可以设置时效性,这里推荐设置时效性。如果一次有效的话这个接口的请求频率可能会很高。token推荐加到请求头上,这样可以跟业务参数完全区分开来。

    这里面主要涉及到sign签名设计规范和token生成规范,需要遵守如上规范,能够保证API接口的安全性和幂等性。

    3.2客户端IP白名单

    ip白名单是指将接口的访问权限对部分ip进行开放。这样就能避免其他ip进行访问,设置ip白名单比较麻烦的一点就是当你的客户端进行迁移后,就需要重新联系服务提供者添加新的ip白名单。设置ip白名单的方式很多,除了传统的防火墙之外,spring cloud alibaba提供的组件sentinel也支持白名单设置。为了降低api的复杂度,推荐使用防火墙规则进行白名单设置或者在API网关层面设置IP白名单,比如shenyu网关支持IP白名单设置。

    3.3单个接口针对ip限流

    限流是为了更好的维护系统稳定性。使用redis进行接口调用次数统计,ip 接口地址作为key,访问次数作为value,每次请求value 1,设置过期时长来限制接口的调用频率。不过这里还是推荐在网关层面进行设置,比如shenyu网关支持IP限流。

    3.4敏感数据加密与脱敏

    参数安全:登录密码、支付密码,需加密后传输,建议使用非对称加密

    响应结果:用户手机号、用户邮箱、身份证号、支付账号、邮寄地址等要进行脱敏,部分数据加 * 号处理。

    在接口调用过程中数据通常需要脱敏安全处理,最常用的方式就是加密。加密方式使用安全性比较高的RSA非对称加密。非对称加密算法有两个密钥,这两个密钥完全不同但又完全匹配。只有使用匹配的一对公钥和私钥,才能完成对明文的加密和解密过程。

    四、API接口幂等性

    幂等性是指任意多次请求的执行结果和一次请求的执行结果所产生的影响相同。说的直白一点就是查询操作无论查询多少次都不会影响数据本身,因此查询操作本身就是幂等的。但是新增操作,每执行一次数据库就会发生变化,所以它是非幂等的。

    我们无法保证接口的每一次调用都是有返回结果的,要考虑到出现网络异常的情况。举个例子,订单创建时,我们需要去减库存,这时接口发生了超时,调用方进行了重试,这时是否会多扣一次库存?

    对于一些重要的操作需要防止客户端重复提交的(如非幂等性重要操作),具体办法是当请求第一次提交时将request_id作为key保存到redis,相应的返回结果集作为value存储到redis,并设置超时时间。当同一个请求第二次访问时会先检测redis是否存在该request_id,如果存在则证明重复提交了,接口直接返回不再继续调用了。

    五、API调用流程

    1.接口调用方(客户端)向接口提供方(服务器)申请接口调用账号,申请成功后,接口提供方会给接口调用方一个app_id和app_key

    2.客户端携带参数app_id、timestamp、request_id、sign去调用服务器端的API token,其中sign=加密(app_id timestamp request_id app_key)

    3.使用参数app_id,timestamp,request_id,sign来获取token,token作为系统调用的唯一凭证

    4.客户端拿着token 去访问相应的接口

    5.如果token过期需要获取刷新token

    sign的作用是防止参数被篡改,客户端调用服务端时需要传递sign参数,服务器响应客户端时也可以返回一个sign用于客户端校验返回的值是否被非法篡改了。

    六、接口文档

    1、尽量采用自动化接口文档,可以做到在线测试,同步更新,推荐使用swagger、yapi。2、应包含:接口BASE地址、接口版本、接口模块分类等。3、每个接口应包含:接口地址:不包含接口BASE地址。请求方式: GET、POST。请求参数:数据格式【默认JSON、可选form data】、数据类型、是否必填、中文描述。响应参数:类型、中文描述。

    七、总结

    关于限流设计、熔断设计、降级设计,目前主流网关都有相关功能(比如shenyu网关),可以不在API实现中开发这些功能。

    In addition, it is recommended to store API-related logs on the log platform, which is conducive to fault location, log statistical analysis, and interface monitoring. The building of the log platform can use ELK components, use Logstash to collect log files, use Elasticsearch engine to search and analyze, and finally display them on the Kibana platform.

Guess you like

Origin blog.csdn.net/Noah_ZX/article/details/128953826