0
0
Postmantesting~5 mins

Variable assignment in flows in Postman

Choose your learning style9 modes available
Introduction

Variable assignment in flows helps you store and reuse data during your API tests. It makes your tests flexible and easier to manage.

When you want to save a value from the API response to use later in the same request.
When you need to keep track of data like tokens or IDs within the current request execution.
When you want to change a variable value based on test results dynamically.
When you want to avoid hardcoding values and make tests reusable.
When you want to pass data between different parts of the same request (pre-request script, tests, etc.).
Syntax
Postman
pm.variables.set('variable_name', value);
pm.variables.get('variable_name');

Use pm.variables.set to assign a value to a variable.

Use pm.variables.get to retrieve the value later in the flow.

Examples
This sets a variable userId to 12345 and then gets it to use later.
Postman
pm.variables.set('userId', 12345);
const id = pm.variables.get('userId');
This saves a token from the API response JSON to a variable for later use.
Postman
pm.variables.set('token', pm.response.json().token);
const token = pm.variables.get('token');
Sample Program

This script saves the user ID from the API response, retrieves it, prints it, and checks that it is a number.

Postman
// Save user ID from response
pm.variables.set('userId', pm.response.json().id);

// Use saved user ID in this request
const userId = pm.variables.get('userId');
console.log(`User ID is: ${userId}`);

// Check if userId is set correctly
pm.test('User ID is assigned', function () {
    pm.expect(userId).to.be.a('number');
});
OutputSuccess
Important Notes

Variables set with pm.variables.set last only during the current request execution.

To keep variables across requests, consider using pm.environment.set or pm.collectionVariables.set.

Always check if the value you want to assign exists in the response to avoid errors.

Summary

Variable assignment lets you save and reuse data during API tests.

Use pm.variables.set to assign and pm.variables.get to retrieve values.

This makes your tests flexible and easier to maintain.