Automatically call API from Postman and generate a JSON response in a file

Viewed 170

I am using Postman to call API. I have a couple to call, so I made a collection and I am able to run it. I am trying to get the results of the API saved in a file (JSON is fine) and then everytime I call the API, to get the file updated. It is possible to automatically save a response for each API call? Could you please how can I do it? I have tried with newman, but I`m not being succesful. Thank you.

1 Answers

Managed to get results in JSON files, although I have to update it manually. Followed this video on Youtube and this is the code in .js (if helps anyone in the future)

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);
        }
    });
});

I am still trying to find out how to automate the process, to get refreshed files every 2-3 hours for example.

Related