🔥 0
0

Environment Variables

Real projects have multiple environments: development, staging, production. Environment variables let you switch between them instantly.

Why Use Variables?

Without variables:
DEV:  https://dev-api.shop.com/products
STAG: https://staging-api.shop.com/products
PROD: https://api.shop.com/products

You'd need to manually change URLs for each environment!

With variables:
{{baseUrl}}/products

Just switch environments - URL updates automatically.

---

Creating an Environment

  • Click Environments in sidebar (or gear icon)
  • Click + to create new environment
  • Name it: Development
  • Add variables:
VariableInitial ValueCurrent Value
baseUrlhttps://fakestoreapi.comhttps://fakestoreapi.com
authToken
userId11
  • Click Save

Create Multiple Environments

Create three environments:

Development:
VariableValue
baseUrlhttps://dev-api.shop.com
authTokendev-token-123
Staging:
VariableValue
baseUrlhttps://staging-api.shop.com
authTokenstaging-token-456
Production:
VariableValue
baseUrlhttps://api.shop.com
authTokenprod-token-789

---

Using Variables in Requests

In URL

{{baseUrl}}/products
{{baseUrl}}/users/{{userId}}
{{baseUrl}}/orders?status=pending

In Headers

Authorization: Bearer {{authToken}}
X-API-Key: {{apiKey}}

In Body

{
  "userId": {{userId}},
  "productId": "{{productId}}",
  "quantity": {{quantity}}
}

---

Variable Syntax

Double curly braces: {{variableName}}

URL:     {{baseUrl}}/products/{{productId}}
Header:  Bearer {{authToken}}
Body:    { "email": "{{userEmail}}" }

Postman highlights variables in orange when recognized.

---

Variable Scopes

Variables can exist at different levels:

┌─────────────────────────────────────────┐
│ Global (available everywhere)           │
├─────────────────────────────────────────┤
│ Collection (within collection)          │
├─────────────────────────────────────────┤
│ Environment (current environment)       │
├─────────────────────────────────────────┤
│ Local (single request run)              │
└─────────────────────────────────────────┘
        ↑ Higher scope = lower priority
Resolution order: Local → Environment → Collection → Global

When to Use Each

ScopeUse ForExample
GlobalConstants across all projectsCompany name
CollectionShared within collectionAPI version
EnvironmentEnvironment-specificBase URL, tokens
LocalTemporary, single requestTest data

---

Setting Variables in Scripts

In Pre-request Script

// Set before request is sent
pm.environment.set("timestamp", Date.now());
pm.environment.set("randomEmail", `user${Date.now()}@test.com`);

In Tests (Post-response)

// Save response data for next request
const response = pm.response.json();

pm.environment.set("productId", response.id);
pm.environment.set("authToken", response.token);

Getting Variables in Scripts

const baseUrl = pm.environment.get("baseUrl");
const token = pm.variables.get("authToken"); // Any scope

console.log("Base URL:", baseUrl);

---

Practical Example: Login Flow

Step 1: Login Request

POST {{baseUrl}}/auth/login

Body:
{
  "username": "{{username}}",
  "password": "{{password}}"
}
Tests (save token):
const response = pm.response.json();

pm.test("Login successful", function() {
    pm.response.to.have.status(200);
    pm.expect(response).to.have.property("token");
});

// Save token for subsequent requests
pm.environment.set("authToken", response.token);
console.log("Token saved!");

Step 2: Use Token in Next Request

GET {{baseUrl}}/users/me

Headers:
Authorization: Bearer {{authToken}}

The token from login is automatically used!

---

E-commerce Workflow Example

Environment Setup

VariableValue
baseUrlhttps://fakestoreapi.com
usernamemor_2314
password83r5^_
authToken
cartId

Request 1: Login

POST {{baseUrl}}/auth/login

Tests:

const response = pm.response.json();
pm.environment.set("authToken", response.token);

Request 2: Create Cart

POST {{baseUrl}}/carts

Body:
{
  "userId": 1,
  "products": [{"productId": 1, "quantity": 2}]
}

Tests:

const cart = pm.response.json();
pm.environment.set("cartId", cart.id);

Request 3: Get Cart

GET {{baseUrl}}/carts/{{cartId}}

The cartId from step 2 is automatically used!

---

Dynamic Variables

Postman has built-in dynamic variables:

VariableDescriptionExample
{{$guid}}UUIDa1b2c3d4-e5f6-...
{{$timestamp}}Unix timestamp1705312800
{{$randomInt}}Random integer847
{{$randomEmail}}Random emailuser123@example.com
{{$randomFirstName}}Random nameJohn

Using in Requests

{
  "email": "{{$randomEmail}}",
  "orderId": "ORD-{{$timestamp}}",
  "transactionId": "{{$guid}}"
}

---

Best Practices

1. Never Hardcode Secrets

❌ Bad:

Authorization: Bearer eyJhbGciOiJ...actualtoken...

✅ Good:

Authorization: Bearer {{authToken}}

2. Use Meaningful Names

❌ Bad: {{v1}}, {{x}}

✅ Good: {{authToken}}, {{productId}}

3. Document Variables

Add descriptions to your environment variables explaining what they're for.

4. Initial vs Current Value

  • Initial Value: Shared when exporting/syncing
  • Current Value: Your local value (can contain secrets)

Keep secrets only in Current Value!

---

Quick Reference

ActionCode
Set environment variablepm.environment.set("key", "value")
Get environment variablepm.environment.get("key")
Set global variablepm.globals.set("key", "value")
Get any variablepm.variables.get("key")
Set collection variablepm.collectionVariables.set("key", "value")
Clear variablepm.environment.unset("key")

---

Key Takeaways

  • Variables make requests reusable across environments
  • Use {{variableName}} syntax in requests
  • Save response data to variables for request chaining
  • Environment variables are best for environment-specific values
  • Never commit secrets in Initial Values

Next up: Collections & Automation - organizing and running tests automatically!

Writing Tests & Assertions