Apifox visual response function makes your interface data clear at a glance

When the response data structure returned by the interface is very complex, full of nested objects and arrays, which may also contain the URL of the image, if you want to find specific information, you need to constantly scroll up and down the JSON response, trying to find the required  fields  . Not only is this annoying, it wastes valuable time.

Apifox provides a programmable method to convert complex JSON response data into an intuitive graphical interface , which greatly improves the efficiency of data lookup, improves the readability of responses, and reduces possible errors.

For example, you can present hierarchically complex data structures through tables:

picture

Convert SVG format images to Base64 encoding format for presentation:

picture

You can even introduce third-party libraries (such as Echarts, D3.js, etc.) to display charts directly:

picture

Implementation ideas

The way to implement visual response is very simple. Add a custom script in the "post operation" of the interface, and then   pass the parameters through the pm.visualizer.set() function. The syntax of this function is as follows:

 
 
pm.visualizer.set(template,data)
  • template : required. HTML template string. This string will eventually be rendered below. You can write in the template to load an external css style sheet, or pass 
  • data : optional. Receives an object and passes data into the template.

For example:

 
 
const template = `<div>{
   
   {name}}</div>`; pm.visualizer.set(template, { name: 'Apifox'}) // 渲染出来的结果为: <div>Apifox</div>

Some common examples are listed below.

Visualize regular pictures

You can visualize images in JPEG, PNG, WebP and other formats. For example, an interface returns the following data structure:

 
 
{ "code": 0, "message": "ok", "data": { "imgHead": "https://cdn.apifox.cn/logo/apifox-logo-64.png" }}

To visualize images, you need to add a custom script in the post-operation of this interface.

The first step is to obtain  the interface  data (picture path):

 
 
// 1、获取图片路径 let imgURL = pm.response.json().data.imgHead;

The second step is to add the HTML template. template Template is used to render interface data. { {}} is used to wrap variables in the template:

 
 
// 2、添加 HTML 模板 let template = `    <img src="{
   
   {imgURL}}"/>`;

The third step is to apply the pm.visualizer.set() function and pass the template and data into it:

 
 
// 3、设置 visualizer 数据。传模板、解析对象 pm.visualizer.set(template, { imgURL });

The result is as follows:

picture

Visualize SVG images

SVG images can render them visually (such as some verification code images). For example, an interface returns the following data structure:

 
 
{    "code": 0,    "message": "ok",    "data": {        "img": "<svg xmlns="http://www.w3.org/2000/svg">\n  ......................  </svg>"    }}

To realize SVG image visualization, you need to add a custom script in the post-operation of this interface.

The first step is to obtain the interface data (picture path) and convert it into Base64 encoding through the btoa() method:

 
 
// 获取 SVG 图片数据let svgContent = pm.response.json().data.img; // 将 SVG 内容转换为 Base64 编码let imgBase64 = `data:image/svg+xml;charset=utf-8;base64,${btoa(svgContent)}`;

The second step is to add the HTML template. Use { {}} to wrap variables in templates :

 
 
// HTML 模板let template = `    <img src="{
   
   {imgBase64}}" />`;

The third step is to use the pm.visualizer.set() function and pass in the template and data:

 
 
// 3、应用函数pm.visualizer.set(template, { tableData });

The result is as follows:

picture

Of course, under normal circumstances when conducting  interface testing  , if you encounter a scenario where you need to enter a picture verification code, you usually add a whitelist to the test account and skip the picture verification code verification.

Visual table

A complex JSON data structure that can present data more intuitively in the form of tables. For example, an interface returns the following data structure:

 
 
{    "code": 0,    "message": "ok",    "data": [        {            "id": 1,            "name": "Apifox",            "logo": "https://cdn.apifox.cn/logo/apifox-logo-64.png",            "description": "API 文档、API 调试、API Mock、API 自动化测试、API 一体化协作平台"        },        {            "id": 2,            "name": "ChatGPT",            "logo": "https://cdn.apifox.cn/app/project-icon/custom/20230831/d925d46b-dca7-4bfe-9fee-524c93ba9549.png",            "description": "基于人工智能技术的对话式语言模型"        },        {            "id": 3,            "name": "GitHub",            "logo": "https://cdn.apifox.cn/app/project-icon/custom/20220701/d5a806db-8567-4e50-a4f8-341581c542ae.png",            "description": "一个基于云端的代码托管平台"        },                ............    ]}

To implement JSON visualization, you need to add a custom script in the post-operation of this interface.

The first step is to obtain the interface data:

 
 
// 1、获取接口数据let tableData = pm.response.json().data;

The second step is to add the HTML template. If you want to loop through array data, start with { {#each variable name}} and end with { {/each}}, where the variables are wrapped with { {}}:

 
 
// 2、添加 HTML 模板var template =`<style>    table {        border-collapse: collapse;        width: 90%;    }    table, th, td {        border: 1px solid #ddd;    }    th, td {        padding: 10px;        text-align: center;    }    th {        background-color: #f2f2f2;    }    img {        max-width: 32px;        max-height: 32px;    }</style> <table>    <thead>        <tr>            <th>ID</th>            <th>Name</th>            <th>logo</th>            <th>description</th>        </tr>    </thead>    <tbody>        {
   
   {#each tableData}}        <tr>            <td>{
   
   {id}}</td>            <td>{
   
   {name}}</td>            <td><img src="{
   
   {logo}}"/></td>            <td>{
   
   {description}}</td>        </tr>        {
   
   {/each}}    </tbody></table>`

The third step is to apply the pm.visualizer.set() function:

 
 
// 3、应用函数pm.visualizer.set(template, { tableData });

The result is as follows:

picture

Visual charts

In the custom script of the post-operation, you can also introduce third-party libraries (such as Echarts, D3.js, etc.) for chart rendering. The operation steps are the same as above.

For example, this Echarts visual chart script:

 
 
var template = `    <div id="container" style="height: 500px;width: 90%"></div>    <script src="https://fastly.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>      <script>    var dom = document.getElementById('container');    var myChart = echarts.init(dom, null, {      renderer: 'canvas',      useDirtyRect: false    });    var app = {};        var option;    option = {      title: {        text: 'Stacked Area Chart'      },      tooltip: {        trigger: 'axis',        axisPointer: {          type: 'cross',          label: {            backgroundColor: '#6a7985'          }        }      },      legend: {        data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']      },      toolbox: {        feature: {          saveAsImage: {}        }      },      grid: {        left: '3%',        right: '4%',        bottom: '3%',        containLabel: true      },      xAxis: [        {          type: 'category',          boundaryGap: false,          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']        }      ],      yAxis: [        {          type: 'value'        }      ],      series: [        {          name: 'Email',          type: 'line',          stack: 'Total',          areaStyle: {},          emphasis: {            focus: 'series'          },          data: [120, 132, 101, 134, 90, 230, 210]        },        {          name: 'Union Ads',          type: 'line',          stack: 'Total',          areaStyle: {},          emphasis: {            focus: 'series'          },          data: [220, 182, 191, 234, 290, 330, 310]        },        {          name: 'Video Ads',          type: 'line',          stack: 'Total',          areaStyle: {},          emphasis: {            focus: 'series'          },          data: [150, 232, 201, 154, 190, 330, 410]        },        {          name: 'Direct',          type: 'line',          stack: 'Total',          areaStyle: {},          emphasis: {            focus: 'series'          },          data: [320, 332, 301, 334, 390, 330, 320]        },        {          name: 'Search Engine',          type: 'line',          stack: 'Total',          label: {            show: true,            position: 'top'          },          areaStyle: {},          emphasis: {            focus: 'series'          },          data: [820, 932, 901, 934, 1290, 1330, 1320]        }      ]    };    if (option && typeof option === 'object') {      myChart.setOption(option);    }    window.addEventListener('resize', myChart.resize);  </script>`pm.visualizer.set(template);

The result is as follows:

picture

Overall, the process of realizing response data visualization can be boiled down to three simple steps: first, obtain the interface data; second, add the HTML template; finally, use the pm.visualizer.set() function to complete the visualization operation.

Knowledge expansion:

Guess you like

Origin blog.csdn.net/m0_71808387/article/details/132897408