This article was posted on Wed, 09 May 2018, 02:26 and is classified as js instance. Read 1,829 times, 1,568 times today

By zhangxinxu from www.zhangxinxu.com/wordpress/?… This article can be reproduced in full, but the original author and source need to be retained.

There are several interface management platforms in the industry, such as easyAPI, SOSOAPI, and YApi introduced in this article.

From the perspective of the team, the biggest effect of these interface platforms is the internal access of the team, standardization of API, management, cooperation and so on will become easier.

From a personal point of view, especially for front-end refacers who need to write high-fidelity pages, these interface platforms can simulate the return of more realistic data, natural cross-domain support, and dynamic features can be displayed without additional services.

I often write high-fidelity interaction prototypes, so I need to be able to have fairly realistic API request data, such as error, request delay simulation, extreme data processing, etc. Under the amway of my colleagues, I began to contact YApi and tried it out. Generally, it is ok. There are some small holes and some limitations.

I. Introduction of interface management platform YApi

The introduction here basically stands in individual use Angle of view.

Register first and use it without email verification.

“New Project” after entering:

Please fill in any of the following:

Then you can add interfaces:

Here can be arbitrary, anyway, later can be modified, such as:

After confirmation, enter the interface as shown below, where:

  • The “preview” function itself is used to copy the API request address provided by YApi;
  • “Edit” is to edit the request type, parameters, returned data, etc. If the simulated data is static, this TAB is the main battleground;
  • “Run” to install Chrome plug-in, but also turn the wall, can be ignored;
  • Advanced mocks are used to set deletion criteria and write your own JS code to return different data based on different parameters.

Let’s take a quick look at “editing” and “advanced mocks” with a few examples.

2. Understand Editing and Advanced Mocks

1. “Edit” without logic and filtering

Edit is suitable for static data simulation and can meet the needs of most API requests.

In “Basic Settings” we can choose whether to make a GET request or a POST request:

“Request Parameter Settings” can set the query parameters of an Ajax request. For example, we write a key and it is required:

There is a JSON-schema in “Return data Settings” :

In my opinion, design the data returned by the request in a visual way.

I personally prefer to look directly at the JSON code, so I leave it blank:

Here, the JSON code is not pure static JSON data, support some specific syntax rules, multiple data can be selected, the number of random number groups, etc., here is an official graph:

Many of these syntax specifications come from mock.js, as you can see here.

The syntax specification for mock.js consists of two parts:

  1. Data Template Definition (DTD)
  2. Data Placeholder Definition (DPD)

The former can realize numerical increment, numerical range, automatic counting, random quantity generation, regular character generation and so on. The latter can be understood as placeholders with specific identities. For example, @ID will generate random ids. You can think of it as placeholders for IDS, and there are many placeholder keywords, such as @email for email, @name for name, etc. Almost all of these words are placeholders.

Examples show

For example, we have the following mock JSON data:

{ "error": 0, "data|0-3": [{ "id": "@id", "value": "@name " }, { "id": "@id", "value": " @name @word" }, { "id": 5, "value", "< img SRC = \ \" icon_del. PNG \ "align = absmiddle > support small ICONS"}, {" id ": 8," value ":" < a href = \? "" key = \" > click < / a > "jump}]}Copy the code

Select 0~3 items randomly in array after “data”, loop 0~3 times.

Therefore, the template returns either zero or 12 arrays of data after “data”.

For example, the data returned from a request:

{ "error": 0, "data": [ { "id": "630000199003261731", "value": "Christopher Hall " }, { "id": "220000201107085094", "value": " Donald Thomas smse" }, { "id": 5, "value": "< img SRC = \ \" icon_del. PNG \ "align = absmiddle > support small ICONS"}, {" id ": 8," value ":" < a href = \? "" key = \" > click < / a > "jump}]}Copy the code

The “data” array in the template loops once, and the first two items in the array have a random ID and value because of the @ID and @name@word placeholders.

Seeing is believing, you can click here: l-ui.com/content/api…

The “Autocomplate function that dynamically returns data based on Ajax” that simulates the request sent by the Autocomplete function is the above template. For each input, the number of drop-down lists may be 0, 4, or 8…

2. You can return query data or request data

Sometimes we want the data returned by the API to be the data we submitted, or to contain the data we submitted, and YApi supports that.

{// The requested URL is /path? ${query.name} = ${query.name} = ${query.name} = ${query.name} = ${query.name} = ${query.name}Copy the code

${query.name} is the name parameter of the GET request and ${body.type} is the type parameter of the POST request.

Examples show

Suppose we add a new interface named “LULu form Submission”, select the POST request, and set the tel and code required fields to represent the phone number and verification code:

Meanwhile, the template data is as follows:

"{" error | 0-1:0," MSG ":" a certain probability of error ", "data" : {" tel ":" ${body. Tel} ", "code" : "${body. Code}"}}Copy the code

The “error” parameter has a 50% chance of returning a value of 1, that is, an error is considered; At the same time, the submitted phone number and verification code are returned intact.

Seeing is believing, you can click here: l-ui.com/content/exa…

The template above is for the form on the document page. Click the submit button and the error message shown below will appear 50% of the time:

50% probability is a success prompt, and the prompt contains the submitted mobile phone number, which is returned by YApi.

3. “Advanced mocks” with filtering capabilities and even complex logic

Advanced Mock has two tabs, one for Expectations and one for Scripts.

Where, “expectation” means that when you enter the request parameter as this, I return you a special data. For example, if the mobile number 11234567890 is an administrator account, and the administrator returns different data than the normal member, we can use the expected processing. “Script” is the ultimate solution to data forgery, which allows you to write JavaScript logic and create your own data.

Examples show

Suppose we create a new interface named “Lulu Rich Interaction List”, select the GET request, and perform the “advanced mock” directly.

This example will first look at the page, with complex logic, true paging lulu rich interactive list: l-ui.com/content/exa…

This page is paginated data is real pagination, search, batch delete, and even Easter eggs, all done by advanced mock, “expectation” and “script”, let’s take a look at each one.

First, a search for error in the input field demonstrates the error effect:

The relevant “expectations” Settings are as follows:

Then, back to the initial state, we select any list and delete it in batches. The list will be empty:

The relevant ‘expectation’ Settings are as follows, set the expectation condition, and return empty data when action is ‘delete’ :

Finally, take a look at how true paging and searching for random list numbers work in the first place. Just write our logic in the “script” input box, as long as we make sure the mockJSON data is what we want to return!

The complete code is as follows:

Var data = [{" id ": 1," title ":" extraction stars of flowers ", "time", "the 2015-07-20 good tidings" and "comment" : 7, "does" : False}, here in the middle of the omitted 47 / *... * / {" id ": 48," title ":" the emotional design of the product details ", "time" : "2015-06-01" they, "comment" : 0, "deleted": false }]; var current = params.current; var every = params.every; var begin = 0; var end = 0; var total = data.length; if (! Params. Key) {// Begin = (current-1) * every; end = every; } else { begin = Math.round(25 * Math.random()); end = Math.round(20 * Math.random()); total = end; } var dataGet = data.slice(begin, begin + end); mockJson = { error: 0, data: { total: total, data: dataGet } }Copy the code

Screenshots:

This is roughly 50 lists of data written down by default (which can be quickly generated using “edit templates” and placeholders) and then processed logically based on the requested parameters.

Params.xxxx gets the value of the XXXX parameter sent in either a POST or a GET request, so we can write the logic in a leisurely manner.

For example, if params.key is a search parameter, a list of random numbers is returned. If there is no params.key, it is considered an initial load, and the exact number of lists is returned based on the current paging page and the number of lists per page selected by the user. Then a high-fidelity rich interactive list is produced, and various experience and interaction problems can be well tested.

4. The priority relationship among the three

When requesting us to simulate data, rule match priority is expected > Custom Scripts > Normal templates.

If the first one matches data, the second one does not return data.

3. Limitations of YApi

HTTPS request is not supported. If the prototype page is HTTPS protocol, YApi can not be used directly, you can set up HTTPS page reverse proxy. Or use EasyApi, which in the meantime supports HTTPS, but I haven’t tested it personally.

Fourth, concluding remarks

This article is so long, mainly show individuals in the development of high-fidelity HTML pages, how to use API interface platform tools, so that our page interaction experience to achieve perfection, more robust, so that designers and developers see people love.

However, the knowledge points involved by individuals are only a small part of YApi. For more content, especially team Intranet deployment, API documents need to be referred to: yapi.ymfe.org/index.html

A little share, my notes and hope to help the API platform interested partners.

Finally, thanks to qunar mobile Big Front-end Technology Center for its open source contribution to this tool.

CSS World
Display my exclusive purchase code

// Want a tip? Click here. Got something to say? Click here.

    API
    The HTTP request
    mock
    mock.js
    yapi
    Dynamic API