0
0
Postmantesting~15 mins

Setting variables from response in Postman - Deep Dive

Choose your learning style9 modes available
Overview - Setting variables from response
What is it?
Setting variables from response means taking data returned by an API after a request and saving it into a variable. This variable can then be used in later requests or tests. It helps automate workflows by passing dynamic data between steps. This process is common in API testing tools like Postman.
Why it matters
Without setting variables from responses, testers would have to manually copy and paste data between requests, which is slow and error-prone. Automating this saves time and reduces mistakes, making tests reliable and repeatable. It also allows testing complex scenarios where data depends on previous responses.
Where it fits
Before learning this, you should understand how to send API requests and read responses in Postman. After this, you can learn about chaining requests, writing test scripts, and using environment variables for more advanced automation.
Mental Model
Core Idea
Extracting data from a response and storing it as a variable lets you reuse dynamic information across multiple API requests automatically.
Think of it like...
It's like writing down a phone number you just got from a friend so you can call them later without asking again.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Send Request  │──────▶│ Receive       │──────▶│ Extract Data  │
│ (API call)    │       │ Response      │       │ (parse JSON)  │
└───────────────┘       └───────────────┘       └───────────────┘
                                                      │
                                                      ▼
                                             ┌─────────────────┐
                                             │ Set Variable in │
                                             │ Environment     │
                                             └─────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding API Responses
🤔
Concept: Learn what an API response is and how to read its data.
When you send a request to an API, it sends back a response. This response usually contains data in a format like JSON. For example, a response might look like {"id": 123, "name": "Alice"}. You need to know how to find the data you want inside this response.
Result
You can identify the parts of the response you want to use later.
Understanding the structure of API responses is essential before you can extract and reuse any data.
2
FoundationWhat Are Variables in Postman
🤔
Concept: Variables store data that can be reused in requests and tests.
Postman lets you create variables in different scopes like environment or collection. Variables hold values like strings or numbers. For example, you can have a variable called userId with value 123. Later, you can use {{userId}} in your requests to insert that value.
Result
You know how to create and use variables in Postman requests.
Variables make your tests flexible and avoid hardcoding values.
3
IntermediateExtracting Data Using JavaScript
🤔Before reading on: do you think you can use simple JavaScript to get data from a JSON response? Commit to your answer.
Concept: Use JavaScript in Postman tests to parse the response and get data.
In Postman, you can write scripts in the Tests tab. Use pm.response.json() to parse the JSON response. For example, let jsonData = pm.response.json(); then access jsonData.id to get the id value.
Result
You can programmatically access any part of the response data.
Knowing how to parse JSON responses with JavaScript unlocks powerful data extraction.
4
IntermediateSetting Variables from Extracted Data
🤔Before reading on: do you think setting a variable requires a special Postman function or just assignment? Commit to your answer.
Concept: Use Postman API to save extracted data into variables.
After extracting data, use pm.environment.set('variableName', value) to save it. For example, pm.environment.set('userId', jsonData.id); saves the id as userId variable in the environment. This variable can be used in later requests as {{userId}}.
Result
Variables now hold dynamic data from responses for reuse.
Using Postman’s set function connects response data to your test flow dynamically.
5
IntermediateUsing Variables in Subsequent Requests
🤔
Concept: Insert variables into request URLs, headers, or bodies to reuse data.
In the next request, you can write the URL like https://api.example.com/users/{{userId}}. Postman replaces {{userId}} with the value saved earlier. This lets you chain requests where one depends on the previous response.
Result
Requests become dynamic and linked, simulating real user flows.
Chaining requests with variables models real-world API usage and complex test scenarios.
6
AdvancedHandling Nested and Array Data Extraction
🤔Before reading on: do you think extracting data from nested JSON or arrays is the same as flat JSON? Commit to your answer.
Concept: Learn to navigate complex JSON structures to extract needed data.
Responses often have nested objects or arrays. For example, {"user": {"id": 123, "roles": ["admin", "user"]}}. Use dot notation like jsonData.user.id or array access like jsonData.user.roles[0]. Extract and set variables accordingly.
Result
You can extract any data regardless of complexity.
Mastering JSON navigation prevents errors and unlocks full data access.
7
ExpertDynamic Variable Setting with Tests and Conditions
🤔Before reading on: do you think you can set variables conditionally based on response content? Commit to your answer.
Concept: Use test scripts to set variables only if certain conditions are met.
In the Tests tab, write JavaScript to check response data before setting variables. For example, if (jsonData.success) { pm.environment.set('token', jsonData.token); } else { pm.environment.unset('token'); } This avoids using invalid data and improves test reliability.
Result
Variables reflect only valid, tested data improving test accuracy.
Conditional variable setting makes tests smarter and more robust in real-world scenarios.
Under the Hood
When a request runs, Postman receives the response as raw text. The test script runs in a JavaScript sandbox where pm.response.json() parses this text into a JavaScript object. Using Postman’s API, scripts can set variables in different scopes by storing key-value pairs. These variables are then substituted in request templates before sending the next request.
Why designed this way?
Postman uses JavaScript for scripting because it is widely known and flexible. Parsing JSON into objects allows easy data access. Variable scopes let users organize data for different testing contexts. This design balances power and simplicity, enabling complex workflows without heavy setup.
┌───────────────┐
│ API Request   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ API Response  │
│ (raw JSON)    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Test Script   │
│ (JavaScript)  │
│ Parses JSON   │
│ Extracts Data │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Set Variable  │
│ (pm.environment.set) │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Next Request  │
│ Uses Variable │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think variables set in one request are automatically available in all environments? Commit to yes or no.
Common Belief:Once you set a variable, it is available everywhere in Postman automatically.
Tap to reveal reality
Reality:Variables have scopes like environment, collection, or global. Setting a variable in one environment does not make it available in others.
Why it matters:Assuming variables are global can cause tests to fail when switching environments because the variable is missing.
Quick: Do you think you can set variables directly in the request URL without scripts? Commit to yes or no.
Common Belief:You can set variables just by writing them in the URL or headers without scripts.
Tap to reveal reality
Reality:Variables must be set using scripts or manually before the request. Writing {{var}} in the URL only uses the variable; it does not create it.
Why it matters:Not understanding this leads to undefined variables and broken requests.
Quick: Do you think you can extract data from any response format the same way? Commit to yes or no.
Common Belief:Extracting variables works the same for all response types like JSON, XML, or plain text.
Tap to reveal reality
Reality:Postman’s pm.response.json() only works for JSON. Other formats require different parsing methods.
Why it matters:Using JSON parsing on non-JSON responses causes errors and test failures.
Quick: Do you think setting a variable overwrites it even if the new value is empty? Commit to yes or no.
Common Belief:Setting a variable always replaces the old value, even if the new value is empty or invalid.
Tap to reveal reality
Reality:You can write conditional scripts to avoid overwriting variables with empty or bad data.
Why it matters:Blindly overwriting variables can cause tests to use invalid data and fail unexpectedly.
Expert Zone
1
Variables set in pre-request scripts can be overwritten by test scripts, so order matters.
2
Using pm.collectionVariables.set() scopes variables to the collection, which is useful for sharing data across requests without polluting environment variables.
3
Postman caches variables during a run, so changes in one request may not reflect immediately in another unless carefully managed.
When NOT to use
Setting variables from response is not suitable when testing APIs that do not return consistent or parseable data formats. In such cases, manual data entry or external data files might be better. Also, for very large responses, extracting variables can slow tests; consider mocking or stubbing instead.
Production Patterns
In real-world API testing, testers chain requests by extracting tokens, IDs, or timestamps from responses to use in subsequent calls. Conditional variable setting handles error cases gracefully. Teams often use environment variables to separate test data from scripts, enabling tests to run in different environments without changes.
Connections
State Management in Web Development
Both involve storing and reusing data dynamically during a process.
Understanding how variables hold state in Postman helps grasp how web apps manage user data across pages.
Data Pipelines in Data Engineering
Setting variables from response is like passing data between pipeline stages.
Seeing API testing as a data flow clarifies how each step depends on the previous output.
Memory in Computer Architecture
Variables act like memory registers holding temporary data for processing.
Knowing how variables store data temporarily helps understand CPU registers and cache behavior.
Common Pitfalls
#1Trying to extract data without parsing JSON first.
Wrong approach:let userId = pm.response.id; // Incorrect, response is raw text
Correct approach:let jsonData = pm.response.json(); let userId = jsonData.id;
Root cause:Not understanding that response data must be parsed into an object before accessing properties.
#2Setting a variable with a wrong scope causing it to be unavailable later.
Wrong approach:pm.global.set('token', jsonData.token); // but later expecting environment variable
Correct approach:pm.environment.set('token', jsonData.token);
Root cause:Confusing variable scopes and where variables are stored.
#3Using variable placeholders in request before the variable is set.
Wrong approach:Request URL: https://api.example.com/users/{{userId}} before userId is set
Correct approach:First run request that sets userId variable, then run dependent request using {{userId}}
Root cause:Not sequencing requests properly or misunderstanding variable availability timing.
Key Takeaways
Setting variables from response automates passing dynamic data between API requests.
You must parse the response data correctly before extracting values.
Variables have scopes; knowing which scope to use prevents test failures.
Using scripts to conditionally set variables makes tests more reliable.
Chaining requests with variables models real user workflows and complex scenarios.