Postman Variables and Environments

Postman Variables and Environments

Master Postman variables and environments for flexible API testing. Learn to manage different configurations and eliminate hardcoded values.

Postman Variables and Environments

Hardcoding URLs, tokens, and IDs into every request is tedious and error-prone. Postman's variables and environments solve this by letting you define values once and reuse them everywhere.


1. Variable Types in Postman

Postman has five levels of variables, from broadest to most specific:

graph TD
    A["Global Variables<br/>Available everywhere"] --> B["Collection Variables<br/>Available in one collection"]
    B --> C["Environment Variables<br/>Available for selected environment"]
    C --> D["Data Variables<br/>From CSV/JSON files"]
    D --> E["Local Variables<br/>Set in scripts, one request only"]

    style A fill:#4f46e5,color:#fff
    style B fill:#0891b2,color:#fff
    style C fill:#059669,color:#fff
    style D fill:#d97706,color:#fff
    style E fill:#6b7280,color:#fff

Variable Scope Priority

If the same variable name exists at multiple levels, the most specific one wins:

Local > Data > Environment > Collection > Global


2. Collection Variables

Collection variables are shared across all requests in a collection.

Setting Collection Variables

  1. Click your collection name
  2. Go to the Variables tab
  3. Add variables:
VariableInitial ValueCurrent Value
baseUrlhttps://jsonplaceholder.typicode.comhttps://jsonplaceholder.typicode.com
testUserId11
testPostId11

Using Collection Variables

Replace hardcoded values with {{variableName}}:

GET {{baseUrl}}/users/{{testUserId}}
POST {{baseUrl}}/posts
GET {{baseUrl}}/posts/{{testPostId}}/comments

Now if the base URL changes, you update it in one place.


3. Environment Variables

Environments let you switch configurations without changing requests.

Creating Environments

Development Environment:

VariableValue
baseUrlhttp://localhost:3000/api
apiKeydev-key-abc123
debugtrue

Staging Environment:

VariableValue
baseUrlhttps://staging-api.example.com
apiKeystaging-key-def456
debugtrue

Production Environment:

VariableValue
baseUrlhttps://api.example.com
apiKeyprod-key-ghi789
debugfalse

Switching Environments

Click the environment dropdown in the top-right corner to switch. All your requests instantly use the new environment's values.

graph LR
    A["Same Request:<br/>GET {{baseUrl}}/users"] --> B{Environment?}
    B -->|Dev| C["http://localhost:3000/api/users"]
    B -->|Staging| D["https://staging-api.example.com/users"]
    B -->|Production| E["https://api.example.com/users"]

    style A fill:#4f46e5,color:#fff
    style C fill:#059669,color:#fff
    style D fill:#d97706,color:#fff
    style E fill:#dc2626,color:#fff

4. Dynamic Variables

Postman has built-in dynamic variables that generate values automatically:

VariableGeneratesExample
{{$guid}}UUIDa1b2c3d4-...
{{$timestamp}}Unix timestamp1708640000
{{$isoTimestamp}}ISO date2026-02-22T18:30:00.000Z
{{$randomInt}}Random integer47
{{$randomEmail}}Random emailuser@example.com
{{$randomFirstName}}Random nameSarah

Use them in request bodies:

{
  "name": "{{$randomFirstName}}",
  "email": "{{$randomEmail}}",
  "requestId": "{{$guid}}"
}

5. Setting Variables from Scripts

The most powerful use: extract values from responses and store them for later requests.

Extract Token from Login Response

Pre-request Script (or Test script on Login request):

// After logging in, save the token
pm.test("Save auth token", function () {
    var jsonData = pm.response.json();
    pm.environment.set("authToken", jsonData.token);
});

Now use {{authToken}} in the Authorization header of subsequent requests.

Extract Created Resource ID

pm.test("Save created post ID", function () {
    var jsonData = pm.response.json();
    pm.collectionVariables.set("newPostId", jsonData.id);
});

Use {{newPostId}} in the next request to read or update that post.

Complete Login Flow with Variables

1. POST {{baseUrl}}/auth/login
   Body: {"email": "{{userEmail}}", "password": "{{userPassword}}"}
   Test: pm.environment.set("authToken", pm.response.json().token)

2. GET {{baseUrl}}/users/me
   Header: Authorization: Bearer {{authToken}}
   (Token from step 1 is used automatically!)

3. POST {{baseUrl}}/posts
   Header: Authorization: Bearer {{authToken}}
   Body: {"title": "New Post"}
   Test: pm.collectionVariables.set("newPostId", pm.response.json().id)

4. GET {{baseUrl}}/posts/{{newPostId}}
   (ID from step 3 is used automatically!)

6. Variable Best Practices

PracticeDescription
Never hardcode base URLsUse {{baseUrl}}
Store tokens in environment variablesEasy to refresh
Use collection variables for test dataIDs, test user info
Use dynamic variables for unique dataPrevents conflicts
Set sensitive values as "secret" typeHidden in Postman UI
Document required variablesIn collection description

Summary and Key Takeaways

  1. Variables eliminate hardcoded values across requests.
  2. Collection variables are shared within a collection; environment variables switch between configs.
  3. Variable priority: Local > Data > Environment > Collection > Global.
  4. Dynamic variables like {{$guid}} generate unique values automatically.
  5. Scripts can extract values from responses and set them as variables for chaining requests.
  6. Environments enable testing against Dev, Staging, and Production with zero request changes.

Lesson Review Quiz

?Knowledge Check

If the same variable 'baseUrl' exists in both collection and environment variables, which value is used?

?Knowledge Check

How do you reference a variable named 'apiKey' in a Postman request?

?Knowledge Check

What is the best way to pass a login token from one request to subsequent requests?

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn