Use local variables in examples. Access to requests history

Hi,
Iā€™m new one to Postman and trying to consider it as a mocking tool.
First thing I wasnā€™t able to use local variables in examples.
For instance:
request

{
    "firstName": "John",
    "lastName": "Doe",
    "dob": "1990-01-01"
}

script

const requestObj = JSON.parse(pm.request.body.raw);
pm.variables.set('firstName', requestObj.firstName);
pm.variables.set('lastName', requestObj.lastName);

example body

{
    "id": "{{$guid}}",
    "firstName": "{{firstName}}",
    "lastName": "{{lastName}}"
}

In fact only id is evaluated. Is it possible to use any variables in examples?

If yes, then next question is how to access history from scripts?
Means the second request will pass id (from previous one) as parameter and use data of previous request/response body in script to generate a new response?
Thanks!

Hi @sergiyd

In the Script instead of setting a normal variable, try to set an environment variable as below;
const requestObj = JSON.parse(pm.request.body.raw);

pm.environment.set(ā€˜firstNameā€™, requestObj.firstName);

pm.environment.set(ā€˜lastNameā€™, requestObj.lastName);

Environment Variable would be set as below:

Once that is done in your next request body instead of a raw json body try to use ā€œx-www-form-urlencodedā€ type as below:


Make sure to set the header as below before hitting the request:

Hit the request with environment set where you defined the variable, it will work :slight_smile: