Setting variables in scripts helps you save and reuse data during your tests. It makes your tests flexible and easier to manage.
0
0
Setting variables in scripts in Postman
Introduction
You want to save a value from a response to use in later requests.
You need to store user input or test data temporarily during a test run.
You want to share data between different requests in a collection.
You want to change values dynamically without editing the request manually.
Syntax
Postman
// Set a variable pm.variables.set('variableName', 'value'); // Get a variable let value = pm.variables.get('variableName');
Use pm.variables.set to create or update a variable.
Use pm.variables.get to read the variable's value.
Examples
This sets a variable named
token with the value 12345abcde.Postman
pm.variables.set('token', '12345abcde');
This retrieves the value of
token and prints it to the console.Postman
let token = pm.variables.get('token');
console.log(token);This sets an environment variable
userId with value 789. Environment variables last longer than local variables.Postman
pm.environment.set('userId', '789');
This gets the environment variable
userId.Postman
let userId = pm.environment.get('userId');Sample Program
This script saves the id from the response JSON into a variable called userId. Then it retrieves and prints it. Finally, it checks if the variable was set correctly.
Postman
// Example: Save a value from response and reuse it // Assume response JSON: { "id": "abc123", "name": "John" } // Save 'id' from response to a variable let jsonData = pm.response.json(); pm.variables.set('userId', jsonData.id); // Later, get the variable and print it let savedId = pm.variables.get('userId'); console.log(`Saved userId is: ${savedId}`); // Test to check if variable is set correctly pm.test('userId variable is set', function () { pm.expect(savedId).to.eql('abc123'); });
OutputSuccess
Important Notes
Variables set with pm.variables.set exist only during the request execution.
Use pm.environment.set or pm.collectionVariables.set to save variables longer.
Always check if the response contains the data before setting variables to avoid errors.
Summary
Setting variables lets you store and reuse data during tests.
Use pm.variables.set and pm.variables.get for local variables.
Variables help make tests dynamic and easier to maintain.