An overview of the

The application scenarios of Web API are very rich. For example, to open the functions or data of the existing system to partners or ecosphere; Publish widgets that can be embedded in other web pages; Build a Web application with front and back end separation; Developing mobile applications across different terminals; Integrate different systems within the company, etc. In the above scenario, you may be a Web API user or designer, but do you know how to judge the merits of a Web API?

criteria

We can judge a Web API from three dimensions:

  • Ease of use: Are Web API users programs or people? I think it’s the people first, and then the program. Why do you say that? The decision to adopt a Web API is a human one, and a good Web API must meet the human aesthetic, such as being short and easy to remember, easy to understand, easy to type, and so on. From a programmatic perspective, Web APIs should follow industry norms, do not require specialization when invoked, and facilitate reuse of existing code or tools.
  • Easy to change: After a Web API is released online, it is inevitable to make changes based on the feedback of real users or the needs of business development, and these changes must not affect users as much as possible. Either provide multi-version support, or provide users with a viable update strategy, and so on.
  • Robust and stable: Publicly available Web APIs are vulnerable to attacks and unpredictable traffic. A good Web API must have anti-injection, tamper-proof, anti-replay and other security mechanisms, as well as avoid service breakdown when traffic increases dramatically.

With all three of these things in place, we have the confidence to open up a Web API to public scrutiny. A good Web API is not only easy to use, but also helps to increase the technical impact of an individual or enterprise, which in turn creates a positive cycle that adds more and more business value. In order to design a beautiful Web API, we need to understand the design specifications and de facto standards associated with it, and try to follow them during the design and development process.

The design specification

URI

  • A URI that is easy to type, short and not redundant. Each Web API is a service, so the “service” in the counterexample below is redundant, and the “API” is repeated twice. This redundancy is bad for memory and input:
Example: http://api.example.com/service/api/users is: http://api.example.com/users
  • Easily read URI, do not arbitrarily use abbreviations, abbreviations must comply with international standards and specifications, do not invent out of thin air, such as: national code definition (ISO3166). In the counter example, there are two abbreviations “SV” and “U” that the user doesn’t know what they mean without additional instructions:
Example: http://api.example.com/sv/u
  • There are no case-mixed URIs. The HTTP protocol (RFC7230) dictates that URI information is case sensitive except for schema and host name. The following two counter examples use case mixed, not easy to remember.
Example: http://api.example.com/Users/12345 counterexamples: http://example.com/API/getUserName
  • Uris that are easy to modify and have predictable rules for naming. We can easily guess that by changing the last ID, we can access the information of other goods.
Is: http://api.example.com/v1/items/123456
  • The URIs of the server architecture are not exposed; the URIs only need to represent functionality, data structure, and meaning, without exposing information about how the server operates. The information is meaningless to users, and there is a potential risk that malicious users or hackers will use the information to find loopholes and launch attacks on the service.
Example: http://api.example.com/cgi-bin/get\_user.php?user=100
  • Unified rules URI, to ensure the use of uniform rules and style, convenient user memory and use. In the counterexample below, the first URI takes a query parameter and the second URI takes a path parameter. The two are not consistent and can cause confusion.
Example: friends information, http://api.example.com/friends?id=100 counterexamples: send a message, http://api.example.com/friend/100/messages is: Friends information, http://api.example.com/friends/100 is example: sending messages, http://api.example.com/friends/100/messages
  • URIs are best made up of nouns. The full name of a URI is a Uniform Resource Identifier, which identifies the location of a Resource on the Internet, similar to a mailing address, which is made up of nouns. There are also some caveats in the use of nouns: First, use the plural form of nouns; Second, try to use the same words used in most APIs. Third, by using as few words as possible; Fourth, try not to use strange abbreviations and so on.
  • Do not use Spaces and characters that need to be encoded, such as Chinese in URIs.
  • Using a hyphen (-) to connect multiple words is recommended for the spine method: First, host names (domain names) in URIs allow hyphens and prohibit underscores, and are case-insensitive. Second, the dot character has a special meaning in keeping with the rules for hostnames.
Spine: http://api.example.com/v1/users/12345/profile-image serpentine: http://api.example.com/v1/users/12345/profile\_image hump method: http://api.example.com/v1/users/12345/profileImage

Query parameters

  • In many scenarios, data needs to be retrieved in batches through the API, and we often struggle with which query parameters to use. There are two commonly used parameter designs in the industry (per-page and page, limit and offset) to identify the amount and starting position of the data to be retrieved each time. During the process of obtaining data in batches, records in the data set may be added or deleted, and we need to pay attention to the different effects brought by the use of relative or absolute positions.
Style 2:http://api.example.com/friends?limit=50&offset=100 1:http://api.example.com/friends?per-page=50&page=3 style
  • The industry also has some de facto standards to consider when designing the parameters of filtering. If we expect the value of a particular attribute in the query result to be exactly the same as the value of the filter parameter, the filter parameter’s name is usually the property name. If we expect any property part of the query result to contain the value of the filter parameter, the name of the filter parameter is usually “q”.
Completely in line with: http://api.example.com/v1/users?name=ken full-text search: http://api.example.com/v1/users?q=ken
  • Can URIs contain the verb “search”? Usually search-focused online service APIs can be included, but otherwise the plural noun is recommended. The common English words “search” and “find” both mean search, but there are some subtle differences between “search” for a vague search and “find” for a precise query.
Fuzzy search: http://yboss.yahooapis.com/ysearch/web?q=ipod
  • Is an attribute used as a component of the URI path or as 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 element, otherwise 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 parameters: http://api.example.com/v1/users?name=ken

HTTP method

As the HTTP protocol was designed, URIs are used to identify the target object (resource) to be operated on, and HTTP methods are used to represent the operation method. SOAP, a simple object access protocol based on HTTP, is gradually being replaced by a RESTful native HTTP protocol. There is no need to add to the pot. It is best to learn the HTTP protocol and take advantage of its features.

GET /v1/users/123 HTTP/1.1

Host: api.example.com
  • GET, to GET resources
  • POST, new resource
  • PUT, which updates existing resources
  • Delete, to DELETE the resource
  • PATCH, to update some resources
  • Head, gets the meta information about the resource

If you encounter scenarios that are not covered by the HTTP method described above, it is usually because the design granularity of the resource is too large, and we can split a coarse-grained resource into several fine-grained resources. In terms of expertise in designing Web APIs using the HTTP protocol, the industry divides it into four levels. Level3 is relatively idealistic and lacks the basis for implementation. Level2 is practical:

  • Level 0: Use HTTP
  • Level 1: Introduce the concept of resources
  • Level 2: Introduce HTTP verbs (GET/POST/PUT/DELETE, etc.)
  • Level 3: Introduce the concept of HATEOAS

The response data

Common data formats include HTML, XML, JSON, YAML, etc. If our service supports different types of data formats when responding, how can the application get the response data in the expected format when calling the service? In general, we can consider the following methods for specifying data formats:

  • How to use query parameters:
Example: https://api.example.com/v1/users?format=xml
  • How to use the extension:
Example: https://api.example.com/v1/users.json
  • Use the method that specifies the media type at the beginning 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 more better? Or as little as possible, just IDs? The recommendation is to return on demand, as required by 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, more or less, in this case, we can let users choose the content of response by specifying query parameters:

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

The structure of response data should be as flat as possible, not too deep nested, to reduce the information load without specific meaning, which can not only compress the size of the message, but also save bandwidth. Of course, if the hierarchy is more advantageous, you can also use it.

An error message

It is suggested to express the error message through the status code of the first part of the HTTP protocol, rather than encapsulating another layer. The advantage of complying with the protocol specification is that it can reduce the cost of communication, and many mature hardware and software products can also be used to handle the abnormal error message. The HTTP protocol specifies five types of status codes:

  • Xx: 1
  • 2 xx: success
  • 3XX: Redirect
  • 4XX: Error caused by client side
  • 5XX: Error caused by server-side causes

We need a usage scenario for each status code to ensure proper use of the status code. In addition, the service also needs to return the detailed error message to the client, we can usually use the following two methods to pass the detailed error message:

  • Approach 1: Define a private header and fill it into the header of the response message.
  • Approach 2: Put detailed error information into the message body.

Version management

With the development of the business, every Web API published online has the possibility of update and modification, which requires the introduction of version management mechanism. There are three common ways to annotate Web API versions in the industry:

  • Embed the version number in the 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 norm for version numbering: the Semantic Versioning specification, at http://semver.org. The version number is composed of three numbers connected by a dot number, such as 1.2.3, which respectively represent the major version number, the minor version number and the patch version number. The increase of the version number follows the following rules:

  • Increase the major version number when making changes to the software that are not backward compatible;
  • When making downward compatible changes to the software or abolishing certain functions, the secondary version number is added;
  • If the API of the software has not changed, but only some bugs have been fixed, the patch version number is added.

In accordance with the rule of increasing version number, the version number of Web API only needs to be marked with the major version number, because the increase of the minor version number and patch version number can be downward compatible and will not affect the use of users, and only the increase of the major version number requires users to update and upgrade. In addition to annotating version information, we also need to design version change policies when we release the Web API, such as how long the old version provides transition, how many versions are compatible at the same time, the expiration date of a particular version, and so on.

conclusion

What is beautiful? Is in line with the public aesthetic, for Web API, is in line with the standard specification, which is conducive to reduce the cost of learning and use of users, easy to communicate, there is no hidden cost. Often, the standard norms and de facto standards that exist in the industry are culled by practice, starting with imitation and then finding opportunities to innovate, rather than reinventing the wheel in the first place.

The standard specifications in the Web API design world are URI, HTTP, and so on, and we want to make the most of these protocol specifications to make each Web API user-friendly (easy to use), technology-friendly (caching support, easy to change). In addition, we also need to consider the robustness of the Web API, and next time we’ll talk about how to design a robust Web API, so please come and talk to me about that.

Today first share here, if you think it is valuable, please move your finger to forward to other friends in need. In addition, I will share my experience in career planning, job interviews, skills improvement, and influence building in the future. Please follow this column or “IT Veteran Princess”!