javascriptjsonpostman-pre-request-script

Change reused JSON body variable in Pre-request script - Postman


I have a collection of JSON POST requests for the same API. API is the same (same URL) as well as the request structure, only few values are changing within the same JSON body which will change the business scenario. What I wanted to achieve is to store a standard request in a variable and change only affected values within a pre-request script. That has to be dynamic and reusable.

I did configure in the Collection pre-request script the following (I'll make it simple)

const StandardCreateReq = {
  "FullName" : "{{FUllName}}",
  "ApplicantWebGuid": `${pm.environment.get('APPWEBGUID')}`,
  "Address": "Main Street"
};
pm.environment.set("CreateRequest" , JSON.stringify(StandardCreateReq));

Within the request body, instead of writing the full JSON body I'm just configuring it like this:

{{CreateRequest}}

So far so good, it works and I'm able to send the request correctly. What I would like to do is, within the pre-request script of the single request (N.B. not in the pre-request script of the collection) to be able to change few values, for instance either the address with a specific value, or an environment variable like EXISTING_APPWEBGUID instead of the one I'm using which is APPWEBGUID.

I'd need to do this for several requests and I don't want to rewrite the json body everytime and just changing values, I want only within the specific request and as a pre-request action, to be able to change only one or two values. The idea and the difficulty it would be to retrieve the string {{CreateRequest}} and change values in it, I tried with JSON.parse but I'm not able to make it work :-( A possible result would be to send request like following Request 1

{
  "FullName" : "John Doe",
  "ApplicantWebGuid": "12345",
  "Address": "Main Street"
}

Request 2

{
  "FullName" : "Jack Brown",
  "ApplicantWebGuid": "67890",
  "Address": "Main Street"
}

Hope you did get my point and you can help me


Solution

  • Postman Run Collection can do repeat API call with same URL by changing Body content.

    Mocking server

    Save as server.js

    const express = require('express');
    const fs = require('fs');
    const multer = require('multer')
    const cors = require('cors');
    
    const app = express();
    
    // for form-data
    const forms = multer();
    app.use(forms.array()); 
    
    app.use(cors());
    const PORT = 3000;
    
    // Function to generate random 5-digit number
    function generateRandomNumber() {
        return Math.floor(10000 + Math.random() * 90000);
    }
    
    app.post('/v1/address', (req, res) => {
        fs.readFile('address-data.json', 'utf8', (err, data) => {
            if (err) {
                console.error('Error reading file:', err);
                res.status(500).send('Internal Server Error');
                return;
            }
    
            try {
                const jsonData = JSON.parse(data);
                res.json(jsonData);
            } catch (error) {
                console.error('Error parsing JSON:', error);
                res.status(500).send('Internal Server Error');
            }
        });
    });
    
    
    app.post('/v1/request', (req, res) => {
        const { FullName, ApplicantWebGuid, Address } = req.body;
        // Form data print
        console.log(`FullName: ${FullName}`);
        console.log(`ApplicantWebGuid: ${ApplicantWebGuid}`);
        console.log(`Address: ${Address}`);
        res.json({
            Application: 'virtual Application',
            name: FullName,
            id: ApplicantWebGuid,
            address: Address,
            result: 'Approved'
        });
    });
    
    // Start the server
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });
    

    Address data

    The mocking server will use this address Save as 'address-data.json'

    {
        "data": [
            {
                "FullName" : "John Doe",
                "ApplicantWebGuid": "12345",
                "Address": "Main Street"
            },
            {
                "FullName" : "Jack Brown",
                "ApplicantWebGuid": "67890",
                "Address": "Main Street"
            }
        ]
    }
    

    Install server dependencies

    npm install express multer cors
    

    Running server

    node server.js
    

    enter image description here

    API Test

    Get Address URL

    http://localhost:3000/v1/address
    

    enter image description here

    Request Application URL

    POST http://localhost:3000/v1/request
    

    form-data

    FullName : John Doe
    ApplicantWebGuid: 12345
    Address: Main Street
    

    enter image description here

    Loop Test

    Save 1-1-demo.postman_collection.json

    {
        "info": {
            "_postman_id": "b0791408-a367-47c1-a96c-3b305a634c10",
            "name": "1-1-demo",
            "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
            "_exporter_id": "1826150"
        },
        "item": [
            {
                "name": "Get Address",
                "event": [
                    {
                        "listen": "test",
                        "script": {
                            "exec": [
                                "const jsonData = pm.response.json();\r",
                                "const FullNames = jsonData.data.map(item => item.FullName);\r",
                                "const ApplicantWebGuids = jsonData.data.map(item => item.ApplicantWebGuid);\r",
                                "const Addresss = jsonData.data.map(item => item.Address);\r",
                                "pm.environment.set('FullNames', JSON.stringify(FullNames));\r",
                                "pm.environment.set('ApplicantWebGuids', JSON.stringify(ApplicantWebGuids));\r",
                                "pm.environment.set('Addresss', JSON.stringify(Addresss));\r",
                                "console.log(\"FullNames data: \" + pm.environment.get(\"FullNames\"));\r",
                                "console.log(\"ApplicantWebGuids data: \" + pm.environment.get(\"ApplicantWebGuids\"));\r",
                                "console.log(\"Addresss data: \" + pm.environment.get(\"Addresss\"));"
                            ],
                            "type": "text/javascript"
                        }
                    }
                ],
                "request": {
                    "method": "POST",
                    "header": [],
                    "url": {
                        "raw": "http://localhost:3000/v1/address",
                        "protocol": "http",
                        "host": [
                            "localhost"
                        ],
                        "port": "3000",
                        "path": [
                            "v1",
                            "address"
                        ]
                    }
                },
                "response": []
            },
            {
                "name": "Request A",
                "event": [
                    {
                        "listen": "test",
                        "script": {
                            "exec": [
                                "const jsonData = pm.response.json();\r",
                                "\r",
                                "console.log(\"FullName: \" + pm.environment.get(\"FullName\"));\r",
                                "\r",
                                "let FullNames = JSON.parse(pm.environment.get(\"FullNames\"));\r",
                                "if (FullNames.length > 0){\r",
                                "    postman.setNextRequest(\"Request A\");\r",
                                "}\r",
                                "\r",
                                "const FullName = jsonData.name;\r",
                                "\r",
                                "pm.test('FullName suhold be applicant equal', function () {\r",
                                "    pm.expect(FullName).to.eql(pm.environment.get(\"FullName\"));\r",
                                "});"
                            ],
                            "type": "text/javascript"
                        }
                    },
                    {
                        "listen": "prerequest",
                        "script": {
                            "exec": [
                                "let FullNames = JSON.parse(pm.environment.get(\"FullNames\"));\r",
                                "console.log(FullNames);\r",
                                "pm.environment.set(\"FullName\", FullNames.shift())\r",
                                "pm.environment.set(\"FullNames\", JSON.stringify(FullNames));\r",
                                "\r",
                                "let ApplicantWebGuids = JSON.parse(pm.environment.get(\"ApplicantWebGuids\"));\r",
                                "console.log(ApplicantWebGuids);\r",
                                "pm.environment.set(\"ApplicantWebGuid\", ApplicantWebGuids.shift())\r",
                                "pm.environment.set(\"ApplicantWebGuids\", JSON.stringify(ApplicantWebGuids));\r",
                                "\r",
                                "let Addresss = JSON.parse(pm.environment.get(\"Addresss\"));\r",
                                "console.log(Addresss);\r",
                                "pm.environment.set(\"Address\", Addresss.shift())\r",
                                "pm.environment.set(\"Addresss\", JSON.stringify(Addresss));"
                            ],
                            "type": "text/javascript"
                        }
                    }
                ],
                "request": {
                    "method": "POST",
                    "header": [],
                    "body": {
                        "mode": "formdata",
                        "formdata": [
                            {
                                "key": "FullName",
                                "value": "{{FullName}}",
                                "type": "text"
                            },
                            {
                                "key": "ApplicantWebGuid",
                                "value": "{{ApplicantWebGuid}}",
                                "type": "text"
                            },
                            {
                                "key": "Address",
                                "value": "{{Address}}",
                                "type": "text"
                            }
                        ]
                    },
                    "url": {
                        "raw": "http://localhost:3000/v1/request",
                        "protocol": "http",
                        "host": [
                            "localhost"
                        ],
                        "port": "3000",
                        "path": [
                            "v1",
                            "request"
                        ]
                    }
                },
                "response": []
            }
        ]
    }
    

    Import this collection into Postman

    enter image description here

    enter image description here

    enter image description here

    Run collection

    enter image description here

    enter image description here

    Result

    Same URL API call with different two people names And result of test logging in Console screen.

    http://localhost:3000/v1/request
    

    enter image description here

    Keys

    Pre-request Scripts Tab get people information

    let FullNames = JSON.parse(pm.environment.get("FullNames"));
    console.log(FullNames);
    pm.environment.set("FullName", FullNames.shift())
    pm.environment.set("FullNames", JSON.stringify(FullNames));
    
    let ApplicantWebGuids = JSON.parse(pm.environment.get("ApplicantWebGuids"));
    console.log(ApplicantWebGuids);
    pm.environment.set("ApplicantWebGuid", ApplicantWebGuids.shift())
    pm.environment.set("ApplicantWebGuids", JSON.stringify(ApplicantWebGuids));
    
    let Addresss = JSON.parse(pm.environment.get("Addresss"));
    console.log(Addresss);
    pm.environment.set("Address", Addresss.shift())
    pm.environment.set("Addresss", JSON.stringify(Addresss));
    

    enter image description here

    Body picked up one of people enter image description here

    Tests tab checking correct matched user

    const jsonData = pm.response.json();
    
    console.log("FullName: " + pm.environment.get("FullName"));
    
    let FullNames = JSON.parse(pm.environment.get("FullNames"));
    if (FullNames.length > 0){
        postman.setNextRequest("Request A");
    }
    
    const FullName = jsonData.name;
    
    pm.test('FullName suhold be applicant equal', function () {
        pm.expect(FullName).to.eql(pm.environment.get("FullName"));
    });
    

    enter image description here