Search code examples
javascriptpostmanweb-api-testing

Postman - How to store random values for multiple requests?


I want to store random values such as randomEmail generated in first request and use the same email in the next three requests. This is how my pre-request script for the first request looks like:

const email = "{{$randomEmail}}"
const firstName = "{{$randomFirstName}}"
const lastName = "{{$randomLastName}}"

pm.globals.set('email', email)
pm.globals.set('firstName', firstName)
pm.globals.set('lastName', lastName)

So basically I generate random email, firstName and lastName and I want to store them as global variables that I could use later on.

This is how the Body of my requests looks like:

{  "accountId": "{{accountId}}",  "email": "{{email}}",  "firstName": "{{firstName}}",  "lastName": "{{lastName}}",  "locale": "en-GB",  "mobile": "1234567890",  "contactable": true}

The Body looks the same for all four requests. The only difference is that I have a pre-request script only for the first request where I generate random values and save them as global variables. What I want to achieve is to generate random email, firstName and lastName in the first request and use the same values (stored as global variables) in all four requests. However, for some reason, new email, firstName and lastName are generated for each request, which is not what I want.

Is there a way to make it work the way I want to?


Solution

  • You should be able to just use .replaceIn() to get the dynamic value for the first request:

    email = pm.variables.replaceIn("{{$randomEmail}}")
    

    That would store the random email value to that local variable, so you could set that as the global to use elsewhere in the other requests.

    As you were setting the Global variable to the string {{$randomEmail}}, each time that's used in the other requests it would resolve to a new value.