Bird
Raised Fist0
Postmantesting~15 mins

Setting variables from response 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 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.

Practice

(1/5)
1. What is the main purpose of setting variables from a response in Postman?
easy
A. To encrypt the response data for security
B. To change the HTTP method of the request automatically
C. To reuse data from one request in subsequent requests or tests
D. To generate random data for the request body

Solution

  1. Step 1: Understand variable usage in Postman

    Variables store data that can be reused across requests and tests.
  2. Step 2: Identify the role of response variables

    Setting variables from response allows using dynamic data from one request in others.
  3. Final Answer:

    To reuse data from one request in subsequent requests or tests -> Option C
  4. Quick Check:

    Variable reuse = Reuse data [OK]
Hint: Variables store response data for reuse in later requests [OK]
Common Mistakes:
  • Thinking variables change HTTP methods
  • Confusing variable setting with encryption
  • Assuming variables generate random data
2. Which Postman script correctly sets an environment variable named token from a JSON response field auth.token?
easy
A. pm.variables.set('token', pm.response.auth.token);
B. pm.environment.set('token', pm.response.json().auth.token);
C. pm.environment.get('token', pm.response.json().auth.token);
D. pm.globals.set('token', pm.response.body.auth.token);

Solution

  1. Step 1: Identify correct method to set environment variable

    Use pm.environment.set(name, value) to set environment variables.
  2. Step 2: Extract JSON response value correctly

    pm.response.json() parses JSON; access nested field with .auth.token.
  3. Final Answer:

    pm.environment.set('token', pm.response.json().auth.token); -> Option B
  4. Quick Check:

    Set environment variable = pm.environment.set [OK]
Hint: Use pm.environment.set with pm.response.json() for JSON fields [OK]
Common Mistakes:
  • Using pm.environment.get instead of set
  • Accessing response fields incorrectly
  • Confusing pm.variables with environment variables
3. Given this Postman test script, what will be the value of the environment variable userId after execution?
const jsonData = pm.response.json();
pm.environment.set('userId', jsonData.data[0].id);

Response body:
{"data": [{"id": 42, "name": "Alice"}, {"id": 43, "name": "Bob"}]}
medium
A. 42
B. 43
C. undefined
D. Error: jsonData.data is not iterable

Solution

  1. Step 1: Parse JSON response and access first element

    jsonData.data[0].id accesses the first object's id, which is 42.
  2. Step 2: Set environment variable userId to this value

    pm.environment.set stores 42 as the value of userId.
  3. Final Answer:

    42 -> Option A
  4. Quick Check:

    First data id = 42 [OK]
Hint: Index 0 of data array gives first id value [OK]
Common Mistakes:
  • Choosing second element's id (43)
  • Assuming undefined due to wrong access
  • Expecting runtime error incorrectly
4. You wrote this Postman test script to set a global variable from a response header:
pm.globals.set('sessionId', pm.response.headers.get('Session-ID'));

But the variable is not set after the request. What is the most likely reason?
medium
A. The header name is case-sensitive and should be 'session-id'
B. You must parse the response body before setting variables
C. pm.globals.set cannot set variables from headers
D. pm.response.headers.get() returns null if header is missing or name is wrong

Solution

  1. Step 1: Understand header retrieval in Postman

    Header names are case-insensitive, but if the header is missing or name is wrong, get() returns null.
  2. Step 2: Check why variable is not set

    If pm.response.headers.get('Session-ID') returns null, the variable is set to null or empty, appearing unset.
  3. Final Answer:

    pm.response.headers.get() returns null if header is missing or name is wrong -> Option D
  4. Quick Check:

    Header get returns null if missing [OK]
Hint: Check header name and existence before setting variable [OK]
Common Mistakes:
  • Assuming header names are case-sensitive
  • Believing pm.globals.set can't set from headers
  • Forgetting to check if header exists
5. You want to set a collection variable authToken from a nested JSON response where the token may sometimes be missing. Which script correctly sets authToken to the token value if present, or to an empty string if missing?
hard
A. const token = pm.response.json()?.auth?.token ?? ''; pm.collectionVariables.set('authToken', token);
B. pm.collectionVariables.set('authToken', pm.response.json().auth.token);
C. if(pm.response.json().auth.token) { pm.collectionVariables.set('authToken', pm.response.json().auth.token); }
D. pm.collectionVariables.set('authToken', pm.response.json().auth?.token || null);

Solution

  1. Step 1: Handle optional chaining to avoid errors if token missing

    Using ?. safely accesses nested properties without error if missing.
  2. Step 2: Use nullish coalescing ?? to set empty string if token is undefined or null

    This ensures authToken is never undefined, avoiding test failures.
  3. Step 3: Set collection variable with the safe token value

    pm.collectionVariables.set('authToken', token); stores the value correctly.
  4. Final Answer:

    const token = pm.response.json()?.auth?.token ?? ''; pm.collectionVariables.set('authToken', token); -> Option A
  5. Quick Check:

    Optional chaining + nullish coalescing = safe set [OK]
Hint: Use ?. and ?? to safely set variables from optional fields [OK]
Common Mistakes:
  • Not handling missing token causing errors
  • Setting variable without fallback value
  • Using || which treats empty string as false