【问题标题】:Automatically call API from Postman and generate a JSON response in a file自动从 Postman 调用 API 并在文件中生成 JSON 响应
【发布时间】:2022-07-18 04:24:25
【问题描述】:

我正在使用 Postman 调用 API。我有几个要打电话,所以我做了一个集合,我可以运行它。 我试图将 API 的结果保存在一个文件中(JSON 很好),然后每次调用 API 来更新文件。是否可以为每个 API 调用自动保存响应? 请问我该怎么做?我已经尝试过 newman,但我没有成功。谢谢。

【问题讨论】:

    标签: postman postman-collection-runner


    【解决方案1】:

    设法在 JSON 文件中获取结果,尽管我必须手动更新它。在Youtube 上关注此视频,这是 .js 中的代码(如果将来对任何人有帮助)

    const newman = require('newman'); // require newman in your project
    const fs = require('fs');
    
    // call newman.run to pass `options` object and wait for callback
    newman.run({
        collection: require('./name_of_postman_collection.json'),
        reporters: 'cli'
    }).on('beforeRequest', (error, data) => {
        if (error) {
            console.log(error);
            return;
        }
        console.log(data);
    })
    .on('request', (error, data) =>{
        if (error) {
            console.log(error);
            return;
        }
    
        const fileName = `response ${data.item.name}.json`;
        const content = data.response.stream.toString();
    
        fs.writeFile(fileName, content, function (error) {
            if (error) {
                console.error(error);
            }
        });
    });
    
    

    我仍在尝试找出如何自动化该过程,例如每 2-3 小时刷新一次文件。

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 2012-09-23
      • 2020-05-12
      • 2019-04-20
      • 1970-01-01
      • 2021-04-16
      • 2020-03-22
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多