Bird
Raised Fist0
Postmantesting~15 mins

Setting variables in scripts in Postman - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Setting variables in scripts
What is it?
Setting variables in scripts means saving values inside Postman scripts so you can use them later in your tests or requests. Variables can hold data like user names, tokens, or IDs that change during testing. This helps make tests flexible and reusable without rewriting values each time. You set variables using simple commands inside Pre-request or Test scripts.
Why it matters
Without setting variables, you would have to manually update values in every request or test, which is slow and error-prone. Variables let you automate tests that adapt to changing data, like login tokens or dynamic IDs. This saves time, reduces mistakes, and makes your tests smarter and more reliable.
Where it fits
Before learning this, you should know how to create basic requests and run simple tests in Postman. After this, you can learn about variable scopes, environments, and chaining requests using variables for more complex workflows.
Mental Model
Core Idea
Variables in Postman scripts store and share data dynamically during test runs to make requests and tests adaptable and reusable.
Think of it like...
It's like writing a note with a phone number on a sticky note so you can use it later without remembering it by heart.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Pre-request   │──────▶│ Set Variable  │──────▶│ Use Variable  │
│ Script runs   │       │ (save value)  │       │ in request or │
│ before request│       │               │       │ test script   │
└───────────────┘       └───────────────┘       └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat are variables in Postman
🤔
Concept: Introduce the idea of variables as named storage for values used in requests and scripts.
Variables hold data like strings or numbers that you can reuse. For example, you can save a user ID as a variable and use it in many requests instead of typing it each time.
Result
You understand that variables are placeholders for data that can change and be reused.
Knowing variables exist helps you avoid repeating the same data and makes your tests easier to maintain.
2
FoundationWhere variables live and how to access
🤔
Concept: Explain variable scopes: global, environment, collection, and local, and how scripts access them.
Postman variables can be global (all collections), environment-specific (per environment), collection-specific, or local (within a single request). Scripts can get or set variables in these scopes using commands like pm.variables.get('name') or pm.environment.set('name', value).
Result
You can identify where variables are stored and how to read or write them in scripts.
Understanding scopes prevents confusion about which variable value is used when multiple exist with the same name.
3
IntermediateSetting variables in Pre-request scripts
🤔Before reading on: do you think setting a variable in a Pre-request script affects the current request or the next one? Commit to your answer.
Concept: Learn how to set variables before a request runs to prepare dynamic data.
In the Pre-request script tab, you can write code like pm.environment.set('token', 'abc123') to save a token before the request runs. This token can then be used in the request headers or body.
Result
Variables set in Pre-request scripts are available during the request execution.
Knowing you can prepare data before sending a request lets you automate workflows like authentication or data setup.
4
IntermediateSetting variables in Test scripts
🤔Before reading on: do you think variables set in Test scripts are available immediately for the current request or only for future requests? Commit to your answer.
Concept: Learn how to save data from responses for use in later requests or tests.
In the Tests tab, you can extract data from the response and save it as a variable. For example, let jsonData = pm.response.json(); pm.environment.set('userId', jsonData.id); saves the user ID from the response.
Result
You can capture dynamic response data and reuse it in following requests.
Extracting and saving response data enables chaining requests and testing workflows that depend on previous results.
5
IntermediateUsing variables in request fields
🤔
Concept: How to insert variables into request URLs, headers, or bodies using double curly braces.
You write {{variableName}} in request fields. Postman replaces this with the variable's current value when sending the request. For example, https://api.example.com/users/{{userId}} uses the userId variable.
Result
Requests become dynamic and adapt to variable values set in scripts or environments.
Using variables in requests avoids hardcoding and allows tests to run with changing data.
6
AdvancedVariable persistence and scope priority
🤔Before reading on: if a variable exists in both environment and global scopes with different values, which one does Postman use? Commit to your answer.
Concept: Understand how Postman decides which variable value to use when multiple scopes have the same name.
Postman uses the variable with the highest priority: local > data > environment > collection > global. Setting a variable in a lower scope does not overwrite higher scopes unless explicitly done.
Result
You can predict which variable value will be used and avoid conflicts.
Knowing scope priority helps prevent bugs where the wrong variable value is used unexpectedly.
7
ExpertDynamic variable setting with scripts and chaining
🤔Before reading on: can you set a variable in one request's Test script and use it immediately in the next request without manual intervention? Commit to your answer.
Concept: Learn how to chain requests by setting variables dynamically and using them in subsequent requests automatically.
By setting variables in Test scripts, you can pass data like tokens or IDs to the next request. For example, after login, save the token with pm.environment.set('authToken', token) and use {{authToken}} in the next request's headers. This creates automated workflows.
Result
You can build complex test flows that adapt to changing data without manual updates.
Mastering dynamic variable setting and chaining unlocks powerful automated testing scenarios that mimic real user journeys.
Under the Hood
Postman scripts run in a JavaScript sandbox environment where variables are stored in different scopes as key-value pairs. When a script sets a variable, Postman updates the corresponding scope store. During request execution, Postman replaces variable placeholders with current values by checking scopes in priority order. This process happens synchronously within the runtime before sending the request or after receiving the response.
Why designed this way?
This design allows flexible variable management across different contexts like environments or collections, supporting reuse and modularity. The priority system avoids ambiguity when variables share names. Running scripts in a sandbox ensures security and isolation from the host system. Alternatives like global-only variables would limit flexibility and cause conflicts.
┌───────────────┐
│ Script runs   │
│ (Pre-request) │
└──────┬────────┘
       │ sets variable
       ▼
┌───────────────┐
│ Variable Store│
│ (env, global) │
└──────┬────────┘
       │ used in
       ▼
┌───────────────┐
│ Request with  │
│ {{variable}}  │
└──────┬────────┘
       │ response
       ▼
┌───────────────┐
│ Script runs   │
│ (Test script) │
└──────┬────────┘
       │ sets variable
       ▼
┌───────────────┐
│ Variable Store│
│ (updated)     │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: If you set a variable in a Test script, is it immediately available in the same request's URL? Commit to yes or no.
Common Belief:Setting a variable in a Test script immediately changes the request URL or headers of the same request.
Tap to reveal reality
Reality:Variables set in Test scripts affect future requests, not the current one, because the request is already sent before the Test script runs.
Why it matters:Expecting immediate effect causes confusion and broken tests when variables don't update the current request as intended.
Quick: Do environment variables override local variables if they share the same name? Commit to yes or no.
Common Belief:Environment variables always override local variables with the same name.
Tap to reveal reality
Reality:Local variables have higher priority than environment variables, so local variables override environment variables if names clash.
Why it matters:Misunderstanding scope priority leads to unexpected variable values and test failures.
Quick: Can you set a variable in a script without specifying the scope and expect it to be saved globally? Commit to yes or no.
Common Belief:If you set a variable without specifying scope, it automatically becomes global.
Tap to reveal reality
Reality:Variables set without scope default to the local scope and do not persist beyond the current request unless explicitly set in environment or global scope.
Why it matters:Assuming variables persist globally causes tests to fail when variables disappear unexpectedly.
Quick: Is it safe to store sensitive data like passwords in global variables? Commit to yes or no.
Common Belief:Storing sensitive data in global variables is safe and convenient.
Tap to reveal reality
Reality:Global variables are accessible across all collections and environments, which can expose sensitive data unintentionally.
Why it matters:Storing secrets globally risks leaking credentials and security breaches.
Expert Zone
1
Setting variables in scripts can trigger asynchronous behavior if you use pm.sendRequest inside scripts, which requires careful handling to avoid race conditions.
2
Variables set in collection or folder scopes can override environment variables, which is useful for organizing tests but can cause subtle bugs if not tracked.
3
Using pm.variables.set affects only the local scope and does not persist beyond the current script execution, unlike pm.environment.set or pm.globals.set.
When NOT to use
Avoid setting variables in scripts when you need static, unchanging values; instead, use environment or global variables directly. For highly sensitive data, use Postman's secret management or external vaults rather than variables. Also, avoid overusing variables for simple tests where hardcoded values improve clarity.
Production Patterns
In real-world APIs, testers use Test scripts to extract authentication tokens and set them as environment variables for subsequent requests. They chain requests by saving IDs from responses and passing them forward. Variables are also used to toggle test modes or inject randomized data for robustness testing.
Connections
Environment Variables
Builds-on
Understanding how to set variables in scripts deepens your grasp of environment variables, which control test contexts and configurations.
Continuous Integration (CI) Pipelines
Builds-on
Using variables in Postman scripts prepares you for managing dynamic data in CI pipelines where tests run automatically with changing inputs.
Memory Management in Programming
Same pattern
Variables in Postman scripts behave like memory slots holding data temporarily or persistently, similar to variables in programming languages managing data lifetimes and scopes.
Common Pitfalls
#1Setting a variable in a Test script and expecting it to change the current request's URL.
Wrong approach:pm.environment.set('userId', '12345'); // expecting current request URL to update
Correct approach:Set variables in Pre-request scripts to affect the current request; use Test scripts to set variables for future requests.
Root cause:Misunderstanding the order of script execution: Test scripts run after the request is sent.
#2Using the same variable name in multiple scopes without knowing which value is used.
Wrong approach:pm.environment.set('token', 'abc'); pm.globals.set('token', 'xyz'); // confusion which token is used
Correct approach:Use unique variable names or understand scope priority to avoid conflicts.
Root cause:Lack of awareness of Postman's variable scope priority rules.
#3Not specifying scope when setting variables, leading to unexpected variable disappearance.
Wrong approach:pm.variables.set('sessionId', '789'); // variable lost after request
Correct approach:pm.environment.set('sessionId', '789'); // persists across requests
Root cause:Confusing local scope (pm.variables) with persistent scopes (environment/global).
Key Takeaways
Setting variables in Postman scripts allows dynamic data storage and reuse, making tests flexible and maintainable.
Variables have different scopes with a clear priority order that determines which value is used when names overlap.
Pre-request scripts set variables for the current request, while Test scripts set variables for future requests.
Using variables properly enables chaining requests and automating complex test workflows.
Misunderstanding variable scopes and script execution order causes common test failures and confusion.

Practice

(1/5)
1. What is the purpose of using pm.variables.set in Postman scripts?
easy
A. To store a value in a local variable for later use within the same request
B. To send a request to the server
C. To delete a variable from the environment
D. To log information to the console

Solution

  1. Step 1: Understand the function of pm.variables.set

    This function stores a value in a local variable that can be used later in the same request or script.
  2. Step 2: Differentiate from other actions

    Sending requests, deleting variables, or logging are done by other methods, not pm.variables.set.
  3. Final Answer:

    To store a value in a local variable for later use within the same request -> Option A
  4. Quick Check:

    pm.variables.set stores local variables [OK]
Hint: Remember: set means save value locally in script [OK]
Common Mistakes:
  • Confusing variable setting with sending requests
  • Thinking it deletes variables
  • Assuming it logs output
2. Which of the following is the correct syntax to set a variable named token with value abc123 in a Postman test script?
easy
A. pm.variables.set['token', 'abc123'];
B. pm.variables.set(token, 'abc123');
C. pm.variables.set('token' = 'abc123');
D. pm.variables.set('token', 'abc123');

Solution

  1. Step 1: Check the correct method signature

    The correct syntax uses pm.variables.set('variableName', 'value'); with the variable name as a string and value as the second argument.
  2. Step 2: Identify syntax errors in other options

    pm.variables.set(token, 'abc123'); misses quotes around the variable name. pm.variables.set('token' = 'abc123'); uses an invalid assignment inside the method. pm.variables.set['token', 'abc123']; uses incorrect bracket notation.
  3. Final Answer:

    pm.variables.set('token', 'abc123'); -> Option D
  4. Quick Check:

    Use quotes for variable name in pm.variables.set [OK]
Hint: Variable names must be strings in quotes [OK]
Common Mistakes:
  • Omitting quotes around variable names
  • Using assignment inside set method
  • Using wrong brackets for method call
3. Consider this Postman test script snippet:
pm.variables.set('userId', 42);
const id = pm.variables.get('userId');
console.log(id);

What will be printed in the Postman console?
medium
A. 42
B. undefined
C. '42'
D. null

Solution

  1. Step 1: Understand variable setting and getting

    The script sets 'userId' to the number 42, then retrieves it with pm.variables.get.
  2. Step 2: Check the console output

    The retrieved value is 42 (a number), so console.log(id); prints 42 without quotes.
  3. Final Answer:

    42 -> Option A
  4. Quick Check:

    Set and get return the same stored value [OK]
Hint: Get returns exactly what was set, including type [OK]
Common Mistakes:
  • Assuming get returns string always
  • Expecting undefined if variable not set
  • Confusing quotes in console output
4. You wrote this Postman script:
pm.variables.set('session', 'abc');
pm.variables.get('session');

But the variable session is not accessible in later requests. What is the likely problem?
medium
A. You must call pm.variables.save() to save variables
B. You should use pm.environment.set to make it accessible across requests
C. Variable names cannot be strings
D. You need to restart Postman to apply changes

Solution

  1. Step 1: Understand variable scopes in Postman

    pm.variables.set sets a local variable only for the current script execution, not across requests.
  2. Step 2: Use environment variables for persistence

    To keep variables accessible across requests, use pm.environment.set instead.
  3. Final Answer:

    You should use pm.environment.set to make it accessible across requests -> Option B
  4. Quick Check:

    Local variables are temporary; environment variables persist [OK]
Hint: Use environment.set for cross-request variables [OK]
Common Mistakes:
  • Expecting pm.variables.set to persist across requests
  • Thinking a save method is needed
  • Believing variable names can't be strings
5. You want to set a variable authToken in a Pre-request Script that depends on the response of a previous request stored in pm.response.json(). Which approach correctly sets authToken for use in the next request?
hard
A. Use pm.variables.set('authToken', pm.response.json().token); in the Pre-request Script
B. Use pm.environment.set('authToken', pm.response.json().token); in the Pre-request Script
C. Use pm.environment.set('authToken', pm.response.json().token); in the Tests script of the previous request
D. Use pm.variables.set('authToken', pm.response.json().token); in the Tests script of the previous request

Solution

  1. Step 1: Identify when response data is available

    The response data from pm.response.json() is only available in the Tests script after the request completes, not in the Pre-request Script.
  2. Step 2: Set variable for next request

    To use authToken in the next request, set it as an environment variable in the Tests script of the current request using pm.environment.set.
  3. Step 3: Why not local variables?

    Local variables set with pm.variables.set do not persist across requests, so they won't be available in the next request.
  4. Final Answer:

    Use pm.environment.set('authToken', pm.response.json().token); in the Tests script of the previous request -> Option C
  5. Quick Check:

    Set environment variables in Tests to share data between requests [OK]
Hint: Set environment vars in Tests script to share between requests [OK]
Common Mistakes:
  • Trying to access response in Pre-request Script
  • Using pm.variables.set for cross-request data
  • Setting variables in wrong script phase