Edit the page Number in the headers and loop it till the last page POSTMAN

If I understand your question correctly, you are trying to access all the pages of a paginated endpoint. This is better done by looping on the current request using postman.setNextRequest(requestName), where you set the requestName to the same request.

You can use variables for the query params/headers of your request that control the pagination (depending on what the endpoint requires). You can use โ€œPre-request Scriptโ€ to set these values based on each iteration, and avoid looping once the total number of records have been received. You can use a variable to store the data across all the pages. Assuming this variable is an array, you will have to push to that array in the โ€œTestsโ€ tab. In the final loop, you can access that variable which by then should have all the data that you pushed to it in the loop.

Example

Your pre-request script can look like this:

const offset = parseInt(pm.variables.get("_rec_offset"));
if (!offset) {
    pm.variables.set("_rec_offset", 0);
}

pm.variables.set("_rec_limit", 10);

And then, the Tests tab can push to the data like this:

// Push the current dataset to this array
let results = [];

// If this is not the first loop, load existing data
if (pm.variables.get("_rec_results")) {
    results = JSON.parse(pm.variables.get("_rec_results"));
}

let jsonData = pm.response.json();

// Process pagination
if (total > offset + limit) {
    // Needs paginated run
    offset = offset + limit;
    // Loop on current request
    postman.setNextRequest("Current request name");
    // Save offset
    pm.variables.set("_rec_offset", offset);
    // Add current dataset to the variable that stores all results
    pm.variables.set("_rec_results", JSON.stringify(results));
} else {
    // Final run. Set the temporary results into a final variable
    pm.environment.set("results", JSON.stringify(results));
}

Bonus

I have added an example collection which you can import by clicking the Run in Postman button below. The first request in this collection does exactly this sort of pagination on another API.

Run in Postman

4 Likes