Script Valley
Postman API Testing: Complete Course
Automation and Advanced FeaturesLesson 5.1

Pre-request Scripts and Dynamic Data in Postman

pre-request scripts, pm.sendRequest, dynamic data generation, HMAC signature, script execution order, CryptoJS, automated token refresh

Pre-request Scripts and Dynamic Data in Postman

Pre-request scripts run before a request is sent and are one of Postman's most powerful automation features. They allow you to dynamically generate data, set up authentication tokens, compute signatures, and prepare anything the request needs before it goes out. In professional Postman API testing workflows, pre-request scripts are essential for advanced automation.

What Can Pre-request Scripts Do?

  • Generate dynamic values like timestamps, random IDs, or computed hashes.
  • Fetch a fresh access token if the current one has expired.
  • Set environment or global variables based on conditions.
  • Perform calculations and set the results as variables used in the request body.
  • Log debugging information to the Postman Console.

Basic Pre-request Script Examples

// Generate a timestamp for the request body
pm.environment.set("current_timestamp", new Date().toISOString());

// Generate a random test user email
const randomNum = Math.floor(Math.random() * 100000);
pm.environment.set("test_email", `testuser_${randomNum}@example.com`);

// Compute a future expiry date
const expiry = new Date();
expiry.setDate(expiry.getDate() + 30);
pm.environment.set("expiry_date", expiry.toISOString());

Using pm.sendRequest in Pre-request Scripts

The most powerful pre-request pattern is using pm.sendRequest to fetch a token before the main request runs:

// Automatically get a fresh token before each request
pm.sendRequest({
  url: pm.environment.get("base_url") + "/auth/login",
  method: "POST",
  header: { "Content-Type": "application/json" },
  body: {
    mode: "raw",
    raw: JSON.stringify({
      email: pm.environment.get("admin_email"),
      password: pm.environment.get("admin_password")
    })
  }
}, function(err, response) {
  if (err) {
    console.error("Login failed:", err);
    return;
  }
  const token = response.json().data.token;
  pm.environment.set("auth_token", token);
  console.log("Token refreshed successfully");
});

HMAC Signature Generation

Some APIs require a request signature — a hash of the request body using a secret key. Pre-request scripts can compute this:

const CryptoJS = require("crypto-js");

const secretKey = pm.environment.get("api_secret");
const requestBody = pm.request.body.raw;
const signature = CryptoJS.HmacSHA256(requestBody, secretKey).toString();

pm.environment.set("request_signature", signature);

Script Execution Order

Understanding the execution order is critical for building correct automation:

  • Collection Pre-request Script runs first.
  • Folder Pre-request Script runs second.
  • Request Pre-request Script runs third.
  • The actual HTTP request is sent.
  • Request Tests script runs.
  • Folder Tests script runs.
  • Collection Tests script runs.

Using CryptoJS and Other Libraries

Postman includes several JavaScript libraries available in scripts: CryptoJS (for hashing and encryption), Cheerio (for HTML parsing), Lodash (for utility functions), and Moment.js (for date handling). These are accessible via require() in scripts.

Key Takeaways

  • Pre-request scripts run before the request is sent — use them to set up tokens, timestamps, and signatures.
  • pm.sendRequest allows making HTTP calls inside scripts — essential for automated token refresh.
  • Execution order: Collection pre-request, Folder pre-request, Request pre-request, then tests in reverse.
  • CryptoJS, Lodash, and Moment.js are available in all Postman scripts via require().

Up next

Automating API Tests with Collection Runner and Newman

Sign in to track progress