Postman Scripts
Pre-Request Scripts
// Pre-request script runs before each request is sent
// Set environment variable
pm.environment.set("timestamp", Date.now());
pm.environment.set("requestId", pm.variables.replaceIn("{{$guid}}"));
// Compute auth token
const token = btoa("username:password");
pm.environment.set("basicAuth", `Basic ${token}`);
// Generate HMAC signature
const CryptoJS = require('crypto-js');
const secret = pm.environment.get("apiSecret");
const body = pm.request.body.raw;
const signature = CryptoJS.HmacSHA256(body, secret).toString();
pm.request.headers.add({ key: "X-Signature", value: signature });
// Set dynamic date
const today = new Date().toISOString().split('T')[0];
pm.environment.set("todayDate", today);
// Conditionally skip request
if (!pm.environment.get("userId")) {
throw new Error("userId is required — set it in environment");
}
Test Scripts — pm.test()
// Basic test structure
pm.test("Status is 200", () => {
pm.response.to.have.status(200);
});
pm.test("Response time < 500ms", () => {
pm.expect(pm.response.responseTime).to.be.below(500);
});
pm.test("Content-Type is JSON", () => {
pm.response.to.have.header("Content-Type", /application\/json/);
});
// Parse and test body
const json = pm.response.json();
pm.test("User has required fields", () => {
pm.expect(json).to.have.property("id");
pm.expect(json.name).to.be.a("string");
pm.expect(json.email).to.include("@");
});
pm.test("Items array is not empty", () => {
pm.expect(json.items).to.be.an("array").that.is.not.empty;
pm.expect(json.items).to.have.length.above(0);
});
// Save to environment for chaining
pm.environment.set("userId", json.id);
pm.environment.set("authToken", json.token);
pm.environment & pm.variables
// Environment variables (per environment)
pm.environment.set("key", "value");
pm.environment.get("key");
pm.environment.unset("key");
pm.environment.clear();
// Global variables (across all environments)
pm.globals.set("globalToken", "abc123");
pm.globals.get("globalToken");
// Collection variables (scoped to collection)
pm.collectionVariables.set("baseUrl", "https://api.example.com");
// Variable resolution order:
// local > data (iteration) > environment > collection > global
// Use in request URL/body via double braces {{variableName}}
// e.g., {{baseUrl}}/users/{{userId}}
// pm.variables.get() resolves from highest-priority scope
const url = pm.variables.get("baseUrl");
// Dynamic variables (built-in)
// {{$guid}} — UUID v4
// {{$timestamp}} — Unix timestamp
// {{$randomInt}} — Random integer 0-1000
// {{$randomEmail}} — Random email
pm.response — Response Inspection
// Status
pm.response.code; // 200
pm.response.status; // "OK"
pm.response.responseTime; // milliseconds
// Headers
pm.response.headers.get("Content-Type");
pm.response.to.have.header("Authorization");
// Body
pm.response.json(); // parsed JSON
pm.response.text(); // raw string
pm.response.size(); // size in bytes
// Assertions on response
pm.response.to.be.ok;
pm.response.to.not.be.error;
pm.response.to.have.status(201);
pm.response.to.have.jsonBody("success", true);
pm.response.to.have.body("hello");
// JSON schema validation
const schema = {
type: "object",
required: ["id", "name"],
properties: {
id: { type: "number" },
name: { type: "string" }
}
};
pm.test("Schema is valid", () => {
pm.response.to.have.jsonSchema(schema);
});
Collection-Level Scripts & Auth Flow
// Collection pre-request: auto-refresh token
const token = pm.collectionVariables.get("accessToken");
const expiry = pm.collectionVariables.get("tokenExpiry");
if (!token || Date.now() > expiry) {
pm.sendRequest({
url: pm.environment.get("authUrl") + "/token",
method: "POST",
header: { "Content-Type": "application/json" },
body: {
mode: "raw",
raw: JSON.stringify({
client_id: pm.environment.get("clientId"),
client_secret: pm.environment.get("clientSecret"),
grant_type: "client_credentials"
})
}
}, (err, res) => {
if (!err) {
const data = res.json();
pm.collectionVariables.set("accessToken", data.access_token);
pm.collectionVariables.set("tokenExpiry",
Date.now() + data.expires_in * 1000);
}
});
}
pm Object Quick Reference
| Object/Method | Purpose |
|---|---|
pm.test(name, fn) | Define a test assertion |
pm.expect(val) | Chai-style assertion |
pm.response.json() | Parse response body as JSON |
pm.environment.set(k,v) | Set environment variable |
pm.globals.set(k,v) | Set global variable |
pm.sendRequest(opts, cb) | Make sub-request in script |
pm.variables.replaceIn(str) | Resolve variable syntax |
pm.info.requestName | Current request name |
pm.info.iterationCount | Number of iterations |