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:
| Variable | Initial Value | Current Value |
|---|---|---|
| baseUrl | https://fakestoreapi.com | https://fakestoreapi.com |
| authToken | ||
| userId | 1 | 1 |
- Click Save
Create Multiple Environments
Create three environments:
Development:| Variable | Value |
|---|---|
| baseUrl | https://dev-api.shop.com |
| authToken | dev-token-123 |
| Variable | Value |
|---|---|
| baseUrl | https://staging-api.shop.com |
| authToken | staging-token-456 |
| Variable | Value |
|---|---|
| baseUrl | https://api.shop.com |
| authToken | prod-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
| Scope | Use For | Example |
|---|---|---|
| Global | Constants across all projects | Company name |
| Collection | Shared within collection | API version |
| Environment | Environment-specific | Base URL, tokens |
| Local | Temporary, single request | Test 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
| Variable | Value |
|---|---|
| baseUrl | https://fakestoreapi.com |
| username | mor_2314 |
| password | 83r5^_ |
| 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:
| Variable | Description | Example |
|---|---|---|
{{$guid}} | UUID | a1b2c3d4-e5f6-... |
{{$timestamp}} | Unix timestamp | 1705312800 |
{{$randomInt}} | Random integer | 847 |
{{$randomEmail}} | Random email | user123@example.com |
{{$randomFirstName}} | Random name | John |
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
| Action | Code |
|---|---|
| Set environment variable | pm.environment.set("key", "value") |
| Get environment variable | pm.environment.get("key") |
| Set global variable | pm.globals.set("key", "value") |
| Get any variable | pm.variables.get("key") |
| Set collection variable | pm.collectionVariables.set("key", "value") |
| Clear variable | pm.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!