Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to design a beautiful Web API

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly analyzes how to design a beautiful Web API related knowledge points, the content is detailed and easy to understand, the operation details are reasonable, and has a certain reference value. If you are interested, you might as well follow the editor to have a look, and follow the editor to learn more about how to design a beautiful Web API.

Overview

WEB API has a wide range of application scenarios, such as opening existing system functions or data to partners or biosphere, publishing widgets that can be embedded into other web pages, building WEB applications separated from front and rear, developing mobile applications across different terminals, integrating different systems within the company, and so on. In the above scenario, you may be a user of WEB API or a designer, but do you know how to judge the merits of WEB API?

Evaluation criteria

We can judge a WEB API from three dimensions:

Easy to use: are WEB API users programs or people? I think it is the people first, then the program. Why would you say that? The decision whether to adopt a certain WEB API is made by people, and a good WEB API must conform to people's aesthetic, such as: short and easy to remember, easy to understand, easy to enter and so on. From a program point of view, WEB API should follow industry standards and do not need to do special processing when calling, which is conducive to the reuse of existing code or tools.

Easy to change: after a WEB API is released and launched, it is inevitable to make updates and modifications according to the feedback of real users or the needs of business development. These updates and modifications must not affect users as far as possible. Either provide multi-version support, or provide users with practical update strategies, and so on.

Robust and stable: public WEB API is at risk of being attacked, and the number of visits cannot be accurately estimated. A good WEB API must have security mechanisms such as anti-injection, anti-tampering and anti-replay, and avoid service breakdown when traffic increases sharply.

Only by achieving the above three aspects can we have the strength to open an WEB API to the public and be tested by the public. Good WEB API is not only easy to use, but also helps to enhance the technical influence of individuals or enterprises, thus forming a positive cycle and bringing more and more business value. In order to design a beautiful WEB API, we need to understand the relevant design specifications and factual standards, and try to follow them in the design and development process.

Design specification

URI

Easy to enter URI, short and non-redundant. Each WEB API is a service, so the "service" in the following counterexample is redundant, and "api" is repeated twice, which is not good for memory and input:

Counterexample: http://api.example.com/service/api/users

Positive example: http://api.example.com/users

Easy to read URI, do not arbitrarily use abbreviations, abbreviations must be in line with international standards, do not invent out of thin air, such as: country Code definition (ISO3166). In the counterexample, there are two abbreviations "sv" and "u". Without additional instructions, the user has no idea what it means:

Counterexample: http://api.example.com/sv/u

There is no mixed case URI. The HTTP protocol (RFC7230) stipulates that except for the schema and hostname, all other information in URI should be case-sensitive. The following two counterexamples are mixed case, which is not convenient for memory.

Counterexample: http://api.example.com/Users/12345

Counterexample: http://example.com/API/getUserName

Easy to modify URI, there is a predictable rule of naming. The following example makes it easy to guess that changing the final ID will allow you to access information about other products.

Positive example: http://api.example.com/v1/items/123456

URI,URI, which does not expose the server-side architecture, only needs to reflect the function, data structure and meaning, and does not need to expose information about how the server operates. This information is meaningless to users, and there are potential risks. Malicious users or hackers will use this information to find loopholes and launch attacks on services.

Counterexample: http://api.example.com/cgi-bin/get_user.php?user=100

URI with uniform rules ensures the use of unified rules and style, which is convenient for users to remember and use. In the following counterexample, the first URI takes query parameters and the second URI takes path parameters, which are not consistent and can easily lead to confusion.

Counterexample: get friend information, http://api.example.com/friends?id=100

Counterexample: send a message, http://api.example.com/friend/100/messages

Positive example: get friend information, http://api.example.com/friends/100

Positive example: send a message, http://api.example.com/friends/100/messages

URI is best made up of nouns. The full name of URI is uniform Resource Locator (Uniform Resource Identifier), which is used to identify the location of resources on the Internet, similar to a mailing address, which is made up of nouns. There are also some matters needing attention in the use of nouns: first, use the plural form of nouns; second, try to use most of the words used in API to express the same meaning; third, express it through as few words as possible; fourth, try not to use strange acronyms.

Do not use spaces and characters that need to be encoded, such as using Chinese in URI.

Using the connector (-) to connect multiple words, the spine method is recommended: first, the hostname (domain name) in URI allows the use of hyphens but forbids the use of underscores, and is not case-sensitive. Second, the dot character has a special meaning in order to be consistent with the rules of the host name.

Spine method: http://api.example.com/v1/users/12345/profile-image

Snake method: http://api.example.com/v1/users/12345/profile_image

Hump method: http://api.example.com/v1/users/12345/profileImage

Query parameters

In many scenarios, we often struggle with which query parameters are used to obtain data in batches through API. There are two commonly used parameter designs in the industry (per-page and page, limit and offset) to identify the amount of data obtained each time and the starting location. In the process of obtaining data in batches, the records in the data set may be added or deleted, so we need to pay attention to the different effects of using relative position or absolute position.

Style 1: http://api.example.com/friends?per-page=50&page=3

Style 2: http://api.example.com/friends?limit=50&offset=100

When designing the filter parameters, the industry also has some factual standards for reference. If we expect the value of a specific attribute of the query result to be exactly the same as the value of the filter parameter, the name of the filter parameter is usually the attribute name; if we expect any attribute part of the query result to contain the value of the filter parameter, the name of the filter parameter is usually "Q".

Exactly match: http://api.example.com/v1/users?name=ken

Full-text search: http://api.example.com/v1/users?q=ken

Can URI include the verb "search"? API, an online service that usually focuses on search, can be included, except that it is recommended to use nouns in the plural. The common English words "search" and "find" have the meaning of search, but there are still some slight differences between them, in which "search" is used for fuzzy search and "find" is used for precise query.

Fuzzy search: http://yboss.yahooapis.com/ysearch/web?q=ipod

Is an attribute a constituent element of the URI path or a query parameter? We can judge according to the following rules: if the attribute information can uniquely locate the resource, then it is suitable as a path component element, otherwise it is used as a query parameter; if the attribute can be omitted, then it is suitable as a query parameter.

Path element: http://api.example.com/v1/users/{id}

Query parameter: http://api.example.com/v1/users?name=ken

HTTP method

According to the original intention of the HTTP protocol, URI is used to identify the target object (resource) being operated, and the HTTP method is to represent the operation method. SOAP, a simple object access protocol based on HTTP protocol, is gradually replaced by RESTful's native HTTP protocol. There is no need for us to add icing on the cake. It is best to understand the HTTP protocol and make full use of its features.

GET / v1/users/123 HTTP/1.1

Host: api.example.com

GET, get resources

POST, add resources

PUT, update existing resources

DELETE, delete resources

PATCH, update some resources

HEAD to get the meta-information of a resource

If you encounter a scenario that cannot be covered by the above HTTP method, it is usually because the design granularity of the resource is too large, and we can decompose the coarse-grained resource into multiple fine-grained resources. In terms of the professional ability to design WEB API using HTTP protocol, the industry divides it into four levels. LEVEL3 is relatively idealized and lacks the basis for implementation. LEVEL2 is feasible:

LEVEL 0: using HTTP

LEVEL 1: introducing the concept of resources

LEVEL 2: introduce HTTP verbs (GET/POST/PUT/DELETE, etc.)

LEVEL 3: introducing the concept of HATEOAS

Response data

The commonly used data formats are: HTML, XML, JSON, YAML, etc. If our service supports different types of data formats in response, how can the application get the response data in the desired format when calling the service? In general, we can consider the following ways to specify data formats:

The method of using query parameters:

Example: https://api.example.com/v1/users?format=xml

The method of using an extension:

Example: https://api.example.com/v1/users.json

Using the method of specifying the media type in the header of the request, this method is preferred:

GET / v1/users

Host: api.example.com

Accept: application/json

What information should the response data contain? Is it better to have more? Or the less, the better, including only ID? The recommendation is to return on demand and return the corresponding data according to the needs of the business function. If a WEB API needs to be provided for different business scenarios, and different business scenarios have different requirements for data attribute information, we can allow users to select the content of the response. The selection method is to specify through the query parameters:

Example: http://api.example.com/v1/users/123?fields=name,age

The structure of response data should be as flat as possible, do not nest too deeply, and reduce the load of information without specific meaning, so that the size of the message can be compressed and the bandwidth can be saved. Of course, if the hierarchy is more advantageous, it can also be used.

Error message

It is suggested that the error message is expressed by the status code of the header of the HTTP protocol, rather than encapsulated in another layer. The advantage of complying with the protocol specification is that it can reduce the cost of communication, and many mature software and hardware products can also be used to deal with abnormal error messages. The HTTP protocol specifies five types of status codes:

1XX: messa

2XX: success

3XX: redirect

4XX: errors caused by client

5XX: errors caused by server-side reasons

We need a usage scenario for each status code to ensure that the status code is used correctly. In addition, the service also needs to return detailed error information to the client, and we can usually use the following two ways to pass the detailed error message:

Method 1: define a private header and fill it in the header of the response message.

Method 2: put the detailed error information into the message body.

Version management

With the development of business, every WEB API released and launched may be updated and modified, so it is necessary to introduce version management mechanism. There are three common ways to label WEB API versions in the industry:

Embed the version number in URI:

Example: http://api.linkedin.com/v1/people

Add version information to the query string:

Example: http://api.example.com/users/123?v=2

Specify version information by media type

Accept: application/vnd.github.v3+json

Content-Type: application/vnd.github.v3+json

Similarly, there is an industry specification for version numbering: semantic version control (Semantic Versioning) specification, website address: semver.org. The version number consists of three numbers connected by the dot, for example: 1.2.3, which represents the major version number, the minor version number, and the patch version number, respectively. The increase of the version number follows the following rules:

Increase the major version number when making incompatible changes to the software

Increase the minor version number when making downward compatible changes to the software or abolishing certain features

If the API of the software has not changed, but only some of the bug has been fixed, increase the patch version number.

According to the rules for the growth of the version number, the version number of the WEB API only needs to be marked with the major version number, because the minor version number and the patch version number can be added to be backward compatible and will not affect the user's use. only the major version number increases to require the user to update and upgrade. In addition to marking version information, we also need to design a strategy for version changes when releasing WEB API, such as how long the transition period of the old version is available, how many versions are compatible at the same time, the end date of a specific version, and so on.

Summary

What is beauty? It is in line with the public aesthetic, for WEB API, it is in line with the standards and norms, which helps to reduce the cost of learning and use by users, easy to communicate, and there is no hidden cost. Usually, the standards and de facto standards that exist in the industry are screened out through practice, starting with following imitation, and then looking for opportunities to innovate, rather than reinventing the wheel in the first place.

The standard specifications in the field of WEB API design are URI, HTTP, etc. We should make the best use of these protocol specifications to make each WEB API user-friendly (easy to use) and technology-friendly (caching, easy to change). In addition, we need to consider the robustness of WEB API.

About "how to design a beautiful Web API" is introduced here, more related content can be searched for previous articles, hope to help you answer questions, please support the website!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report