RESTful API Design Guidelines

The web application is divided into two parts, front-end and back-end. The current development trend is that front-end devices emerge in an endless stream (mobile phones, tablets, desktop computers, other special equipment...).

Therefore, there must be a unified mechanism for different front-end devices to communicate with the back-end. This has led to the popularity of API architecture, and even the emergence of "API First" design ideas. RESTful API is a relatively mature set of API design theory for Internet applications. I previously wrote an article Understanding RESTful Architecture that explores how to understand this concept.

Today, I will introduce the design details of RESTful API and discuss how to design a reasonable and easy-to-use API. My main reference is two articles (1, 2).

RESTful API
1. Protocol

The communication protocol between the API and the user always uses the HTTPs protocol .
2. Domain Name

You should try to deploy your API under a dedicated domain name.

https://api.example.com

If it is determined that the API is very simple and there will be no further expansion, it can be considered under the main domain name.

https://example.org/api/

3. Versioning

The version number of the API should be put into the URL.

https://api.example.com/v1/

Alternatively, put the version number in the HTTP header, but it is not as convenient and intuitive as putting it in the URL. Github adopts this approach.
4. Path (Endpoint)

The path, also known as the "endpoint", represents the specific URL of the API.

In the RESTful architecture, each URL represents a resource (resource), so there can be no verbs in the URL, only nouns, and the nouns used often correspond to the table names in the database. In general, the tables in the database are "collections" of the same kind of records, so the nouns in the API should also be plural.

For example, if there is an API that provides information about a zoo, and also includes information about various animals and employees, its path should be designed as follows.

    https://api.example.com/v1/zoos
    https://api.example.com/v1/animals
    https://api.example.com/v1/employees

5. HTTP verbs

For specific types of operations on resources, represented by HTTP verbs.

There are five commonly used HTTP verbs (the corresponding SQL commands are in parentheses).

    GET(SELECT):从服务器取出资源(一项或多项)。
    POST(CREATE):在服务器新建一个资源。
    PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。
    PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。
    DELETE(DELETE):从服务器删除资源。

There are also two less commonly used HTTP verbs.

    HEAD:获取资源的元数据。
    OPTIONS:获取信息,关于资源的哪些属性是客户端可以改变的。

Below are some examples.

    GET /zoos:列出所有动物园
    POST /zoos:新建一个动物园
    GET /zoos/ID:获取某个指定动物园的信息
    PUT /zoos/ID:更新某个指定动物园的信息(提供该动物园的全部信息)
    PATCH /zoos/ID:更新某个指定动物园的信息(提供该动物园的部分信息)
    DELETE /zoos/ID:删除某个动物园
    GET /zoos/ID/animals:列出某个指定动物园的所有动物
    DELETE /zoos/ID/animals/ID:删除某个指定动物园的指定动物

6. Filtering information

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

Below are some common parameters.

    ?limit=10:指定返回记录的数量
    ?offset=10:指定返回记录的开始位置。
    ?page=2&per_page=100:指定第几页,以及每页的记录数。
    ?sortby=name&order=asc:指定返回结果按照哪个属性排序,以及排序顺序。
    ?animal_type_id=1:指定筛选条件

Parameters are designed to allow for redundancy, which allows for occasional repetition of API paths and URL parameters. For example, GET /zoo/ID/animals has the same meaning as GET /animals?zoo_id=ID.
7. Status Codes

The common status codes and prompt information returned by the server to the user are as follows (the HTTP verbs corresponding to the status codes are in square brackets).

 200 OK - [GET]:服务器成功返回用户请求的数据,该操作是幂等的(Idempotent)。
 201 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。
 202 Accepted - [*]:表示一个请求已经进入后台排队(异步任务)
 204 NO CONTENT - [DELETE]:用户删除数据成功。
 400 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操作,该操作是幂等的。
 401 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。
 403 Forbidden - [*] 表示用户得到授权(与401错误相对),但是访问是被禁止的。
 404 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操作,该操作是幂等的。
 406 Not Acceptable - [GET]:用户请求的格式不可得(比如用户请求JSON格式,但是只有XML格式)。
 410 Gone -[GET]:用户请求的资源被永久删除,且不会再得到的。
 422 Unprocesable entity - [POST/PUT/PATCH] 当创建一个对象时,发生一个验证错误。
 500 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将无法判断发出的请求是否成功。

A full list of status codes can be found here .
8. Error handling

If the status code is 4xx, an error message should be returned to the user. Generally speaking, the returned information uses error as the key name and error information as the key value.

{
    error: "Invalid API key"
}

9. Return the result

For different operations, the results returned by the server to the user should conform to the following specifications.

    GET /collection:返回资源对象的列表(数组)
    GET /collection/resource:返回单个资源对象
    POST /collection:返回新生成的资源对象
    PUT /collection/resource:返回完整的资源对象
    PATCH /collection/resource:返回完整的资源对象
    DELETE /collection/resource:返回一个空文档

十、Hypermedia API

The RESTful API is best to be Hypermedia, that is, to provide links in the returned results to connect to other API methods, so that users can know what to do next without checking documents.

For example, when a user makes a request to the root directory of api.example.com, he will get such a document.

{"link": {
  "rel":   "collection https://www.example.com/zoos",
  "href":  "https://api.example.com/zoos",
  "title": "List of zoos",
  "type":  "application/vnd.yourformat+json"
    }
}

The above code indicates that there is a link attribute in the document, and the user can read this attribute to know what API to call next. rel represents the relationship between this API and the current URL (collection relationship, and gives the URL of the collection), href represents the path of the API, title represents the title of the API, and type represents the return type.

The design of the Hypermedia API is called HATEOAS. Github's API is designed this way, visiting api.github.com will get a list of all available API URLs.

{
  "current_user_url": "https://api.github.com/user",
  "authorizations_url": "https://api.github.com/authorizations",
 }

As you can see from the above, if you want to get the information of the current user, you should go to api.github.com/user , and then you get the following result.

{
  "message": "Requires authentication",
  "documentation_url": "https://developer.github.com/v3"
}

The above code indicates that the server has given prompt information and the URL of the document.
Eleven, other

(1) The authentication of the API should use the OAuth 2.0 framework.

(2) The data format returned by the server should use JSON as much as possible and avoid using XML.

This article is reproduced from: http://www.ruanyifeng.com/blog/2014/05/restful_api.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325471866&siteId=291194637