Outputting request + response pairs to file

Hi

I’m currently using this (very helpful!) to output responses to file:

Is there a way to write the requests to file, too? Ideally I’d like to have file output with the request & response pairs logically named.

Has anyone done this or can anyone suggest a solution, please?
@singhsivcan - I believe you wrote the original server. Would it be possible to modify the script.js such that the requests are also outputted?

Thanks,

Frank

@frankdoylezw Try the following script by replacing your existing Tests script with the following one:
To edit the script: Right click the collection > Edit > Tests tab.

function getPayload (response) {
    // Request Separator
    let body = '\n\n=======REQUEST DATA=======\n\n';

    // Attach the stringified request
    body += JSON.stringify(pm.request);

    // Response Separator
    body += '\n\n=======RESPONSE DATA=======\n\n';

    // Attach the response
    body += response;

    return body;
}

// The opts for the server, also includes the data to be written to file
let opts = {
    requestName: request.name || request.url,
    fileExtension: 'json',
    mode: 'writeFile', // Change this to any function of the fs library of node to use it.
    uniqueIdentifier: false,
    responseData: getPayload(pm.response.text())
};

pm.sendRequest({
    url: 'http://localhost:3000/write',
    method: 'POST',
    header: 'Content-Type:application/json',
    body: {
        mode: 'raw',
        raw: JSON.stringify(opts)
    }
}, function (err, res) {
    console.log(res);
});

What I am doing here is appending the payload of the request also in the data going to the server along with the response.

1 Like

@singhsivcan Thank you - that is exactly what I was hoping for! Your scripting skills are something to aspire to, for sure :slight_smile:

I had only a single query, please: the counts of requests in the collection vs tests vs files written do not tie up, for some reason. I have 182 tests in 138 requests, but when I run that collection only 63 files are written? Am I missing something, please?

1 Like

@frankdoylezw you probably have multiple requests with the same name, and the files are being overwritten.

Please pull/clone the latest changes from here: https://github.com/sivcan/ResponseToFile-Postman

Next, you can edit the opts in the Tests script to the following:

// The opts for the server, also includes the data to be written to file
let opts = {
    requestName: request.name || request.url,
    fileExtension: 'json',
    mode: 'writeFile',
    uniqueIdentifier: true,
    responseData: getPayload(pm.response.text())
};

The uniqueIdentifier property makes sure that a random number is appended to every file name, thus everytime it’ll create a new file and write your request and response to it.

Let me know if it works for you :slight_smile:

1 Like