Official website: https://www.apifox.cn/?utm_source=dqsj
front end pain
As a front-end, when is the most painful?
For each iteration, the requirements documents and design drafts come out, and the static pages are finished in two days. But doing the front-end is not simply to put the data spit out from the back-end on the page, and there are also various front-end processing logic.
Before the back-end interface came out, I had to test the front-end effect while writing code, and there was no real data. Some people suggest to use the Mock tool, but each interface has to write its own Mock rules, which is a waste of time.
After I finally wrote the interface at the back end, and after a couple of joint debugging, the data of many fields did not match the data of my Mock, and the code had to be changed again.
Every iteration is a torture.
It's the kind of powerlessness that clearly knows that the whole team can be more efficient in this place, but it just can't do it.
Dawn of Hope
Until one day, I came across this artifact. My efficiency has increased by 100%.
I can get the mock data I need in the most effortless and elegant way without even any configuration. Moreover, all kinds of crashing front-end and back-end data docking problems encountered during the joint debugging are all gone! See! !
This is it ⬇️
I researched for a whole week, and the more I researched, the more frightened I became. This tool is too powerful, completely beyond my expectations, just like Zhang Wuji's practice in "Eternal Heaven and Dragon Slayer" shifted the universe.
I used to think that you can set the interface or whatever, and it has nothing to do with my front end. Just set the spit data and give it to me.
I used to think that writing interface documentation is a complete waste of time, and it’s not good to change the interface while writing code.
It wasn't until I came across this artifact that I understood how much better work habits could improve my efficiency.
I am different now. I think this artifact can double the work efficiency of all front-end programmers in China. I also hope that you who are reading this article can make good use of this tool.
Okay, I'm going to do my work next.
Layer 1: Smart Mock
Apifox is an API collaboration tool, and the basis for using it to make mock data is API documentation. The API maintained in Apifox can generate good-looking online interface documents, one-click debugging like Postman, testing like JMeter, and direct Mock data. But today we only talk about Mock.
First, you need to create an interface in Apifox, define request parameters and return data structure.
OK, save. Finish!
………………
Wait a minute? What about Mock? How is it done? Where are the Mock rules written?
Really done.
Apifox will automatically start a local Mock service. I copy the Mock address automatically generated by Apifox and open it with a browser to see the effect.
It's that simple! It's so convenient!
what! None are needed! Configure!
In fact, most of the API return data we encounter are generic, such as username, mobile phone number, address, email, timestamp, and so on. But it's very troublesome if you want to write Mock rules. How do you generate a Chinese name that looks reasonable?
In Apifox, this becomes the easiest thing to do, even completely insensitive. As long as the returned data structure is well defined when writing the API documentation, this is done. Apifox will intelligently generate mock data based on field names without any configuration.
For example, if a field name in the data structure returned by the interface is called username, it will get "Cheng Min", "Wang Ning", "An Muxi" and "Li Mabi".
If the field name is phone, you will get 15237829132, 18907284633.
If the field name is city, it will get Hangzhou City, Kaohsiung City, and Bortala Mongolian Autonomous Prefecture.
Even if your field name is icon, it will return an image URL, which is really a png image when opened!
If your team is using other tools such as Swagger to manage API documents, you can also import them into Apifox (Apifox supports data import in more than 20 formats, and you can also set up automatic import at regular intervals), you can also use this smart Mock, which is also automatically generated with zero configuration. All Mock data.
There is no need to worry about any Mock data configuration issues. As long as the interface is set, the Mock data will be there, and I can write any front-end code.
Layer 2: Custom Smart Mock Rules
Some students asked, you are all preset to die, right? How do I know what parameter name to write and what data will you give me Mock? Well, this is the second layer of Apifox Mock functionality: custom smart Mock rules.
There is a set of Mock rules built in Apifox. When our return field name matches one of the rules, a random value (Mock.js grammar rule) will be generated according to the corresponding rule.
The matching method of field names supports wildcards and regular expressions. For example, as long as the field ends with "url", it will get a correct URL; if it starts with "mail", it will get an email address.
If it ends with "time", it will automatically mock the value according to the data type of the field: if it is a string type, it will return a time in 'yyyy-mm-dd hh:mm:ss' format; if it is an integer type, it will return a timestamp. Is it smart? !
There are built-in rules, and of course new ones can be customized.
For example, if our company's order id is a ten-digit number starting with "DD", I can create a new string type rule, write "*orderid" for the matching rule, and write a regular expression for the mock rule: @regexp(/DD\d{10}/)
. In this way, as long as any of my interface return fields end with "orderid", I will get a return value like "DD1284918414".
Layer 3: Return to advanced field settings
Some classmates said that yours is a more general data type, but I still have many types that are not so general. For example, pets on the shelves of pet stores have three states: available for sale, sold, and to be put on the shelves. How to Mock them out?
In Apifox, each field has a concept of "advanced settings" when defining the interface to return the data structure. For example, the listing status of my pet can also be defined as an enumeration, and the optional values of the enumeration are ("available", "sold", "pending"). If the interface is defined like this, then Mock will automatically take values from these three strings.
There are not only enumerations in the advanced settings of this field, but also length ranges, regular rules, etc. can be set. If the field type is a number, you can also set the maximum and minimum values, etc.
If you are familiar with JSON Schema, you can also write Schema directly, and the definition space will be larger.
And we have to pay attention: At this time, what we set is not the Mock rule, but the data structure definition of the interface return value. This will take effect on the automatic verification function of interface debugging. If the data returned by the back-end interface does not meet the requirements here If set, Apifox will return a "Data structure verification failed", which tells the backend that your interface returns the wrong data structure.
And our Mock data is also automatically generated based on the settings here, without any additional configuration.
If you are not happy, you can directly take a screenshot and go to the back end.
The fourth layer: interface-level custom Mock
Some students said, then I have another scenario, such as my username field, the data definition actually allows him to enter any string, but my mock needs a real name, and cannot be defined by the field.
Moreover, what you just demonstrated are Chinese names, and my clients are all European and American.
Ah, finally a little bit of rules for specific interfaces.
In Apifox, when defining a data structure for an interface, you can set Mock rules for each field, and you can directly select a series of commonly used Mock rules. In fact, all common data types are complete. For example, if I need a foreign name, I can write @name here, and run it to get English names like "Larry Smith" "Susan Lee".
If the smart Mock mentioned above does not satisfy you, you can override the built-in rules by setting the rules here. Mock.js and regular expressions are supported here, as long as the rules you can think of, all Mock can come up with.
Moreover, Apifox supports the definition of data model (Schema), different interfaces can reuse the same data model, and the rules defined in the model will take effect in all the interfaces that reference it, without any additional configuration.
Mock once, enjoy for life.
Layer 5: Advanced Mock
There are also some students, they said, I hope I can define it myself: according to different parameter values, return different data.
For example, if the parameter pet ID I request is 1, it will return a pet data on sale, and if the pet ID is 2, it will return a sold pet data. My front end can make pages in several states.
Well, the fifth layer of Apifox mock is for you.
There is an "Advanced Mock" tab in the "Interface Management" of Apifox. Here we can add "expectations".
An expectation is that when your request contains a parameter value, specific data is returned.
For example, I set my pet No. 1 to be on sale, pet No. 2 to be sold, pet No. 3 to have no record, and pet No. DDD to be "incorrect ID format". I set these return values all right.
After that, when the request parameter I send is 1, it returns a pet information on sale; 2 returns a sold pet; 3 returns a "404 not found", and 4 returns an "Invalid Param".
Ah, I can simulate a backend server!
I'm the pet with the malformed ID
Layer 6: Advanced Mock Template Syntax
You think this Mock function is already very powerful, right? I mentioned Zhang Wuji at the beginning, do you know how many layers Zhang Wuji's Great Shifting of the Universe has?
When we enter the advanced Mock writing expectations, an example will pop up when the mouse is placed on the support "Mock.js syntax".
What is this example about? We can actually try it out in Apifox.
It produces an array in JSON format!
There are a total of 20 sets of ids and names. For example, if you want to generate a two-dimensional form filled with data in the front end, you can mock a whole set at one time! All it takes is just a few lines of code!
Let's look back at this grammar example. In normal JSON, two pieces of "for" code wrapped in curly brackets and percent signs are inserted, which is the JS template grammar (Nunjucks grammar), which can be used to generate complex data structures!
Not only for loops are supported! Also supports if branches! Regular expressions are also supported! Also supports calling functions!
you say! Is it enough to have me (plus Apifox)! What to do with the back end!
Layer 7: Advanced Mock Custom Scripts
besides? ? ?
This is a powerful feature only available in the latest Apifox 2.1.7.
The new version of Advanced Mock adds a "script" Tab. What is the use of this advanced Mock custom script?
Let's consider a practical case. I have a GET interface for "query pet list", its request parameters are page and pageSize, and the values are 6 and 10, which means that I want to check the sixth page of the pet list, and each page is limited to 10 records. This is a very common page-turning scenario.
The returned data is first an array, and each entry is a pet on this page that I found. There is also a page and total below, that is, the current page number and the total number of records. Request, the returned Mock data is a series of pet information.
Go to the following page field, there is a problem: what I am requesting is clearly the data of the 6th page, what does it mean that you return the page to me is the 10th page.
When I turned the page again, a new question appeared: it was still 25 pages just now, but when I turned the page, it became a total of 40 pages? ? ? And the next page of page 10 is page 22?
What do I want the data from Mock to look like? It should be the number of pages I requested, and the data returned is the number of pages; then the total number of pages should be fixed, and will not change because I turn forward and back.
At this time, we need custom scripts for advanced Mock.
There is a sample code on the right side of the custom script interface, let's read it carefully.
- Obtain the JSON data automatically generated by the system through fox.mockResponse.json() and assign it to the variable responseJson.
- Get the actual request parameter page through fox.mockRequest.getParam('page') and assign it to the page field in the variable responseJson.
- Rewrite the total field of responseJson to 120.
- Set the modified variable responseJson to the mockResponse through fox.mockResponse.setBody(responseJson), thus modifying the JSON data returned by the system.
In this way, the number of pages I request is the corresponding number of pages returned, and then the total number of pages remains the same as 12 (120 divided by 10 per page).
This custom script can do a lot of things. For example, I need to mock out different avatars according to the gender of the user, male or female; or Mock out the date of birth first, and then use the date of birth to assemble the corresponding ID number, etc., It can make the data from our Mock match each other.
The objects that the custom script can operate are the fox.mockRequest and fox.mockResponse, which can obtain request parameters, Header, Cookie, modify the response Body, HTTP status code, etc., and even the response delay can be customized.
You say cow is not cow!
Download it now
The seven-layer ladder with Apifox Mock function is finished.
If you're a front-end and read this, I think you should give it a round of applause.
Apifox's Mock function is totally worth you to click to read the original text and then download it. You can throw away all the other APIs and mocking tools.
Remember to download the Apifox desktop version to use, the WEB version does not support the Mock function yet.
As a final reminder, Mock is only a small part of Apifox's capabilities. Apifox = Postman + Swagger + Mock + Jmeter, it's much more than this article.
Official website: https://www.apifox.cn/?utm_source=dqsj
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。