0
0
PostmanHow-ToBeginner ยท 4 min read

How to Use Collection Variables in Postman for Efficient Testing

In Postman, collection variables store values accessible by all requests within a collection. You create or set them in the collection settings or scripts using pm.collectionVariables.set('key', 'value') and access them with {{key}} or pm.collectionVariables.get('key').
๐Ÿ“

Syntax

Collection variables in Postman can be set and accessed using the pm.collectionVariables API in scripts. Use pm.collectionVariables.set('variableName', 'value') to create or update a variable, and pm.collectionVariables.get('variableName') to retrieve its value. In request URLs, headers, or bodies, use {{variableName}} to reference the variable.

javascript
pm.collectionVariables.set('token', '123abc');
const tokenValue = pm.collectionVariables.get('token');
console.log(tokenValue);
Output
123abc
๐Ÿ’ป

Example

This example shows how to set a collection variable in a pre-request script and use it in the request header. The variable authToken is set with a value, then referenced in the Authorization header using {{authToken}}.

javascript
// Pre-request Script
pm.collectionVariables.set('authToken', 'Bearer abcdef123456');

// Request Header
Authorization: {{authToken}}
Output
Request sent with header Authorization: Bearer abcdef123456
โš ๏ธ

Common Pitfalls

  • Not setting variables before use: Trying to use a collection variable before it is set will result in empty or undefined values.
  • Confusing variable scopes: Collection variables override environment and global variables within the collection, but outside the collection, they are not accessible.
  • Using wrong syntax: Forgetting to use double curly braces {{variableName}} in request fields will not substitute the variable.
javascript
// Wrong: Using variable without setting it
console.log(pm.collectionVariables.get('missingVar')); // undefined

// Right: Set before use
pm.collectionVariables.set('missingVar', 'value');
console.log(pm.collectionVariables.get('missingVar')); // 'value'
Output
undefined value
๐Ÿ“Š

Quick Reference

ActionSyntaxDescription
Set variablepm.collectionVariables.set('key', 'value')Create or update a collection variable
Get variablepm.collectionVariables.get('key')Retrieve the value of a collection variable
Use in request{{key}}Reference variable in URL, headers, or body
Delete variablepm.collectionVariables.unset('key')Remove a collection variable
โœ…

Key Takeaways

Use pm.collectionVariables.set() to create or update collection variables in scripts.
Access collection variables in requests with {{variableName}} syntax.
Collection variables are shared across all requests in the same collection.
Always set collection variables before using them to avoid empty values.
Collection variables override environment and global variables within their collection scope.