gnagesh
gnagesh

Reputation: 93

How to run the "set a Global Variable" only once in POSTMAN and use them for all the keys In the collection

I have a request body as follows, Here I need the keys "id", "sys2Acct" and "shortName" to be set to a same value.

NOTE: the request body has huge number of key's, I somehow want to assign the same number (i.e random) to the mentioned keys in this request and also for the other requests in the collection.

Currently I have written the following script in Collection Pre-Request, But the problem is it is being called every time for the keys, hence resulting in different numbers for the keys

Code in collection pre-request script:

pm.globals.set("randomNumber", JSON.stringify('{{$randomCreditCardMask}}'));

Output:

{"id":"0372","name":"AN","contName":"CN","phone":"","sys2Acct":"7491","shortName":"2592"}

Can you please guide me how to achieve this.

"id":{{randomNumber}},"name":"AN","contName":"CN","phone":"","sys2Acct":{{randomNumber}},"shortName":{{randomNumber}},

Upvotes: 0

Views: 1796

Answers (2)

SpecialK711
SpecialK711

Reputation: 83

If you have a folder full of requests that all require the same random number, what I would do is just set the random variable in the pre-request script tab of your first request of the folder (instead of at the collection level), and continue to use the variable in the rest of your requests.

Upvotes: 0

bitoiu
bitoiu

Reputation: 7484

If I understand your problem correctly and you have a body that on each request needs to be sent where 3 parameters have the same random number, you can do this (just one way of doing it)

On your pre-request script generate a randomInt with Postman Dynamic variables. Then, set the whole payload to a global variable:

const randomInt = pm.variables.replaceIn('{{$randomInt}}')
const payload = {
    "id": randomInt,
    "name":"AN",
    "contName":"CN",
    "phone":"",
    "sys2Acct":randomInt,
    "shortName": randomInt
    }

pm.globals.set("payload", JSON.stringify(payload));

Now set the body to the {{payload}}

enter image description here

And you can see that on each request, the body is the the same with the 3 properties you listed set to the same random number. I've created a public request with this example, so if you hit send and then check the Body response you'll see that the payload works as you described it:

Request #1

enter image description here

Request #2

enter image description here

And so on.

Upvotes: 0

Related Questions