postmanpostman-collection-runner

Postman - Loop same or different request with different query params in a collection


I am trying to add some new requests to existing collection. The first request is getting the values, which gives me the result as an object array with ids. I want to use the ids from the object and perform an update with another request.

How can I iterate over the ids for the next request.

I tried using the pm.collectionVariables and assign the values and used setNectRequest in a for loop. It only executes once with the last id.

My GET request:

URL: {{api_url}}/resourcetypes

Tests:
let responseJson = pm.response.json();
let filteredResourceTypesIds = responseJson.values.map((type) => type.id)

pm.collectionVariables.set("filteredResourceTypesIds", filteredResourceTypesIds);

if (!filteredResourceTypesIds || filteredResourceTypesIds == null || filteredResourceTypesIds == undefined) {
    return;
}

for (i = 0; i <= filteredResourceTypesIds.length; i++) {
    console.log(i)
    pm.collectionVariables.set("resourceTypeId", filteredResourceTypesIds[i]);
    postman.setNextRequest("Add Property");
}

My Patch Request :

URL: {{api_url}}/resourcetypes/{{currentRsourceTypeId}}

Pre-script: let currentResourceTypeId = pm.collectionVariables.get("resourceTypeId");


Solution

  • In the Get Resource IDs API,setting array variable

    In tests tab

    let filteredResourceTypesIds = responseJson.typeIDs.map((type) => type.id)
    pm.collectionVariables.set("filteredResourceTypesIds", JSON.stringify(filteredResourceTypesIds));
    

    In the Patch Resource ID API, get array variable and shift

    In Pre-request Script tab

    let filteredResourceTypesIds = JSON.parse(pm.collectionVariables.get("filteredResourceTypesIds"));
    pm.collectionVariables.set("currentRsourceTypeId", filteredResourceTypesIds.shift())
    pm.collectionVariables.set("filteredResourceTypesIds", JSON.stringify(filteredResourceTypesIds));
    if (filteredResourceTypesIds.length > 0){
        postman.setNextRequest("Update Resource"); // <- Patch Request Name
    }
    

    Mocking Server

    It provides Two APIs

    GET http://localhost:3000/api/resourcetypes
    
    PATCH http://localhost:3000/api/resourcetypes/:id
    

    mocking-server.js

    const express = require('express');
    const bodyParser = require('body-parser');
    
    const app = express();
    const port = 3000;
    
    app.use(bodyParser.json());
    
    
    // Mock data for demonstration purposes
    const resourceTypes = [
        { id: 1, name: 'Type A' },
        { id: 2, name: 'Type B' },
        { id: 3, name: 'Type C' }
    ];
    
    app.get('/api/resourcetypes', (req, res) => {
        res.json({ typeIDs: resourceTypes });
    });
    
    app.patch('/api/resourcetypes/:typeId', (req, res) => {
        const typeId = parseInt(req.params.typeId);
        const updateData = req.body;
    
        // Find and update the resource type
        const resourceType = resourceTypes.find(type => type.id === typeId);
        if (resourceType && updateData) {
            Object.assign(resourceType, updateData);
            res.json(resourceType);
        } else {
            res.status(404).json({ error: 'Resource Type not found' });
        }
    });
    
    app.listen(port, () => {
        console.log(`Server running on http://localhost:${port}`);
    });
    

    Install Dependencies

    npm install express body-parser
    

    Run Mocking Server

    node mock-server.js
    

    Postman Collection File

    Import as 1-demo-postman-collection.json

    {
        "info": {
            "_postman_id": "ef4bd661-b94e-4099-b512-a2268c5d5fc5",
            "name": "1-demo",
            "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
            "_exporter_id": "1826150"
        },
        "item": [
            {
                "name": "Get Resource Types",
                "event": [
                    {
                        "listen": "test",
                        "script": {
                            "exec": [
                                "const responseJson = pm.response.json();",
                                "let filteredResourceTypesIds = responseJson.typeIDs.map((type) => type.id)",
                                "console.log(filteredResourceTypesIds);",
                                "pm.collectionVariables.set(\"filteredResourceTypesIds\", JSON.stringify(filteredResourceTypesIds));"
                            ],
                            "type": "text/javascript"
                        }
                    }
                ],
                "request": {
                    "method": "GET",
                    "header": [],
                    "url": {
                        "raw": "{{api_url}}/resourcetypes",
                        "host": [
                            "{{api_url}}"
                        ],
                        "path": [
                            "resourcetypes"
                        ]
                    }
                },
                "response": []
            },
            {
                "name": "Update Resource",
                "event": [
                    {
                        "listen": "prerequest",
                        "script": {
                            "exec": [
                                "let filteredResourceTypesIds = JSON.parse(pm.collectionVariables.get(\"filteredResourceTypesIds\"));",
                                "console.log(filteredResourceTypesIds);",
                                "pm.collectionVariables.set(\"currentRsourceTypeId\", filteredResourceTypesIds.shift())",
                                "pm.collectionVariables.set(\"filteredResourceTypesIds\", JSON.stringify(filteredResourceTypesIds));",
                                "if (filteredResourceTypesIds.length > 0){",
                                "    postman.setNextRequest(\"Update Resource\");",
                                "}"
                            ],
                            "type": "text/javascript"
                        }
                    },
                    {
                        "listen": "test",
                        "script": {
                            "exec": [
                                "const responseJson = JSON.parse(responseBody);",
                                "const currentRsourceTypeId = pm.collectionVariables.get(\"currentRsourceTypeId\")",
                                "pm.test('Current Resource Type should be response ID:  ' + responseJson.id, function () {",
                                "    pm.expect(responseJson.id).to.equal(currentRsourceTypeId);",
                                "});"
                            ],
                            "type": "text/javascript"
                        }
                    }
                ],
                "request": {
                    "method": "PATCH",
                    "header": [],
                    "body": {
                        "mode": "raw",
                        "raw": "{\n    \"name\": \"New Type name {{currentRsourceTypeId}}\"\n}",
                        "options": {
                            "raw": {
                                "language": "json"
                            }
                        }
                    },
                    "url": {
                        "raw": "{{api_url}}/resourcetypes/{{currentRsourceTypeId}}",
                        "host": [
                            "{{api_url}}"
                        ],
                        "path": [
                            "resourcetypes",
                            "{{currentRsourceTypeId}}"
                        ]
                    }
                },
                "response": []
            }
        ],
        "event": [
            {
                "listen": "prerequest",
                "script": {
                    "type": "text/javascript",
                    "exec": [
                        ""
                    ]
                }
            },
            {
                "listen": "test",
                "script": {
                    "type": "text/javascript",
                    "exec": [
                        ""
                    ]
                }
            }
        ],
        "variable": [
            {
                "key": "filteredResourceTypesIds",
                "value": "[]",
                "type": "string"
            },
            {
                "key": "currentRsourceTypeId",
                "value": "1",
                "type": "string"
            },
            {
                "key": "api_url",
                "value": "http://localhost:3000/api",
                "type": "string"
            }
        ]
    }
    

    Postman Request

    enter image description here

    Get Resource Types

    enter image description here

    Update Resource

    After Import that collection file, you can get the whole scrips

    enter image description here

    enter image description here

    enter image description here

    Collection Variables enter image description here

    Run looping - collection

    enter image description here

    Result

    looped Patch request three times by resource IDs array.

    enter image description here