As a programmer, you don't know RESTful yet?

What is RESTful?

  • RESTFUL is a design style and development method for web applications, based on HTTP, which can be defined in XML format or JSON format. RESTFUL is suitable for scenarios where mobile Internet manufacturers are used as service enablement interfaces, and realizes the function of third-party OTT invoking mobile network resources. The action types are add, change, and delete the invoked resources.
  • REST is a very general concept that represents an architectural style.
  • REST名称REST – REpresentational State Transfer
    • The full name is Resource Representational State Transfer. In layman's terms, it means that resources perform state transfer in some form of representation in the network.
    • Resource: Resource, that is, data (the core of the network was mentioned earlier). Such as newsfeed, friends, etc.;
    • Representational: some form of representation, such as JSON, XML, JPEG, etc.;
    • State Transfer: State change. Implemented via HTTP verbs.

Traditional vs RESTful

  • traditional style
http://127.0.0.1/user/query/1 GET  根据用户id查询用户数据
http://127.0.0.1/user/save POST 新增用户
http://127.0.0.1/user/update POST 修改用户信息
http://127.0.0.1/user/delete GET/POST 删除用户信息
  • RESTful style
http://127.0.0.1/user/1 	GET  根据用户id查询用户数据
http://127.0.0.1/user  		POST 新增用户
http://127.0.0.1/user  		PUT 修改用户信息
http://127.0.0.1/user  		DELETE 删除用户信息
  • Let's take a look at a comparison chart
    insert image description here

version number

  • In a RESTful API, the API interface should be as compatible with the previous version as possible. However, in the actual business development scenario, the existing API interface may not support the adaptation of the old version with the continuous iteration of business requirements. At this time, if the API interface of the server is forcibly upgraded, the old function of the client will fail. Therefore, it is difficult for the current product to adapt to the API interface of the new server, resulting in functional failure. In this case, the user must upgrade the product to the latest version to use it normally.
  • To address this version incompatibility, a practical approach in designing RESTful APIs is to use version numbers. In general, we will keep the version number in the url and be compatible with multiple versions at the same time.
【GET】  /v1/users/{user_id}  // 版本 v1 的查询用户列表的 API 接口
【GET】  /v2/users/{user_id}  // 版本 v2 的查询用户列表的 API 接口

resource path

  • The design of RESTful API takes resources as the core, and each URI represents a resource. Therefore, URIs cannot contain verbs, only nouns. Note that adjectives can also be used, but they should be used sparingly. In general, nouns for APIs should be named in plural, regardless of whether the resource is single or multiple. Also, when naming nouns, use lowercase, numbers, and underscores to distinguish multiple words. This is designed to be consistent with the naming scheme for json objects and properties.
  • For example, an interface for querying system tags can be designed as follows.
【GET】  /v1/tags/{tag_id} 
  • At the same time, the path of the resource should be as follows from root to child
/{resources}/{resource_id}/{sub_resources}/{sub_resource_id}/{sub_resource_property}
  • Let's look at a design of "Adding User's Role", where "User" is the main resource and "Role" is the sub-resource.
【POST】  /v1/users/{user_id}/roles/{role_id} // 添加用户的角色
  • Sometimes, when a resource change is difficult to name using a standard RESTful API, consider using some special actions naming.
/{resources}/{resource_id}/actions/{action}
  • For example, the naming of the interface "password modification" is difficult to use nouns to construct paths, and action naming can be introduced at this time.
【PUT】  /v1/users/{user_id}/password/actions/modify // 密码修改

request method

  • You can operate on server-side resources through GET, POST, PUT, PATCH, DELETE, etc. in:
    • GET: used to query resources
    • POST: used to create a resource
    • PUT: All information used to update the resources of the server
    • PATCH: Part of the information used to update the resources of the server
    • DELETE: Used to delete resources on the server.
  • Here, the case of "user" is used to review operations on server-side resources through GET, POST, PUT, PATCH, DELETE, etc.
【GET】          /users                # 查询用户信息列表
【GET】          /users/1001           # 查看某个用户信息
【POST】         /users                # 新建用户信息
【PUT】          /users/1001           # 更新用户信息(全部字段)
【PATCH】        /users/1001           # 更新用户信息(部分字段)
【DELETE】       /users/1001           # 删除用户信息

query parameters

  • The RESTful API interface should provide parameters to filter the returned results. where offset specifies the starting position of the returned record. Under normal circumstances, it will be combined with limit to do paging query, where limit specifies the number of returned records.
【GET】  /{version}/{resources}/{resource_id}?offset=0&limit=20
  • At the same time, order by can be used for sorting, but only supports the sorting of a single character. If there are multiple fields for sorting, you need to expand other parameters in the business to support.
【GET】  /{version}/{resources}/{resource_id}?orderby={field} [asc|desc]
  • In order to better choose whether to support the total number of queries, we can use the count field, which indicates whether the returned data contains the total number of items, and its default value is false.
【GET】  /{version}/{resources}/{resource_id}?count=[true|false]
  • The offset, limit, and orderby introduced above are some public parameters. In addition, there are many personalized parameters in business scenarios. Let's look at an example.
【GET】  /v1/categorys/{category_id}/apps/{app_id}?enable=[1|0]&os_type={field}&device_ids={field,field,}
  • Be careful not to over-engineer and only return the query parameters the user needs. Also, consider whether to create database indexes on query parameters to improve query performance.

status code

  • It's important to use the appropriate status code, and you shouldn't all return a status code of 200, or use it indiscriminately. Here, some status codes commonly used in the actual development process are listed for reference.
status code describe
200 request succeeded
201 Created successfully
400 bad Request
401 Unverified
403 be rejected
404 unable to find
409 Resource conflict
500 Internal server error

abnormal response

  • When a non-2xx HTTP error code response occurs on the RESTful API interface, the global exception structure is used to respond to the information.
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
    "code": "INVALID_ARGUMENT",
    "message": "{error message}",
    "cause": "{cause message}",
    "request_id": "01234567-89ab-cdef-0123-456789abcdef",
    "host_id": "{server identity}",
    "server_time": "2014-01-01T12:00:00Z"
}

request parameters

  • When designing the server-side RESTful API, we also need to limit the request parameters. For example, an interface that supports batch queries, we need to consider the maximum number of supported queries.
【GET】     /v1/users/batch?user_ids=1001,1002      // 批量查询用户信息
  • Parameter Description
    • user_ids: User ID string, up to 20 are allowed.
    • In addition, when designing new or modified interfaces, we also need to clearly tell the caller in the document which parameters are required, which are optional, and their boundary value restrictions.
【POST】     /v1/users                             // 创建用户信息
  • request content
{
    "username": "carroll",                 // 必填, 用户名称, max 10
    "realname": "张三",               // 必填, 用户名称, max 10
    "password": "123456",              // 必填, 用户密码, max 32
    "email": "[email protected]",     // 选填, 电子邮箱, max 32
    "weixin": "carroll",            // 选填,微信账号, max 32
    "sex": 1                           // 必填, 用户性别[1-男 2-女 99-未知]
}

response parameter

  • For different operations, the results returned by the server to the user should conform to the following specifications.
【GET】     /{version}/{resources}/{resource_id}      // 返回单个资源对象
【GET】     /{version}/{resources}                    // 返回资源对象的列表
【POST】    /{version}/{resources}                    // 返回新生成的资源对象
【PUT】     /{version}/{resources}/{resource_id}      // 返回完整的资源对象
【PATCH】   /{version}/{resources}/{resource_id}      // 返回完整的资源对象
【DELETE】  /{version}/{resources}/{resource_id}      // 状态码 200,返回完整的资源对象。
                                                      // 状态码 204,返回一个空文档
  • If it is a single piece of data, returns a JSON string of an object.
HTTP/1.1 200 OK
{
    "id" : "01234567-89ab-cdef-0123-456789abcdef",
    "name" : "example",
    "created_time": 1496676420000,
    "updated_time": 1496676420000,
    ...
}
  • If it is list data, it returns an encapsulated struct.
HTTP/1.1 200 OK
{
    "count":100,
    "items":[
        {
            "id" : "01234567-89ab-cdef-0123-456789abcdef",
            "name" : "example",
            "created_time": 1496676420000,
            "updated_time": 1496676420000,
            ...
        },
        ...
    ]
}

a complete case

  • Finally, we use a complete case to integrate the knowledge presented earlier. Here, the case of "get user list" is used.
【GET】     /v1/users?[&keyword=xxx][&enable=1][&offset=0][&limit=20] 获取用户列表
  • Function description: get user list

  • Request method: GET

  • Parameter Description

    • keyword: The keyword for fuzzy search. [optional]
    • enable: enable state [1-enable 2-disable]. [optional]
    • offset: Get the position offset, starting from 0. [optional]
    • limit: The number of items returned each time, the default is 20, and the maximum is 100. [optional]
  • response content

HTTP/1.1 200 OK
{
    "count":100,
    "items":[
        {
            "id" : "01234567-89ab-cdef-0123-456789abcdef",
            "name" : "example",
            "created_time": 1496676420000,
            "updated_time": 1496676420000,
            ...
        },
        ...
    ]
}
  • failure response
HTTP/1.1 403 UC/AUTH_DENIED
Content-Type: application/json
{
    "code": "INVALID_ARGUMENT",
    "message": "{error message}",
    "cause": "{cause message}",
    "request_id": "01234567-89ab-cdef-0123-456789abcdef",
    "host_id": "{server identity}",
    "server_time": "2014-01-01T12:00:00Z"
}
  • error code
- 403 UC/AUTH_DENIED    授权受限

The more you know, the more you don't know.
If there is a way but no art, art can still be sought; if there is art, there is no way, and it ends at art.
If you have any other questions, please leave a message, we will discuss, learn and make progress together

Published 198 original articles , received 122 likes , and visited 10,000+

Related Posts