Pre-request scripts: practical examples

A pre-request script runs just before a request is sent. It can read variables, change headers, the URL and the body, and set values for this request or later ones. Most collections never need one. When you do need one, it's usually for one of the jobs below.

All examples use the Postman-compatible pm API (cm works as an alias), and run the same in the app, in collection runs and in the CLI.

1. Sign a request with HMAC

Webhooks and many partner APIs expect a signature over the body and a timestamp:

JavaScript
const CryptoJS = require('crypto-js');

const timestamp = Math.floor(Date.now() / 1000).toString();
const body = pm.request.body.raw || '';
const secret = pm.environment.get('signingSecret');

const signature = CryptoJS.HmacSHA256(`${timestamp}.${body}`, secret).toString(CryptoJS.enc.Hex);

pm.request.headers.set('X-Timestamp', timestamp);
pm.request.headers.set('X-Signature', `sha256=${signature}`);

2. Add a correlation ID to every request

Set this once as a collection-level pre-request script, and every request gets an ID you can search for in your logs:

JavaScript
const uuid = require('uuid');

const requestId = uuid.v4();
pm.environment.set('requestId', requestId);
pm.request.headers.set('X-Request-Id', requestId);

Collection and folder scripts run before the request's own script for the same phase, so one script covers the whole collection.

3. Dates and time windows

Report endpoints often want a date range. moment is built in:

JavaScript
const moment = require('moment');

pm.environment.set('from', moment().subtract(7, 'days').startOf('day').toISOString());
pm.environment.set('to', moment().endOf('day').toISOString());
Output
GET {{baseUrl}}/reports/sales?from={{from}}&to={{to}}

4. Unique test data

JavaScript
const suffix = Date.now();
pm.environment.set('email', `qa+${suffix}@example.com`);
pm.environment.set('username', `qa_${suffix}`);

Or use dynamic variables right in the body: {{$randomEmail}}, {{$randomUUID}}, {{$randomFullName}}. The full list is in Dynamic variables reference.

5. Choose the URL from the environment

JavaScript
const region = pm.environment.get('region') || 'eu';
pm.request.url.update(pm.variables.replaceIn(`https://${region}.api.example.com{{path}}`));

pm.variables.replaceIn resolves {{variables}} inside any text.

6. Hash a body for an idempotency key

JavaScript
const CryptoJS = require('crypto-js');
const key = CryptoJS.SHA256(pm.request.body.raw || '').toString();
pm.request.headers.set('Idempotency-Key', key);

Sending the same body twice now carries the same key, which is a cheap way to test that your API really is idempotent.

7. Skip work when a value is already there

JavaScript
if (!pm.environment.get('token')) {
  console.log('No token yet: run the Login request first.');
}

console.log output shows in the app's diagnostics drawer and with --verbose in the CLI.

What a pre-request script can't do

Scripts can't send extra HTTP requests (there's no pm.sendRequest). If you need a value from another endpoint, make that call a request of its own earlier in the collection and store the value from its response. See How to chain API requests.

Safety

More in the scripts reference.