07 Pre Request Scripts
title: "Pre-Request Scripts in Postman" description: "Write Pre-request scripts in Postman for request setup including authentication, data generation, variable manipulation, and conditional logic before API requests execute." weight: 7 date: 2026-06-28 lastmod: 2026-06-28 tags: [api-development, postman] }
Pre-request scripts execute before an API request is sent. They prepare the request by setting variables, generating dynamic data, computing signatures, handling authentication, and making preliminary API calls.
What You'll Learn
- Pre-request script execution order
- Authentication token refresh patterns
- Dynamic data generation
- Conditional request modification
- Making HTTP requests from scripts
Why It Matters
Pre-request scripts automate setup that would otherwise require manual steps. Automatic token refresh eliminates expired credential errors. Dynamic data generation creates realistic test scenarios.
Real-World Use
AWS API collections use pre-request scripts to sign requests with AWS Signature V4. OAuth2 flows use pre-request scripts to obtain tokens. Payment API tests generate unique idempotency keys.
flowchart LR
Start[Pre-request Script] --> Prepare[Prepare Variables]
Prepare --> Auth[Check/Refresh Auth]
Auth --> Data[Generate Test Data]
Data --> Modify[Modify Request]
Modify --> Send[Send Request]
Auth --> Login[Login API Call]
Login --> Store[Store Token]
Teacher Mindset
Pre-request scripts set the stage for the request. Use them for anything that must happen before the request is sent. Keep them focused and idempotent. Handle errors gracefully.
Code Examples
// Example 1: Automatic token refresh
const token = pm.environment.get('auth_token');
const tokenExpiry = pm.environment.get('token_expiry');
if (!token || Date.now() > parseInt(tokenExpiry)) {
console.log('Token expired, refreshing...');
pm.sendRequest({
url: pm.environment.get('base_url') + '/auth/login',
method: 'POST',
header: { 'Content-Type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify({
username: pm.environment.get('username'),
password: pm.environment.get('password')
})
}
}, (err, res) => {
if (!err) {
const response = res.json();
pm.environment.set('auth_token', response.token);
pm.environment.set('token_expiry', Date.now() + (response.expiresIn * 1000));
}
});
}
// Example 2: Dynamic data generation
const crypto = require('crypto');
// Generate unique request ID
pm.variables.set('request_id', crypto.randomUUID());
// Generate timestamp-based reference
const ref = `ORD-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
pm.variables.set('order_ref', ref);
// Generate test data based on environment
if (pm.environment.get('env') === 'test') {
pm.variables.set('test_email', `test-${Date.now()}@example.com`);
}
// Example 3: Conditional request modification
const method = pm.request.method;
const url = pm.request.url.toString();
// Skip auth for login endpoint
if (url.includes('/auth/login')) {
console.log('Login endpoint, skipping auth header');
return;
}
// Add pagination parameters for list endpoints
if (url.includes('/api/users') && method === 'GET') {
if (!pm.request.url.query.get('page')) {
pm.request.url.query.add({ key: 'page', value: '1' });
pm.request.url.query.add({ key: 'limit', value: '20' });
}
}
// Modify body for update operations
if (method === 'PATCH' || method === 'PUT') {
const body = JSON.parse(pm.request.body?.raw || '{}');
body.updatedAt = new Date().toISOString();
pm.request.body.raw = JSON.stringify(body);
}
Common Mistakes
- Making pre-request scripts dependent on the response of the current request
- Not handling errors in pm.sendRequest callbacks
- Overwriting variables needed by other requests
- Creating scripts that are too complex and hard to debug
- Not checking if authentication is already valid before refreshing
Practice
- Write a pre-request script that sets a timestamp header.
- Implement automatic token refresh in a pre-request script.
- Generate a random email address for user creation tests.
- Add conditional logic that only runs for specific endpoints.
- Challenge: Build a pre-request script that retries with exponential backoff if the auth token refresh fails.
FAQ
Mini Project
Build a collection with a pre-request script that: checks and refreshes auth token, generates unique order reference IDs, sets timestamp headers, and adds pagination parameters to list endpoints. Test that the script works correctly for both authenticated and unauthenticated requests.
What's Next
Next, you will learn about test scripts for validating API responses.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro