0
0
Postmantesting~15 mins

Setting variables in scripts in Postman - Deep Dive

Choose your learning style9 modes available
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.