First, excellent interface design

In daily development, there are always interfaces to work with. Front-end and back-end data transmission interfaces and third-party service platform interfaces. The data transmission interfaces at the front and back ends of a platform generally communicate in the Intranet environment and use a security framework, so the security is well protected. This article focuses on how to design business interfaces for third-party platforms. What questions should we consider?

Mainly from the above three aspects to design a safe API interface.

1.1 Security Issues

Security is a specification that interfaces must guarantee. If an interface is not secure, your interface is exposed to the public network.

1.1.1 Prerequisite for calling the interface – Token

Obtaining the token generally involves several parameters appID, AppKey, TIMESTAMP, nonce and sign. We use the above parameters to get the credentials to call the system.

Appid and AppKey can be directly applied for online or issued offline. Appids are globally unique, each appID will correspond to a customer, and appkeys need to be highly confidential.

Timestamp is a timestamp, using the system’s current Unix timestamp. The purpose of timestamps is to mitigate DOS attacks. Prevents attempts to request the interface after a request has been intercepted. The server side sets the timestamp threshold, and if the request timestamp and server time exceed the threshold, the response fails.

Nonce is a random value. The random value is mainly to increase the variability of sign and protect the idempotency of the interface. The nonce of two adjacent requests is not allowed to repeat. If the request repeats, it is considered as repeated submission and the response fails.

Sign is a parameter signature that combines appkey, TIMESTAMP, and nonce for MD5 encryption (of course, irreversible encryption using other methods is also ok).

Token, using parameters appID, TIMESTAMP, nonce, sign to obtain the token, as the unique credentials of the system call. Tokens can be set to be valid once (for greater security), or they can be set to be time-limited, which is recommended. The frequency of requests to this interface may be high if it is valid once. The token is recommended to be added to the request head so that it can be completely separated from the business parameters.

1.1.2 Using POST as the Interface Request Mode

The two most common ways to invoke interfaces in general are GET and POST. The difference is also obvious, as GET requests expose parameters in the browser URL and have a limit on length. For higher security, all interfaces request through POST.

1.1.3 Whitelist of Client IP addresses

The IP address whitelist allows the access permission of an interface to some IP addresses. In this way, other IP addresses can be used to prevent access attacks. The tricky part of setting an IP address whitelist is that after the client is migrated, you need to contact the service provider to add a new IP address whitelist. There are many ways to set IP whitelists. In addition to traditional firewalls, Sentinel, a component provided by Spring Cloud Alibaba, also supports whitelisting Settings. To reduce API complexity, you are advised to use firewall rules to set whitelists.

1.1.4 Traffic Limiting for a Single Interface

Current limiting is to better maintain system stability. Redis is used to count the number of interface calls, with IP + interface address as key, access times as value, and value+1 for each request. The expiration period is set to limit the call frequency of the interface.

1.5 Recording Interface Request Logs

Use AOP global request log, quickly locate abnormal request location, troubleshoot the cause of the problem.

1.1.6 Desensitization of sensitive data

In the process of interface invocation, sensitive data such as order number may be involved. Such data usually needs desensitization, and encryption is the most commonly used method. The encryption mode is RSA asymmetric encryption with high security. Asymmetric encryption algorithms have two keys that are completely different but exactly match. Only a matching pair of public and private keys can be used to encrypt and decrypt plaintext.

1.2 Idempotence problem

Idempotent means that the execution result of any number of requests has the same effect as the execution result of a single request. To put it bluntly, the query operation does not affect the data itself no matter how many times it is queried, so the query operation itself is idempotent. But the database changes every time a new operation is performed, so it’s nonidempotent.

There are many ways to solve idempotent problems, and here is a more rigorous one. Provides an interface for generating random numbers, which are globally unique. Call the interface with a random number. When the service is successfully processed for the first time, the random number is used as the key, the operation result is used as the value, and the redis is saved. At the same time, the expiration time is set. The second call, which queries redis, returns an error if the key is present.

1.3 Data specification issues

1.3.1 Version Control

A mature set of API documentation, once published, does not allow arbitrary modification of the interface. If you want to add or modify an interface, you need to add version control. The version number can be an integer or a floating-point number. Generally, the interface address contains the version number, http://ip:port//v1/list.

1.3.2 Response status code specification

A great API, but also to provide a simple response value, based on the status code to roughly know what the problem is. We use the HTTP status code for data encapsulation, for example, 200 indicates that the request is successful, 4xx indicates that the client error, 5xx indicates that the server internal error. The status code design reference is as follows:

classification describe
1xx Message, the server receives the request and requires the requester to proceed with the operation
2xx successful
3xx Redirect, requiring further action to complete the request
4xx Client error, request contains syntax error or request cannot be completed
5xx Server error

Status code enumeration class:

public enum CodeEnum {

    // Add them based on service requirements
    SUCCESS(200."Processed successfully"),
    ERROR_PATH(404."Requested address error"),
    ERROR_SERVER(505."Server internal error");
    
    private int code;
    private String message;
    
    CodeEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode(a) {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage(a) {
        return message;
    }

    public void setMessage(String message) {
        this.message = message; }}Copy the code

1.3.3 Unified Response data format

In order to facilitate the response to the client, the response data will contain three attributes: status code, message description and response data. The client can quickly know the interface based on the status code and information description. If the status code is returned successfully, the client can process data again.

Definition of response results and common methods:

public class R implements Serializable {

    private static final long serialVersionUID = 793034041048451317L;

    private int code;
    private String message;
    private Object data = null;

    public int getCode(a) {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage(a) {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData(a) {
        return data;
    }

    /** * puts the response enumeration */
    public R fillCode(CodeEnum codeEnum){
        this.setCode(codeEnum.getCode());
        this.setMessage(codeEnum.getMessage());
        return this;
    }

    /** * Insert the response code and information */
    public R fillCode(int code, String message){
        this.setCode(code);
        this.setMessage(message);
        return this;
    }

    /** * Successfully processed, put into the custom business data set */
    public R fillData(Object data) {
        this.setCode(CodeEnum.SUCCESS.getCode());
        this.setMessage(CodeEnum.SUCCESS.getMessage());
        this.data = data;
        return this; }}Copy the code

1.4 Summary of interface design

This article discusses API design specifications in terms of security, idempotency, and data specifications. In addition, a good API also requires good interface documentation. The readability of interface documentation is very important, even though many programmers don’t like to document and don’t like people to document. In order not to increase programmer pressure, it is recommended to use Swagger or other interface management tools. With simple configuration, interface connectivity can be tested during development and offline documents can be generated for API management.

Recommend some excellent online document generation tools

Some excellent online documents, interface documents generation tools, to meet the following conditions:

  1. Must be open source
  2. Ability to generate online documents in real time
  3. Support full text search
  4. Supports online debugging
  5. Beautiful interface

Some online interface documentation tools that meet the above criteria are recommended here.

2.1 Knife4j

Gitee address: gitee.com/xiaoym/knif… Open source License: Apache-2.0 License

Recommend index: u u u u sample address: swagger-bootstrap-ui.xiaominfo.com/doc.html

Knife4j is an enhanced solution to generate Api documentation for Java MVC framework integration with Swagger. Formerly swagger-Bootstrap-UI, KNI4j was named for being as small, lightweight, and powerful as a dagger.

  • Advantages: Generate real-time online documents based on Swagger, support online debugging, global parameters, internationalization, access control, etc., very powerful.

  • Cons: The interface is a bit ugly and relies on extra JAR packages

  • Personal advice: If your company is not too UI demanding, you can use this document generation tool, the comparison function is quite powerful.

2.2 smartdoc

Gitee address: gitee.com/smart-doc-t… Open source License: Apache-2.0 License

Users: Xiaomi, IFLYtek, 1 + recommended index: ★★★★

Example:

Smart-doc is a Java restful API document generation tool. Smart-doc subverts the traditional implementation of swagger, which uses extensive annotation intrusion to generate documents. Smart-doc generates the interface document entirely based on the source code analysis of the interface, completely without annotation intrusion, just need to write according to the Java standard annotation can get a standard Markdown interface document.

  • Advantages: generate interface documents based on interface source code analysis, zero annotation invasion, support HTML, PDF, Markdown format file export.

  • Disadvantages: Additional JAR packages need to be introduced and no online debugging is supported

  • Personal advice: Use this if you are generating documentation in real time but don’t want to add extra annotations, such as @API, @APIModel, etc., to use Swagger.

2.3 redoc

Github address: github.com/Redocly/red… Open source License: MIT License

★★★ ★★★ ★★★

Example:

Redoc itself claims to be one of the best documentation tools available online. It supports Swagger interface data, provides multiple ways to generate documents, and is very easy to deploy. Use Redoc-CLI to bundle your documents into a zero-dependency HTML file with a responsive three-panel design with menu/scroll synchronization.

  • Advantages: Very easy to generate documents, three panel design

  • Disadvantages: Does not support Chinese search, including the common version and paid version. The common version does not support online debugging. In addition, UI interaction is not suitable for the operation habits of most domestic programmers.

  • Personal tip: Use this if you want to build a Swagger based document quickly and don’t require online debugging.

2.4 yapi

Github address: github.com/YMFE/yapi Open-source protocol: Apache-2.0 License

Users: Tencent, Ali, Baidu, JINGdong and other large factories recommended index: ★★★★★ ★

Example:

Yapi is independently developed and open source by qunar’s front end team and mainly supports the following functions:

  • Visual Interface Management

  • The mock data

  • Automated interface testing

  • Data import (including Swagger, HAR, Postman, JSON, command line)

  • Rights management

  • Support local deployment

  • Support plugins

  • Support secondary development

  • Advantages: very powerful function, support authority management, online debugging, interface automation test, plug-in development, etc., BAT and other large factories in use, indicating that the function is very good.

  • Disadvantages: online debugging function requires plug-in installation, user health check is slightly bad, mainly to solve cross-domain problems, there may be security issues. However, to solve this problem, you can implement a plug-in yourself, should not be difficult.

  • Personal advice: This online documentation tool is very useful if you don’t care about the security of plug-in security. It is a magic tool, and I strongly recommend it.

2.5 apidoc

Github address: github.com/apidoc/apid… Open source License: MIT License

★★★★☆

Example:

Apidoc is a simple RESTful API document generation tool that extracts content in a specific format from code comments to generate documents. Support for most development languages such as Go, Java, C++, Rust, etc. You can use the apidoc lang command line to view the list of all supported languages.

Apidoc has the following characteristics:

  1. Cross-platform, Linux, Windows, macOS, etc.
  2. Support language wide, even if it is not supported, it is very easy to expand;
  3. Generate one document for multiple projects supporting multiple languages;
  4. The output template can be customized.
  5. Generate mock data from the document;
  • Advantages: Generate online documents based on code comments, less embedding of code, support multiple languages, cross-platform, and can also customize templates. Supports search and online debugging.

  • Disadvantages: you need to add specified annotations in the annotations. If the code parameters or types are modified, you need to modify the related content of annotations synchronously, which requires a certain amount of maintenance work.

  • Personal advice: This online document generation tool provides another way of thinking, Swagger is to add annotations to the code, while APidoc is to add data to the annotations, the code is less embedded, recommended use.

2.6 Showdoc (seems to start charging)

Github address: github.com/star7th/sho… Open-source license: Apache License

Users: more than 10000+ Internet teams are using recommended index: ★★★★☆

Example:

ShowDoc is a great online document sharing tool for IT teams to speed up communication between teams.

What functions does it have:

  1. Responsive Web design that allows project documents to be shared to a computer or mobile device. You can also export the project to a Word file for offline viewing.
  2. Access management, ShowDoc has both public and private projects. Public projects can be accessed by any logged-in or non-logged-in user, while private projects require password authentication. The password is set by the project author.
  3. ShowDoc uses the Markdown editor, and the API template and data dictionary template can be easily inserted by clicking the button at the top of the editor.
  4. ShowDoc provides a historical version feature for your page, so you can easily restore the page to its previous version.
  5. Supports file import, including postman JSON files, Swagger JSON files, and ShowDoc Markdown compression packages. The system automatically identifies file types.
  • Advantages: support project authority management, a variety of format file import, full-text search and other functions, it is very convenient to use. And support both deployment of their own servers, but also support online hosting two ways.

  • Disadvantages: Does not support online debugging

  • Personal tip: This online documentation tool is worth using if you don’t require online debugging.

2.7 Apizza (Geek exclusive Interface collaboration Management tool)

Official website: www.apizza.net/

2.7.1 Main Functions

  1. API cross-domain debugging tailored chrome plugin, local, online interface, can be tuned.

  2. Cloud storage, Enterprise Security edition supports local data centers.

  3. One-click share to share your API documentation with the team.

  4. Support Postman, Swagger format Import Postman/Swagger Json to generate documents.

  5. Export offline documents and deploy the local server.

  6. API Mock automatically generates return results from documents and provides a separate URL to facilitate front-end testing.

  7. Support a variety of documents HTTP interface documents, Markdown documentation.

One major drawback of the Apizza interface documentation tool is that the Apizza personal free edition has a limited number of users, so if you want to use it for free, you don’t need to consider Apizza. If you see an article or a public account that says Apizza is free, it’s bullshit. He hasn’t used it. Of course, if you are not short of money, you can pay for the enterprise version. Our team also used Apizza for more than half a year. Later, due to the increase of personnel, we could not add new members in Apizza, forcing us to give up Apizza.

2.8 APIJSON

Gitee address: gitee.com/Tencent/API…

★★★★ ★

  • APIJSON is a JSON network transport protocol and AN ORM library based on this protocol. For simple add, delete, change, search, complex query, simple transaction operations to provide a fully automated universal API.

  • Can greatly reduce the development and communication costs, simplify the development process, shorten the development cycle.

  • Suitable for small and medium-sized projects with separated front and back ends, especially BaaS, Serverless, Internet entrepreneurship projects and enterprise self-use projects.

  • With a versatile API, the front end can customize any data, any structure.

  • Most HTTP request backends no longer need to write interfaces, let alone documents.

  • The front end no longer has to communicate interface or documentation issues with the back end. No more documentation errors.

  • The back end no longer has to write new versions of interfaces and documentation to accommodate older ones. I won’t be bothered endlessly by the front end anytime, anywhere.

2.8.1 Features and Functions

For the front

  • No need to push the interface back end, document
  • The data and structure are completely customized, and you can have anything you want
  • You know what you ask, you get what you ask
  • Any data, any structure, can be retrieved at once
  • It can remove duplicate data, save traffic and improve speed

For the back-end

  • Provides a common interface, most of the API no longer need to write
  • Automatic generation of documents, no need to write and maintain
  • Automatic permission verification, automatic version management, automatic anti-SQL injection
  • Open apis do not require versioning and are always compatible
  • Support to add, delete, change, complex query, cross – library table, remote functions

2.8.2 APIJSON Interface Display

2.9 Other interface management artifacts

Because apis are so critical to the software development process, managing them is especially important. API management tools and platforms can greatly simplify the difficulty and complexity of API management. Here are some of the top API management tools and platforms for your reference.

2.9.1 API Umbrella

API Umbrella is one of the top open source tools for managing apis and microservices. It enables multiple teams to use the same Umbrella by granting different administrator rights to different domains. The platform also provides rate limiting, API keys, caching, real-time analysis and a Web management interface.

2.9.2 Gravitee. IO

Gravitee. IO is an open source platform for managing apis that are flexible and lightweight. It has out-of-the-box features such as rate limiting, IP filtering, cross-domain resource sharing, plug-and-play options, developer portal with OAuth2 and JSON Web token policies, load balancing, and more.

However, the main function of this API management tool is the ability to generate fine-grained reports to understand how the API’s data is being used.

2.9.3 APIman. IO

Apiman. IO is a top-level API management platform introduced by Red Hat, found on GitHub, that provides a lot of convenience for back-end developers. This includes:

Fast running policy-based governance asynchronous features with detachable policy engine enhanced settlement and analysis options REST API availability management speed limit, among other things

2.9.4 WSO2 API Manager

WSO2 API Manager is a complete lifecycle API management platform that can be run anytime, anywhere. API distribution and deployment can be performed within the enterprise and on private clouds. In addition, it provides some other conveniences. Some of them are:

Highly customized management strategies for ease of use, the possibility of designing and prototyping for SOAP or RESTful apis, better access control and monetization facilities, etc

2.9.5 Kong Enterprise

Kong is a widely adopted open source microservices API tool that enables developers to manage everything quickly, easily, and securely. The Enterprise edition comes with many features and functions, such as:

Availability of open source plug-ins One-click operation Common language infrastructure powerful visual monitoring features general software health check OAuth2.0 permissions, and wider community support

2.9.6 Tyk. IO

Tyk.io is written in the Go programming language and is also a recognized open source API gateway.

It comes with a developer portal, detailed documentation, dashboards for API analysis, API rate limits, authentication, and various other such specifications to help organizations focus on microservice environments and containerization. However, its business-based service is only available in the paid version.

2.9.7 Fusio

Fusio is another open source API management tool that developers can use to create and maintain REST apis from different data types. It has efficient lifecycle management features such as a back-end dashboard for administrative control, detailed documentation, JSON validation for incoming requests, and scope processing to satisfy user permissions.

Furthermore, the APIM platform automatically generates OAI and RAML requirements and creates custom client SDKS based on the defined architecture.

2.9.8 Apigility

Apigility, designed and maintained by the Zend framework, is the next open source framework to be considered for API management. The platform creates and presents a JSON representation of its code. It also provides them with different versioning options, as well as ease of authentication through OAuth2 and documentation containing API blueprints.

API Management, 15 open source tools to help you manage API ility

2.9.9 SwaggerHub

SwaggerHub is considered for management apis by over 40 organizations and is one of the best open source API management tools available.

The platform provides a wide range of options for designers and developers in the field of back-end development. It gives them a powerful and intuitive editor that provides greater efficiency and speed while maintaining design consistency.

In addition, it offers opportunities for intelligent error feedback, syntax auto-completion, and availability of a variety of style validators.

2.9.10 API Axle

With support from Exicon, API Axle is another open source, simple and lightweight proxy that offers many benefits to developers, such as: Real-time analysis for powerful authentication, logging API traffic for statistics and reporting, easy creation and management of API keys, and support for REST API design and use of Go, PHP and Node.js libraries.

IBM 2.9.11 Bluemix API

The API management tool enables developers to use more than 200 software and middleware patterns to build portable and compatible applications for the hybrid cloud. It also provides a variety of pre-built services and powerful mechanisms for moderating API access, managing multiple API versions, maintaining rate limits, and tracking performance metrics and analysis for each API involved.

2.9.12 Repose

Repose is an open source RESTful middleware platform that plays a significant role in the ever-changing API market. The platform provides organizations with a variety of API processing capabilities, including authentication, API authentication, rate limiting, and HTTP request logging.

The API management platform is designed to provide well-formed and validated downstream services that trust downstream requests. Moreover, it is highly scalable and extensible by nature, meaning that developers can easily use it based on ever-growing demands.

2.9.13 SnapLogic Enterprise Integration Cloud

SnapLogic is an integrated platform as a Service (iPaaS) tool that helps organizations acquire, maintain, and grow their customer base. Its characteristics are:

It is fast, multipoint, and has options that flexibly meet data integration requirements for batch and real-time applications. It has an extensible architecture that operates like a Web server, but also offers the option to embrace versatility. It also comes with innovative data flow solutions that encourage organizations to add well-known SaaS applications such as SugarCRM and Salesforce to their traditional processes.

2.9.14 DreamFactory

The DreamFactory API management platform is one of the best free open source tools to consider for your next project and is popular for the following reasons:

It gives developers a way to develop mobile applications without having to manually write apis.

It enables them to integrate any SQL/NoSQL database, external HTTP/SOAP service or file storage system into the DreamFactory environment and automatically get a comprehensive, flexible, fully documented and ready-to-use REST API. In addition to accessing API parameters for paging, complex filters, virtual foreign keys, related table joins, and more, the platform provides a detailed REST API for SQL databases.

Another unique feature of the DreamFactory API management platform is that it instantly converts JSON requests to SOAP and vice versa. In addition, the platform provides highly secure user management, SSO authentication, CORS, JSON Web tokens, SAML integration, role-based access control on API endpoints, OAuth, and LDAP in an easy-to-manage form. API Management, these 15 open source tools help you manage the API DreamFactory

2.9.15 3 scale

Last but not least, 3Scale complements this list of API management tools.

The API Management tool, owned by Red Hat, makes it easy and secure for businesses large and small to manage their apis with the following features:

It uses a distributed cloud layer to centralize control of API applications. This makes it easier to control analytics, accessibility, developer workflow, profitability, and so on.

Because it is hosted on the distributed cloud hosting layer, it has a high degree of flexibility and scalability.

The OpenShift integration capabilities of the 3Scale API enable you to run high-performance applications in an automated and closed manner. This complete lifecycle API management platform enables developers to plan, design, apply, publish, manage, analyze, optimize, and deprecate your apis at any time to provide a superior experience.

It has the ability to easily share organizational data, services, and content via Web or mobile applications. Most importantly, the 3Scale API management platform gives you the opportunity to inject various encryption, authentication, and authorization protocols into your development environment. This enables back-end development companies to provide a highly secure mobile application experience tailored to their target audience.

All of the API management tools shared above are open source and are expected to be useful additions to the technology stack. However, to ensure that you choose the best fit for your business application’s needs, let’s cover some tips on choosing an API management tool.

Third party API interface test problem feedback document

  • Proxmire is not a dream: Third party API interface testing problem feedback document

Step into the shoes of the third party technician and think about what information they need to help them locate the problem.

  • The documentation explains why the document was sent to them
  • Problem feedback record summary records all possible problems of the interface, because sometimes the processing interface can not be improved at one time, need constant coordination and modification, the purpose of the document is also to record the process of dealing with interface problems, do file.
  • The interface address is used to indicate that we used such a URL when testing the interface, so that a third party technician can determine whether we mismeasured the interface.
  • Testers are used by third-party technicians to contact and explain directly to testers.
  • Test time Records the time when the test occurred, making it easier for them to find log documents.
  • Request mode, request header information and request parameters can enable third-party technicians to quickly judge whether the tester is testing in accordance with the interface requirements. In addition, the request guess number is convenient for third-party technicians to test the problem by themselves.
  • The response status code directly tells them if the interface is working.
  • The actual return value versus the expected return value allows a third-party technician to compare what kind of data we want.
  • Problem description Records what problems we found and what problems we hope to solve.

  • Personal website: www.lovebetterworld.com/
  • For the rest of my life, I just want to share some dry goods, some notes and summaries of my work and study, and help anyone who needs help. Pay attention to me, let’s learn together!