Postman uses variables to make API testing flexible and reusable. Understanding variable scopes and URL patterns helps you build maintainable test collections.
Key Takeaways
- 1Variables use {{variableName}} syntax in URLs
- 2Scope hierarchy: global > collection > environment > data > local
- 3Path parameters use :paramName syntax
- 4Pre-request scripts can modify URLs dynamically
- 5Collections can be shared with variable templates
Mastering Postman variables transforms how you work with APIs. Instead of hardcoding URLs and manually switching between environments, you can build flexible, reusable request collections that your entire team can share.
“Variables enable you to store and reuse values in your requests and scripts. Use environments to group related variables and switch contexts quickly.”
Variable Syntax
Postman uses double curly braces for variable interpolation and colons for path parameters. Understanding these syntax patterns is essential for building dynamic requests.
| Syntax | Usage | Example |
|---|---|---|
| {{variable}} | Any variable scope | {{baseUrl}}/users |
| :param | Path parameter | /users/:userId |
| {{$guid}} | Dynamic UUID | {{$guid}} |
| {{$timestamp}} | Unix timestamp | {{$timestamp}} |
| {{$randomInt}} | Random integer | {{$randomInt}} |
The dynamic variables like {{$guid}} and {{$timestamp}} are built into Postman and generate fresh values for each request, useful for unique identifiers and cache busting.
URL Construction
Building URLs with variables lets you switch between environments without modifying your requests. The same collection can target development, staging, or production servers just by changing the active environment.
# Basic URL with variable
{{baseUrl}}/api/users
# Environment: production
baseUrl = https://api.example.com/v2
# Environment: staging
baseUrl = https://staging-api.example.com/v2
# Full URL with path parameters
{{baseUrl}}/users/:userId/posts/:postId
# With query parameters
{{baseUrl}}/search?q={{searchTerm}}&page={{page}}&limit=20
# Combining static and dynamic parts
https://{{region}}.api.example.com/v{{apiVersion}}/usersThese examples show how variables can be used throughout your URLs. The base URL, path parameters, query parameters, and even individual path segments can all be parameterized.
Variable Scopes
Postman variables have a hierarchy of scopes that determines which value wins when the same variable name exists in multiple places. Understanding this hierarchy is crucial for managing complex API collections.
// Variable scope hierarchy (highest to lowest priority)
// 1. Local (within script)
// 2. Data (from data file)
// 3. Environment
// 4. Collection
// 5. Global
// Setting variables in pre-request scripts
pm.variables.set('localVar', 'value'); // Local scope
pm.environment.set('envVar', 'value'); // Environment scope
pm.collectionVariables.set('collVar', 'value'); // Collection scope
pm.globals.set('globalVar', 'value'); // Global scope
// Getting variables
const baseUrl = pm.variables.get('baseUrl'); // Auto-resolves scope
const envVar = pm.environment.get('apiKey'); // Specific scope
// Unset variables
pm.environment.unset('tempToken');
// Check if variable exists
if (pm.variables.has('userId')) {
// Use variable
}Use pm.variables.get() when you want Postman to automatically resolve the correct scope. Use the specific scope getters like pm.environment.get() when you need a value from a particular scope.
Dynamic URL Generation
Pre-request scripts let you programmatically build URL components before the request executes. This is powerful for complex scenarios like generating query strings dynamically or selecting base URLs based on conditions.
// Pre-request Script for dynamic URLs
// Generate unique request ID
pm.variables.set('requestId', pm.variables.replaceIn('{{$guid}}'));
// Timestamp for cache busting
pm.variables.set('cacheBuster', Date.now());
// Build complex URL parts
const filters = {
status: 'active',
type: 'premium',
sort: 'created_at'
};
const queryString = Object.entries(filters)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join('&');
pm.variables.set('filterParams', queryString);
// URL: {{baseUrl}}/users?{{filterParams}}&_t={{cacheBuster}}
// Conditional base URL
const env = pm.environment.get('environment');
const baseUrls = {
production: 'https://api.example.com',
staging: 'https://staging.api.example.com',
local: 'http://localhost:3000'
};
pm.variables.set('baseUrl', baseUrls[env] || baseUrls.local);This script demonstrates several techniques: generating unique IDs, building query strings dynamically, and selecting base URLs based on environment. The variables you set are available immediately in the request URL.
Path Parameters
Path parameters use colon syntax and appear in the Postman UI as editable fields. They are different from query parameters and let you work with RESTful resource identifiers cleanly.
# Path parameter syntax
GET /users/:userId/orders/:orderId
# In Postman UI:
# URL: {{baseUrl}}/users/:userId/orders/:orderId
# Path Variables:
# userId: 12345
# orderId: 67890
# Request sent: {{baseUrl}}/users/12345/orders/67890
# Dynamic path parameters from response
# In Tests script of previous request:
pm.environment.set('userId', pm.response.json().id);
# Then use in next request:
GET {{baseUrl}}/users/{{userId}}/profileThe key insight is that you can chain requests together. The first request stores an ID from its response, and subsequent requests use that ID in their URLs without manual intervention.
Collection URL Templates
Collections can include default variable values that ship with the collection. This makes sharing easier because recipients have sensible defaults without needing to configure environments first.
{
"info": {
"name": "API Collection",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"variable": [
{
"key": "baseUrl",
"value": "https://api.example.com/v1"
},
{
"key": "apiVersion",
"value": "v1"
}
],
"item": [
{
"name": "Get Users",
"request": {
"method": "GET",
"url": {
"raw": "{{baseUrl}}/users?page={{page}}&limit={{limit}}",
"host": ["{{baseUrl}}"],
"path": ["users"],
"query": [
{ "key": "page", "value": "{{page}}" },
{ "key": "limit", "value": "{{limit}}" }
]
}
}
}
]
}This JSON structure shows how collections are stored internally. You can edit collection JSON directly for bulk changes or use it as a template for generating collections programmatically.
URL Testing in Scripts
Test scripts let you validate URLs and extract data for subsequent requests. Use them to ensure your API calls go to the correct endpoints and to automatically capture resource identifiers from responses.
// Tests script - validate URL patterns
// Check request URL
pm.test('Request URL is correct', () => {
const url = pm.request.url.toString();
pm.expect(url).to.include('/api/v2/');
pm.expect(url).to.not.include('localhost');
});
// Validate response URL (after redirects)
pm.test('Final URL is HTTPS', () => {
// Note: pm.response doesn't have URL in Postman
// Use request URL or track redirects manually
});
// Extract and store URL parts from response
pm.test('Store resource URL', () => {
const response = pm.response.json();
// Store URL from response for next request
if (response.links && response.links.self) {
pm.environment.set('resourceUrl', response.links.self);
}
// Extract ID from URL
const match = response.url.match(/\/users\/(\d+)/);
if (match) {
pm.environment.set('userId', match[1]);
}
});
// Build next URL from pagination
pm.test('Setup pagination', () => {
const response = pm.response.json();
if (response.nextPage) {
pm.environment.set('nextPageUrl', response.nextPage);
}
});These test scripts show common patterns: validating URLs match expected patterns, extracting IDs from response URLs using regular expressions, and setting up pagination for subsequent requests.
Environment Configuration
Environments group related variables together so you can switch contexts with a single click. A well-designed environment strategy makes it easy to test against different API versions, regions, or deployment stages.
{
"name": "Production",
"values": [
{
"key": "baseUrl",
"value": "https://api.example.com",
"enabled": true
},
{
"key": "apiVersion",
"value": "v2",
"enabled": true
},
{
"key": "apiKey",
"value": "{{vault:api-key}}",
"type": "secret",
"enabled": true
}
]
}
// Switching environments changes all {{variable}} values
// Production: {{baseUrl}} -> https://api.example.com
// Staging: {{baseUrl}} -> https://staging.api.example.com
// Local: {{baseUrl}} -> http://localhost:3000
// Sharing collections:
// Export without environment = uses collection variables
// Export with environment = includes specific values
// Use placeholder values for secretsWhen sharing collections, export them without environments to avoid accidentally sharing secrets. Recipients can create their own environments with the required variable names documented in your collection.