0
0
Postmantesting~5 mins

Variable scope and precedence in Postman

Choose your learning style9 modes available
Introduction

Variable scope and precedence help you understand where your variables live and which value is used when multiple variables have the same name.

When you want to store and reuse data in different parts of your Postman tests.
When you have variables with the same name but different values in different places.
When debugging why a test uses an unexpected variable value.
When organizing your tests to keep data clean and avoid conflicts.
When sharing collections and environments with teammates.
Syntax
Postman
pm.variables.get('variableName')
pm.environment.get('variableName')
pm.collectionVariables.get('variableName')
pm.globals.get('variableName')

Postman variables have scopes: local (pm.variables), environment, collection, and global.

When resolving a variable with {{variableName}}, Postman checks scopes in this order: local → environment → collection → global.

Examples
Set and get a local variable in the current request or script.
Postman
pm.variables.set('userId', '123')
console.log(pm.variables.get('userId'))
Set and get an environment variable that is shared across requests in the same environment.
Postman
pm.environment.set('userId', '456')
console.log(pm.environment.get('userId'))
Set and get a collection variable that is shared across all requests in the collection.
Postman
pm.collectionVariables.set('userId', '789')
console.log(pm.collectionVariables.get('userId'))
Set and get a global variable that is available in all collections and environments.
Postman
pm.globals.set('userId', '000')
console.log(pm.globals.get('userId'))
Sample Program

This script sets a variable named 'var' in all scopes with different values. When we get 'var' using pm.variables.get(), it returns the local scope value because local has the highest precedence.

Postman
// Set variables in different scopes
pm.globals.set('var', 'global')
pm.collectionVariables.set('var', 'collection')
pm.environment.set('var', 'environment')
pm.variables.set('var', 'local')

// Get variable without specifying scope
console.log(pm.variables.get('var'))
OutputSuccess
Important Notes

Local variables exist only during the request or script execution.

Environment variables change when you switch environments in Postman.

Collection and global variables persist until you change or delete them.

Summary

Postman variables have scopes: local, environment, collection, and global.

When accessing a variable, Postman uses the value from the highest precedence scope available.

Understanding scope helps avoid confusion and bugs in your tests.