How to add Actual request body in pre-request script without using environment variable

Below is my pre-requisite script and without using environment variable how can I add JSON body in below pre-requisite script?

const echoPostRequest = {
    url: "http://abcd",
    method: 'POST',
    header: { 'content-type': 'application/json' },
    body: {
        mode: 'raw',
        raw: pm.environment.get('Body') // Here i want to add actual body data

    }
};

pm.sendRequest(echoPostRequest, function (err, res) {
    var jsonData = res.json();
    if (err) {
        console.log(err);
    }
    else {
        pm.environment.set("Response", jsonData.ID);
    }
});

Sample Request Body:

{
   "Id":"1255",
   "URL":"https://localhost/4455",
   "cId":"Case{{RANDOMOBCID}}",
   "cuList":[
      {
         "cuId":"{{RANDOMOBCID}}"
      }
   ]
}

Hey @apakhare

Welcome to the community! :trophy:

If I understand you correctly, I think something like this should work:

const options = {
    url: "https://postman-echo.com/post",
    method: 'POST',
    header: { 'content-type': 'application/json' },
    body: {
        mode: 'raw',
        raw: JSON.stringify({ "Id": "1255", "URL": "https://localhost/4455", "cId": `Case${pm.environment.get("RANDOMOBCID")}`, "cuList": [{ "cuId": `${pm.environment.get("RANDOMOBCID")}` }] })

    }
};

pm.sendRequest(options, function (err, res) {
    var jsonData = res.json();
    if (err) {
        console.log(err);
    }
    else {
        pm.environment.set("Response", jsonData.ID);
    }
});

I’ve just used the Postman-Echo service to post the request but you can replace the URL with your own and give it a go.

@dannydainton,

Thank You for your quick response, its working.

1 Like

Based on the Environment variable(conditionally) Option A, B or C, I have to take a different request. How to achieve that?

option A:

{
    "profile": {
        "firstname": "firstname",
        "lastname": "lastname",
	    **"mobile" : "{{mobile}}"**
    }
}

option c:

{
    "profile": {
        "firstname": "firstname",
        "lastname": "lastname",
        **"email": "{{email}}",**
       **"mobile" : "{{mobile}}"**
    }
}

Option B:

{
    "profile": {
        "firstname": "firstname",
        "lastname": "lastname",
        **"email": "{{email}}"**
    }
}

Note: Just the request body is dynamic based on Environment variable. Hader/URL and method remains the same.

Appreciated your help

Hey @apalani2,

It would probably to better to start a new thread rather than jumping on to one that’s already open.

It provides a level of separation between different items and avoids spamming others who have been mentioned on the thread already :smiley:

New thread created: