In projects with separate front and back ends, the quality of the API interface directly affects the logic of the front-end page rendering. After years of “running-in” with backend developers and products, the author summarizes a relatively complete and front-end friendly interface specification. I hate the back end, but on the other hand, it helps the back end improve.

0. Design specification principles

1. The front-end should only focus on rendering logic, not data processing logic. The data returned by the interface should be directly displayed on the interface. 2. A function should avoid multiple interface nested calls to obtain data, and the background should handle one-time return. 3. The response format should be JSON, and multi-level JSON should be avoided; 4. If the back-end interface needs to refresh data in real time, it should not require the front end timer polling, but provide functions such as webSocket.Copy the code

According to this principle, the data returned by the back end should be WYSIWYG data, not complex JSON layer by layer, requiring the front end to handle complex de-duplication, sorting, depth copy, deformation, etc. The front end does not have to worry about data structure inconsistency when rendering each div and each table cell.

1. The whole process of interface formulation

Front-end requests generally use HTTP. This section uses HTTP as an example.

Protocol type of the HTTP request

The HTTP methods (using SQL keywords) listed below should be used:

  • GET(SELECT) : Retrieves one or more resources from the server.
  • POST(CREATE) : Creates a resource on the server.
  • PUT(UPDATE) : Updates the resource on the server (the client provides the full resource after the change).
  • PATCH(UPDATE) : Updates the resource on the server (the client provides the changed properties), which is less used
  • DELETE(DELETE) : Deletes resources from the server.

Here are some examples:

  • GET/schools: List all the schools
  • POST/ School: Build a new school
  • GET/school/{id} : Gets information about a specified school
  • PUT/school/{id} : updates information about a specified school (provide all information about that school instead of letting the front end get it through another interface)
  • PATCH/school/{id} : update information about a specified school (provide partial information about that school)
  • DELETE/school/{id} : Deletes a school

Parameter definitions for HTTP requests

Different HTTP methods have different parameter transmission modes, as follows:

Query refers to the path of the parameter, body refers to the requestBody requestBody

  • GET: the path and query
  • POST: the path & body
  • PUT: path & Query & body
  • PATCH: path & Query & body
  • DELETE: the path and query

Note:

1. Do not place parameters in positions that do not appear in the table above. For example, do not place parameters in the body of the GET method. 2. Parameter naming follows the small hump naming method. 3. Ensure that the length of the parameters passed in path and Query is controllable. If the parameter length exceeds 2000 characters (depending on the browser), the request may fail. When the request cannot keep the parameter length manageable, you cannot place the parameter in path or Query and must use an HTTP method that supports the body parameter, such as POST. 4. The parameters passed in path and query must be primitive types, and serialized JSON objects cannot be passed! Otherwise the front end will try/catch and parse. 5. The body parameter must be a valid JSON object or formData. }Copy the code

HTTP response result definition

For different operations, the server should return results to the user that conform to the following specifications.

  • GET/ COLLECTIONS: Returns a list (array) of resource objects
{
    RetCode: 0.Message: 'ok'.Action: 'collections'.Data: [{Id: 1.name: 'collection1'. },... ] }Copy the code
  • GET/collection/resource: Returns a single resource object
{
    RetCode: 0.Message: 'ok'.Action: 'collectionResource'.Data: {
        Id: 1.name: 'collection1'. }}Copy the code
  • POST/collection: Returns the newly generated resource object
{
    RetCode: 0.Message: 'ok'.Action: 'collection'.Data: {
        Id: 1.name: 'collection1'. }}Copy the code
  • PUT/collection/resource: returns the full resource object.
  • PATCH/collection/resource: returns the full resource object.
  • DELETE/collection/resource: Returns an empty document
{
    RetCode: 0.Message: 'ok'.Action: 'collectionResource'.Data: {}}Copy the code

Note:

1. All returned data must be valid JSON. Try to return object or array (except binary file download). If the data contains properties of type array, if the data is empty, try to return an empty array [] instead of null. 2. Avoid using map <'key', 'value'> form for returning data! If data is returned in a relevant format, convert it to array. 3. If no data needs to be returned or an error is reported, the following fixed fields are returned: {RetCode: number; // Back-end status code Message: string; // Request return message Action: string; Keyword/request/response Data: Object | Array; 4. The return value should avoid unnecessary information or additional data structures, and only include necessary data. Essential data refers to data that needs to be rendered by the front end. 5. All back-end exceptions are returned in the form of '500' status codes. Additional information can be added appropriately.Copy the code

URL specification

Can follow this example: GET | HTTPS] [HTTP: / / host: port/studio/API/v1 / module/component name name/menu name/interface name: param

Note:

1. Do not use uppercase letters. For example, write the invitation code as invitationcode instead of invitation_code. Use nouns for resource sets, use plural forms (to ensure consistency across ALL API URIs), and do not use verbs; 3. Each resource should have at least one URI that identifies it, and should follow a predictable hierarchy to improve understandability and thus usability; 4. The object must be a noun. The URL cannot have verbs, only nouns, API nouns should also use plural, the object is the API URL, is the OBJECT of the HTTP verb. It should be a noun, not a verbCopy the code

Is 🌰 :

  • GET/classes: List all classes
  • POST/classes: Create a new class
  • GET/classes/{classId} : Gets information about a specified class
  • PUT/classes/{classId} : Updates the information of a specified class (generally tends to update the whole class)
  • PATCH/classes/{classId} : Updates information about a specified class.
  • DELETE/classes/{classId} : Delete a class
  • GET/classes/{classId}/teachers: lists all the teachers in a specified class
  • GET/classes/{classId}/students: Lists all students in a specified class
  • DELETEClasses /{classId}/ teacherId /{teacherId} : Delete information about the specified teacher in a specified class

Example:

  • /getAllclasses
  • /createNewclass
  • /deleteAllActiveclasses

Plural or singular URL Question: Since URLS are nouns, should they be plural or singular? There is no universal rule, but a common operation is to read a collection, such as GET /articles (read all articles), which is obviously complex, and GET a single one using GET /article/2. Of course, you can always use plural urls for uniformity, such as GET /articles/2.

Multi-level URL processing: When there is a lot of resource information queried, multi-level parameters often appear in the URL. Here we will discuss the following three situations:

  1. Query information indicates that when the layer has a unique ID, the query information is placed in path to construct a unique query path, for example:

# GET /authors/12/categories/2

  1. The query information belongs to the state filtering of the counterpart layer information. The query information is placed in query, for example:

# GET /articles? published=true

  1. The query information contains both the local layer ID and the filtering information. Put the ID and filtering information in the path and query respectively, for example:

# GET /authors/12/categories/2? published=true

HTTP status code constraints

Every time a client requests something, the server must respond. The response consists of HTTP status code and data. The HTTP status code is a three-digit number divided into five categories.

# 1xx: Related information # 2XX: operation successful # 3XX: redirection # 4xx: client error # 5xx: server errorCopy the code

See W3C on HTTP Status Code definitions for the status code specification

Paging and search interface constraints

Paging interface is widely used in tabular interaction in large data volume scenarios. Even for simple list elements, more than 500 items can cause the front end to stall, and more than 5,000 items (depending on browser and computer configuration) can cause the front end to crash. Any interface that cannot be guaranteed to limit the number of interface returns to a smaller order of magnitude (less than 100) should consider supporting back-end paging; If the number of results returned is uncontrolled (such as containing user-generated data), back-end paging must be supported.

Here is an example request:

GET an interface

? page={page}&size={size}

POST interface

1 / / format
{
    page: number;
    size: number;
    total: number; // Total amount of data
}

2 / / format
{
    Limit: number;
    Offset: number
    Total: number; // Total amount of data
}

// Where page is the current request page, is a positive integer starting from 0;
// size indicates the current page size. The value can be 10 or 20. In theory, any positive integer must be supported. In particular, if the value is -1, you can specify that the value can be queried all
/ / the size Limit
// Offset is the relative Offset, which is a positive integer starting from 0
Copy the code

It is important to note that if filtering and sorting functions occur in the interaction, they will require back-end support if necessary. Arguments are acceptable in a Query if they are guaranteed to be no longer than a certain length. Array arguments can be passed as comma-concatenated fields, for example:

? status=RUNNING,COMPLETE,ERRORCopy the code

Special type processing

  1. For Boolean types, true/false fields are used in JSON data transfer.
  2. As for date types, JSON data is transmitted using Unix time, and the specific date display format is processed by the front end.

2. Precautions

Any kind of interface change can have an impact on the front end, such as field name change, field addition or subtraction, field type change, request parameter type change, etc. Principle After interface interconnection is complete, there should be no modification in any form. If the interface must be changed, the front-end developer should be notified in time and the interface should be connected again.

Fields with the same meaning should be the same in the same set of functional interfaces (add, delete, change, and search). In interface design, interfaces that operate on the same entity should try to ensure that the data structure of the entity is consistent in parameters and return values, and avoid data object conversion at the front end.

reference

Ruan Yifeng RESTful API Design Guide

# Representational state transfer

Hypertext Transfer Protocol

# Source of inspiration - Transwarp General Technical Group Front End Team JIRA documentation - Front and back end interface specificationCopy the code