Bird
Raised Fist0
Postmantesting~15 mins

Environment variables in Postman - Deep Dive

Choose your learning style10 modes available
Overview - Environment variables
What is it?
Environment variables in Postman are named values that store information you want to reuse in your API requests. They help you avoid repeating the same data, like URLs or tokens, by referencing a variable instead. You can create different environments, each with its own set of variables, to test APIs in various settings like development or production. This makes your testing faster, cleaner, and less error-prone.
Why it matters
Without environment variables, testers would have to manually change values like API endpoints or credentials in every request when switching contexts. This is slow and risky because mistakes can cause tests to fail or hit the wrong system. Environment variables automate this switching, saving time and reducing errors, so teams can test APIs reliably across different setups.
Where it fits
Before learning environment variables, you should understand basic API requests and how to use Postman to send them. After mastering environment variables, you can explore advanced scripting in Postman, like pre-request scripts and test scripts, which often use these variables to create dynamic tests.
Mental Model
Core Idea
Environment variables are reusable placeholders that store data to make API testing flexible and efficient across different setups.
Think of it like...
Think of environment variables like labels on jars in your kitchen. Instead of remembering what's inside each jar every time you cook, you just read the label. If you switch kitchens, you just change the labels to match the new ingredients without repacking everything.
┌───────────────────────────────┐
│         Environment           │
│ ┌───────────────┐ ┌─────────┐ │
│ │ Variable Name │ │ Value   │ │
│ ├───────────────┤ ├─────────┤ │
│ │ baseUrl       │ │ https://api.dev │
│ │ authToken     │ │ abc123  │ │
│ └───────────────┘ └─────────┘ │
└─────────────┬─────────────────┘
              │
              ▼
     API Requests use {{baseUrl}} and {{authToken}}
Build-Up - 7 Steps
1
FoundationWhat are environment variables
🤔
Concept: Introduce the idea of storing reusable data in named variables within Postman environments.
In Postman, environment variables let you save values like URLs or tokens under a name. Instead of typing the full URL every time, you write {{baseUrl}} in your request. Postman replaces this with the saved value when sending the request.
Result
You can write requests with placeholders like {{baseUrl}} and Postman fills in the actual value from the environment.
Understanding that variables act as shortcuts for values helps you avoid repetitive typing and mistakes.
2
FoundationCreating and using environments
🤔
Concept: Learn how to create environments and assign variables to them in Postman.
In Postman, you create an environment by clicking 'Manage Environments' and adding a new one. Then you add variables with names and values. When you select this environment, Postman uses its variables in your requests.
Result
You have a named environment with variables ready to be used in your API calls.
Knowing how to set up environments lets you switch contexts easily without changing requests.
3
IntermediateReferencing variables in requests
🤔Before reading on: do you think you can use environment variables anywhere in the request or only in the URL? Commit to your answer.
Concept: Understand how to insert variables into different parts of a request like URL, headers, and body.
You can use {{variableName}} syntax to insert environment variables in URLs, headers, query parameters, and request bodies. For example, setting Authorization header to Bearer {{authToken}} uses the token stored in the environment.
Result
Requests dynamically change based on the environment variable values without editing the request itself.
Knowing variables work everywhere in requests makes your tests flexible and adaptable.
4
IntermediateSwitching environments for testing
🤔Before reading on: do you think changing environment affects only new requests or also past saved requests? Commit to your answer.
Concept: Learn how switching environments changes variable values globally for all requests using those variables.
When you select a different environment in Postman, all requests using variables like {{baseUrl}} automatically use the new environment's values. This lets you test the same requests against dev, staging, or production servers by just switching environments.
Result
Requests adapt instantly to the selected environment without manual edits.
Understanding environment switching saves time and prevents errors when testing multiple setups.
5
IntermediateVariable scope and precedence
🤔Before reading on: do you think environment variables override global variables or vice versa? Commit to your answer.
Concept: Introduce variable scopes in Postman and how Postman decides which variable value to use when names overlap.
Postman has multiple variable scopes: global, environment, collection, and local. When a variable name exists in multiple scopes, Postman uses the closest scope first. Environment variables override global variables with the same name.
Result
You can control which variable value is used by placing it in the right scope.
Knowing variable precedence helps avoid confusion and bugs when variables share names.
6
AdvancedDynamic variables with scripts
🤔Before reading on: do you think environment variables can change during test runs or are they fixed? Commit to your answer.
Concept: Learn how to set and update environment variables dynamically using Postman scripts before or after requests.
In Postman, you can write JavaScript in pre-request or test scripts to set environment variables using pm.environment.set('varName', 'value'). This lets you generate tokens, timestamps, or capture response data to reuse in later requests.
Result
Environment variables can change during a test run, making tests dynamic and stateful.
Understanding dynamic variables unlocks powerful testing scenarios that adapt to API responses.
7
ExpertManaging secrets and security
🤔Before reading on: do you think environment variables are secure storage for sensitive data? Commit to your answer.
Concept: Explore best practices and limitations of storing sensitive data like passwords or tokens in environment variables.
Environment variables in Postman are stored locally and can be exported or shared, so they are not fully secure. For sensitive data, use Postman's secret management features or external vaults. Avoid committing environment files with secrets to public repositories.
Result
You protect sensitive information while still using environment variables effectively.
Knowing the security limits of environment variables prevents accidental leaks and builds trust in your testing process.
Under the Hood
Postman stores environment variables as key-value pairs in JSON format within the environment file. When a request runs, Postman parses the request text and replaces all {{variableName}} placeholders with the current value from the active environment. Scripts can modify these values at runtime, updating the environment object in memory and optionally saving changes to disk.
Why designed this way?
This design allows separation of request logic from data, enabling reuse and easy switching between contexts. Using simple text replacement keeps the system fast and flexible. The JSON storage format is human-readable and easy to export or import, supporting collaboration and version control.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Environment   │──────▶│ Request Text  │──────▶│ Variable      │
│ JSON file     │       │ with {{vars}} │       │ Replacement   │
└───────────────┘       └───────────────┘       └───────────────┘
         ▲                                              │
         │                                              ▼
  ┌───────────────┐                               ┌───────────────┐
  │ Scripts       │◀──────────────────────────────│ Runtime Env   │
  │ (set/get vars)│                               │ Variables     │
  └───────────────┘                               └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do environment variables automatically update across all team members when changed locally? Commit to yes or no.
Common Belief:Environment variables are shared automatically with the whole team once changed on one machine.
Tap to reveal reality
Reality:Environment variables are stored locally and must be manually shared or synced; changes do not propagate automatically.
Why it matters:Assuming automatic sharing can cause confusion and inconsistent test results across team members.
Quick: Can environment variables store complex data types like arrays or objects directly? Commit to yes or no.
Common Belief:You can store arrays or objects directly as environment variable values.
Tap to reveal reality
Reality:Environment variables store only strings; to store complex data, you must serialize it (e.g., JSON stringify) and parse it in scripts.
Why it matters:Misunderstanding this leads to errors when trying to use variables as objects without proper handling.
Quick: Does changing an environment variable in a test script affect the variable for all future requests in the same run? Commit to yes or no.
Common Belief:Changing an environment variable in a test script only affects that single request.
Tap to reveal reality
Reality:Changes to environment variables in scripts persist and affect all subsequent requests in the same environment session.
Why it matters:Not knowing this can cause unexpected test behavior when variables change mid-run.
Quick: Are environment variables a secure place to store passwords and API keys? Commit to yes or no.
Common Belief:Environment variables in Postman are secure enough to store sensitive data safely.
Tap to reveal reality
Reality:Environment variables are not encrypted and can be exposed if environment files are shared or leaked.
Why it matters:Storing secrets insecurely risks data leaks and security breaches.
Expert Zone
1
Environment variables can be scoped not only globally or per environment but also per collection or local to a request, allowing fine-grained control.
2
Using scripts to dynamically update environment variables enables chaining requests where data flows seamlessly without manual intervention.
3
Exported environment files can be parameterized and templated for CI/CD pipelines, integrating Postman tests into automated workflows.
When NOT to use
Avoid using environment variables for highly sensitive secrets without additional encryption or secret management tools. For static data that never changes, hardcoding in the request or using collection variables might be simpler. When testing APIs that require complex state management, consider using external data files or databases instead.
Production Patterns
Teams maintain separate environments for dev, staging, and production with distinct variable sets. They use pre-request scripts to refresh tokens and update environment variables dynamically. Environment files are stored securely and shared via version control with sensitive values redacted or replaced by CI/CD secrets.
Connections
Configuration Management
Environment variables in Postman are a form of configuration management for API tests.
Understanding environment variables helps grasp how software systems separate code from configuration, enabling flexible deployments.
Dependency Injection (Software Engineering)
Both inject external data into code or tests to increase modularity and reuse.
Knowing environment variables clarifies how dependency injection works by providing external inputs without changing code.
Biology: Genetic Code as Information Storage
Environment variables store information that controls behavior, similar to how genes store instructions for organisms.
Recognizing this parallel shows how information storage and reuse is a universal principle across fields.
Common Pitfalls
#1Using the wrong variable syntax in requests.
Wrong approach:GET https://{{baseurl}}/users (note lowercase 'baseurl')
Correct approach:GET https://{{baseUrl}}/users (correct case matching variable name)
Root cause:Variable names are case-sensitive; mismatched casing causes Postman to leave placeholders unresolved.
#2Forgetting to select the correct environment before running requests.
Wrong approach:Running requests with variables but no environment selected, causing {{variable}} to remain unresolved.
Correct approach:Select the intended environment from the dropdown before sending requests.
Root cause:Variables only resolve if the environment containing them is active; missing this step leads to errors.
#3Storing sensitive data directly in environment variables and sharing environment files publicly.
Wrong approach:Including API keys in environment JSON files committed to public repositories.
Correct approach:Use Postman's secret management or environment variable placeholders without real secrets in shared files.
Root cause:Lack of awareness about security risks of exposing environment files.
Key Takeaways
Environment variables store reusable data that makes API testing flexible and efficient.
They allow switching between different setups like development and production without changing requests.
Variables can be used anywhere in requests and updated dynamically with scripts.
Understanding variable scope and precedence prevents confusion and bugs.
Security is important: environment variables are not secure storage for secrets by default.

Practice

(1/5)
1. What is the main purpose of environment variables in Postman?
easy
A. To store reusable values that can be used across multiple requests
B. To write test assertions for API responses
C. To create new API endpoints automatically
D. To generate random data for requests

Solution

  1. Step 1: Understand environment variables role

    Environment variables hold values like URLs or tokens that you reuse in many requests.
  2. Step 2: Compare with other options

    Writing tests or generating data are different features, not the main use of environment variables.
  3. Final Answer:

    To store reusable values that can be used across multiple requests -> Option A
  4. Quick Check:

    Environment variables = reusable values [OK]
Hint: Environment variables hold reusable data for requests [OK]
Common Mistakes:
  • Confusing environment variables with test scripts
  • Thinking environment variables create endpoints
  • Assuming they generate random data automatically
2. Which of the following is the correct way to set an environment variable named token to abc123 in a Postman test script?
easy
A. pm.environment.set('token', 'abc123');
B. pm.variables.set('token', 'abc123');
C. pm.environment.get('token', 'abc123');
D. pm.setEnvironment('token', 'abc123');

Solution

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

    Postman uses pm.environment.set(key, value) to set environment variables.
  2. Step 2: Check other options for correctness

    pm.variables.set sets local variables, pm.environment.get is for getting values, and pm.setEnvironment is not a valid method.
  3. Final Answer:

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

    Set env var = pm.environment.set(key, value) [OK]
Hint: Use pm.environment.set() to assign environment variables [OK]
Common Mistakes:
  • Using pm.environment.get() to set variables
  • Confusing pm.variables.set() with environment variables
  • Using non-existent methods like pm.setEnvironment()
3. Given the following Postman test script, what will be the value of the environment variable userId after execution?
pm.environment.set('userId', 10);
pm.environment.set('userId', Number(pm.environment.get('userId')) + 5);
medium
A. Error
B. 10
C. undefined
D. 15

Solution

  1. Step 1: Analyze first line setting userId

    The first line sets userId to 10.
  2. Step 2: Analyze second line updating userId

    The second line gets current userId (10), adds 5, and sets it back, so userId becomes 15.
  3. Final Answer:

    15 -> Option D
  4. Quick Check:

    10 + 5 = 15 [OK]
Hint: Get then set adds values correctly [OK]
Common Mistakes:
  • Assuming variable stays 10 after second line
  • Thinking get returns undefined initially
  • Expecting a runtime error
4. You wrote this Postman script to remove an environment variable sessionId but it does not work:
pm.environment.delete('sessionId');

What is the correct way to delete an environment variable?
medium
A. pm.environment.remove('sessionId');
B. pm.environment.unset('sessionId');
C. pm.environment.clear('sessionId');
D. pm.environment.deleteVariable('sessionId');

Solution

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

    Postman uses pm.environment.unset(key) to remove environment variables.
  2. Step 2: Check why original code fails

    pm.environment.delete() is not a valid method, so it does not remove the variable.
  3. Final Answer:

    pm.environment.unset('sessionId'); -> Option B
  4. Quick Check:

    Delete env var = pm.environment.unset(key) [OK]
Hint: Use pm.environment.unset() to remove variables [OK]
Common Mistakes:
  • Using pm.environment.delete() which is invalid
  • Trying pm.environment.remove() or clear() which don't exist for single variables
  • Confusing with non-existent deleteVariable()
5. You want to run the same Postman collection on two different servers: dev and prod. Which is the best way to use environment variables to switch the base URL without changing the request code?
hard
A. Use global variables to store the URLs and change them before each run
B. Hardcode the server URL in each request and manually change it before running
C. Create two environments with a variable baseUrl set to each server URL, then select the environment before running
D. Write separate collections for dev and prod with different URLs

Solution

  1. Step 1: Understand environment variables for different setups

    Creating separate environments with baseUrl variables allows easy switching without code changes.
  2. Step 2: Compare other options

    Hardcoding or separate collections cause manual errors and duplication; global variables are less flexible for multiple setups.
  3. Final Answer:

    Create two environments with a variable baseUrl set to each server URL, then select the environment before running -> Option C
  4. Quick Check:

    Use environments to switch URLs easily [OK]
Hint: Use separate environments with baseUrl variables [OK]
Common Mistakes:
  • Hardcoding URLs in requests
  • Using global variables instead of environments
  • Creating duplicate collections for each server
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard