How to design a beautiful Web API?

1 Overview

WEB API application scenarios are very rich, such as: the capabilities of existing systems or data open to partners or ecosystem; released a widget that can be embedded into other web pages; before and after the end construction of the separation of WEB application; development across different terminals mobile application; internal integration of different systems and the like. In the above scenario, you may be user WEB API, it may be the designer, but you know how to judge the merits of WEB API do?

API

2. criteria

We can judge the merits of a WEB API from three dimensions:

  • Ease of use: Users WEB API is the program or people? I think the first is the people, then the program. Why do you say? Decide whether to adopt a WEB API is people make a good WEB API must comply with the aesthetic of people, such as: short and easy to remember, easy to understand, easy to enter and so on. From a program perspective, WEB API should follow industry standards, you do not need to call upon specialized treatment, help reuse existing code or tools.
  • Easy to change: a WEB API released after on-line, will inevitably have to do to update or revise as necessary feedback business development of real users, these updates modifications must minimize the impact on users. Or providing support for multiple versions or updates to provide users with practical strategies and so on.
  • Robust and stable: there is open to the public WEB API risk ***, as well as the amount of access can not be accurately estimated, etc. A good WEB API must have anti-implantation, anti-tamper, anti-replay and other security mechanisms, but also in avoid breakdown service when a sharp rise in traffic.

Did these three aspects, we have confidence will open a WEB API, subject to public inspection. Good WEB API is not only easy to use, but also help enhance the technological influence of individuals or companies, to form a positive cycle, bring more and more business value. In order to design a beautiful WEB API, we need to understand the associated design specifications and the de facto standard, and try to follow them in the design and development process.

3. The design specifications

3.1 URI

  • URI easy to enter, short not redundant. Each WEB API is a service, then the following counter-examples among the "service" is redundant, and "api" also repeated twice, this redundancy is not conducive to memory and input:
反例:http://api.example.com/service/api/users
正例:http://api.example.com/users
  • Easy to read the URI, not arbitrarily abbreviated, the abbreviation must be in line with international standards, not out of thin air inventions, such as: country code defined (ISO3166). Counterexamples appeared in two abbreviation "sv", "u", without additional explanation of the situation, the user simply does not know the meaning of:
反例:http://api.example.com/sv/u
  • No mixed case URI. HTTP protocol (RFC7230) provides that: In addition to the mode (schema) and the host name, additional information about the URI must distinguish between uppercase and lowercase letters. The following two counterexamples mixed case, hard to remember.
反例:http://api.example.com/Users/12345
反例:http://example.com/API/getUserName
  • Easy to modify the URI, predictable regularity name exists. The following positive examples we can easily guess the last change ID can access information other commodities.
正例:http://api.example.com/v1/items/123456
  • Not exposed server architecture URI, URI only need to reflect the functions, data structure and meaning, without exposing information on how the server works. This information is no significance to the user, there are potential risks, or malicious users will use this information to look for loopholes to launch the service .
反例:http://api.example.com/cgi-bin/get_user.php?user=100
  • Unified rules of URI, to ensure uniform rules and style, convenient for users to remember and use. Anti following the first embodiment uses a URI query parameter, the second path using the URI parameter, the two are not consistent, likely to cause confusion.
反例:获取好友信息,http://api.example.com/friends?id=100
反例:发送消息,http://api.example.com/friend/100/messages
正例:获取好友信息,http://api.example.com/friends/100
正例:发送消息,http://api.example.com/friends/100/messages
  • URI best of nouns. URI stands for Uniform Resource Locator (Uniform Resource Identifier), used to identify the location of resources on the Internet, similar to the mailing address, and the address are made of nouns. On the use of the term there are some points to note: First, the use of the plural form of the noun; secondly, as far as possible to indicate the same word used in the majority of API; Third, by as few words to express; Fourth, not surprisingly acronyms, etc. as possible.
  • Do not use spaces and characters need to be encoded, for example, the use of Chinese in the URI and so on.
  • Use the hyphen (-) to connect multiple words, spine recommended method: First, URI in the host name (domain name) allows the use of hyphens and prohibit the use of an underscore, not case sensitive. Secondly, the point characters have special meaning to the rules of the host name consistent.
脊柱法:http://api.example.com/v1/users/12345/profile-image
蛇形法:http://api.example.com/v1/users/12345/profile_image
驼峰法:http://api.example.com/v1/users/12345/profileImage

3.2 query parameters

  • In many scenarios need to get data through API batches, we will often tangled what kind of query parameters using the industry there are two common design parameters (per-page and page, limit and offset), is used to identify each acquisition and the starting position of the data amount. In the process of acquiring data in batches, the record in the data set may change deletions occur, we need to pay attention to using the relative position or absolute position caused by the different effects.
风格1:http://api.example.com/friends?per-page=50&page=3
风格2:http://api.example.com/friends?limit=50&offset=100
  • In the design of the filter parameters, there are some industry de facto standard for reference. Exactly the same as the value of a specific property values ​​with the filter parameters if we expect the results of a query, the name of the filter that usually attribute parameter name; if we expect the value of any property of the query results section contains the filter parameters, the name of that filter parameters are usually to "q".
完全符合:http://api.example.com/v1/users?name=ken
全文搜索:http://api.example.com/v1/users?q=ken
  • URI can include whether the verb "search"? Usually in search-based online service API may contain, in addition to the plural form of the noun is recommended. Common English word meaning "search" and "find" are looking for, but the two still have some minor differences, which "search" for fuzzy search, but "find" for precise queries.
模糊搜索:http://yboss.yahooapis.com/ysearch/web?q=ipod
  • What is a property URI path as an element or as a query parameter it? We can be judged according to the following rules: If the property information is uniquely positioned resources, then it is suitable as a constituent element of the path, otherwise it as a query parameter; if the property can be omitted, then it is suitable as a query parameter.
路径元素:http://api.example.com/v1/users/{id}
查询参数:http://api.example.com/v1/users?name=ken

3.3 HTTP method

HTTP protocol designed in accordance with the intention, the URI for identifying a target object (resources), and the HTTP method is a method of operating it. Simple Object Access Protocol (SOAP) HTTP protocol have been gradually replaced by native RESTful HTTP protocol, we do not need superfluous, the best is to thoroughly understand the HTTP protocol, take full advantage of its features.

GET /v1/users/123 HTTP/1.1
Host: api.example.com
  • GET, access to resources
  • POST, additional resources
  • PUT, update existing resources
  • DELETE, delete resources
  • PATCH, updating some of the resources
  • HEAD, get meta-information resources

If you encounter a scene HTTP method described above can not be covered, it is usual to design the resource size is too big, we can break down into a coarse-grained resource resources more fine-grained. On the WEB API using the HTTP protocol design expertise, the industry will be divided into four levels, LEVEL3 relatively idealistic, lack of basic implementation, LEVEL2 is feasible:

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

3.4 Response Data

Common data formats: HTML, XML, JSON, YAML, etc., if our service support different types of data formats in response to that application how to get the desired response data format when calling services? Usually we can consider several methods of data format specified by the following:

  • Use query parameters:
示例:https://api.example.com/v1/users?format=xml
  • Use extensions:
示例:https://api.example.com/v1/users.json
  • The method used in the request header specified media type, priority recommended this method:
GET /v1/users
Host: api.example.com
Accept: application/json

What information should be included in response to the data it? You are better? Or will the better, contains only ID? Suggestion is returned demand required to return the corresponding data according to the service function. If you need a WEB API provided to different business scenarios using different requirements for different business scenarios data attribute information, more or less, in which case we can let the user select the content of the response, selection method is through query parameter:

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

Response data structure should be as flat, not deep nested, reduce information load no specific meaning, so that both the compressed packet size, and can save bandwidth. Of course, if the hierarchical structure of an advantage, can also be used.

3.5 error message

Recommended to represent the error message, rather than repackaging level, the benefits of the agreement to comply with the specification can reduce the cost of communication, you can also use many mature hardware and software products to handle an exception error messages via HTTP status code header. HTTP protocol set up five types of status codes:

  • 1XX: Message
  • 2XX: Success
  • 3XX: Redirection
  • 4XX: error causes the client
  • 5XX: server-side error causes

We need to use every scene status codes to ensure the proper use of state codes. In addition, the service also requires the client to return detailed error information, we usually deliver detailed error information the following two ways:

  • Method 1: define the private header, the header portion which is filled response message.
  • Method 2: The detailed error information into the message body.

Management version 3.6

With the development of business, each on-line publication of WEB API there may update modified, version management mechanism would need to be introduced. There are three common ways the industry marked WEB API version:

  • Embedded version number in the URI:
示例:http://api.linkedin.com/v1/people
  • Join the version information in the query string:
示例:http://api.example.com/users/123?v=2
  • To specify the version information through the media types
Accept: application/vnd.github.v3+json
Content-Type: application/vnd.github.v3+json

Similarly, there are also the industry specification version number: Semantic Versioning (Semantic Versioning) specification, Web site address:http://semver.org . 3-digit number version number of connection points, for instance: 1.2.3, respectively, the major version number and minor version numbers, patch version number, the version number increased to follow the following rules:

  • When the software is not backward-compatible changes to increase the major version number;
  • When the software is backward compatible change or repeal certain features, increase the minor version number;
  • If the software's API is not changed, just fixes some bug, the patch version number increase.

According to the rules of the version number increase, WEB API version number only need to mark the major version number on it, because the minor version number, increase the patch version numbers can be backward compatible, does not affect users, only the major version No increase in user only needs an upgrade. In addition to information outside the marked version, we need to design a good strategy changes in version released WEB API Shihai, such as: the old version provides long transitional period, while the number of versions, a specific version of the termination date, and so compatible.

4. Summary

What is beautiful? Is consistent with the public aesthetic, for WEB API, is to meet the standards, which will help reduce the cost of users to learn and use, easy to exchange, sunk costs do not exist. Typically, there are industry standards and de facto standards are screened out after practice, to follow from beginning to imitate, and then find opportunities for innovation, rather than one up on re-inventing the wheel.

WEB API standard in the field of design specifications is URI, HTTP, and we want to maximize the use of these protocol specifications, so that each WEB API is user-friendly (easy to use), technology-friendly (support caching, easy-to-change) is. In addition, we also need to consider the robustness WEB API, the next time we come to talk about how to design robust WEB API, welcome to come to me to discuss the exchange of relevant topics.

Today to share here, it is not easy to adhere to the original, if you feel valuable, trouble moving hands pointing "below

Guess you like

Origin blog.51cto.com/14622239/2466761