This page looks best with JavaScript enabled

API Interface Specification

 ·  ☕ 2 min read

In the process of Web application development, backend developers need to deliver API interfaces frequently, and frontend developers need to call API interfaces frequently. To lower communication costs and prevent possible security risks, and following the principle of convention over configuration, it is necessary to standardize the API specification. Restful API is a resource-centric approach to API design, where every operation targets a specific resource. In SaaS development, the Restful API style is recommended; this article mainly discusses some upfront conventions for Restful API in the SaaS development process.

1. Request Specification

1.1 Encoding

Use charset=utf-8 uniformly.

Ajax global configuration

1
2
3
$.ajaxSetup({
  contentType: "application/json; charset=utf-8",
});

Axios global configuration

1
2
axios.defaults.headers.common["Content-Type"] =
  "application/json;charset=UTF-8";

1.2 Request Methods

The API Method should match the actual type of request.

VerbMeaning
GETView
POSTCreate
DELETEDelete
PUTUpdate

1.3 Passing Parameters

  • GET requests
    Parameters go into the query string after the request path that starts with ?, urlencode-encoded.

  • PUT / PATCH / POST requests
    For passing complex data structures, it is recommended to JSON-encode the parameters and put them in the request body.

1.4 Request Parameters

  • Bulk data must be sorted, for example: ?sortOrder=asc&sortField=created_time
  • Bulk data must be paginated, for example: ?page=5&pagesize=50
  • APIs that support bulk requests must not be polled, for example: ?id=1,2,3

2. Response Specification

2.1 Unified Response Format

Field nameDescription of returned content
resultTrue/False
codeMay be unused at this stage; 0 means success, non-zero means different error cases
dataOn success, the content of the returned data
messageOn failure, the returned error message
request_id(Optional) an id identifying the request (an automatically generated unique identifier, handy for tracing a request record, uuid )
1
2
3
4
5
6
{
    'result': True,
    'message': '',
    'data': [],
    'code': 0
}

2.2 Appropriate Status Codes

It is recommended to make full use of the HTTP Status Code as the basic status code of the response result; where the basic status codes cannot distinguish the status, supplement it with the “conventional” code in the response.

  • 200 : GET request succeeded, and a DELETE or PATCH synchronous request completed, or a PUT synchronously updated an existing resource
  • 201 : POST synchronous request completed, or a PUT synchronously created a new resource
  • 401 : Unauthorized : the user is not authenticated, request failed
  • 403 : Forbidden : the user has no permission to access the resource, request failed
  • 429 : Too Many Requests : you have been rate-limited because of frequent access, retry later
  • 500 : Internal Server Error : server error, confirm the status and report the problem

For detailed descriptions of HTTP status codes, refer to:
https://zh.wikipedia.org/wiki/HTTP%E7%8A%B6%E6%80%81%E7%A0%81

2.3 How to Obtain Parameters

  • Use Django URL regex matching to obtain parameters
1
url(r'^area/(?P<cityID>\d{6})/$', 'get_area')
  • Use Django Forms to obtain parameters
1
2
3
4
5
6
7
8
9
class FilterForm(forms.Form):
    sys_type = forms.ChoiceField(choices=choices.SYS_CHOICES, required=True, label=u'类型')

def my_view(request):
    form = FilterForm(request.GET)
    if not form.is_valid():
        # 数据不合法
    else:
        # 通过 form.cleaned_data 获取数据

2.4 Permission Checks

  • Vertical privilege escalation
    An ordinary user must not access administrator user resources

  • Horizontal privilege escalation
    An ordinary user must not access the resources of other ordinary users that are not authorized

3. Error Code Specification

3.1 Error Code Design

  • Design error codes sensibly

Reference design 1

2000502
HTTP status codeService module codeSpecific error code

Reference design 2

ERROR_INVALID_FUNCTION
ERROR_PATH_NOT_FOUND
ERROR_TOO_MANY_OPEN_FILES
ERROR_ACCESS_DENIED

3.2 Error Messages Should Be Accurate and Useful

Two basic pieces of content need to be provided:

  • Return the error status and explain the reason
  • Tell the user how to resolve it

For example:

  • Calling the XXX interface failed, please retry later, or contact administrator XXX
  • Connecting to the MySQL database failed, please contact administrator XXX
  • The XXX you entered does not meet the format requirements, please enter data in the XXX format

3.3 Provide an Error Code Reference Table

Provide a page or interface showing error code to error details. For example: the interface /api/v1/error_code/ returns:

1
2
3
4
5
6
{
  "http_status_code - error_code - message": [
    [412, "Error_LOGIN_FRONT_NOT_GIFT", "礼品不充足"],
    [503, "ERROR_FAULT", "服务器内部错误"]
  ]
}

4. References


微信公众号
WRITTEN BY
微信公众号