Pre-request Script in Postman: Essential Guide for Linux Users
Pre-request scripts are JavaScript code snippets executed before sending an HTTP request in Postman. They are crucial for automating dynamic parameter generation, modifying request configurations, and setting up prerequisites (e.g., authentication tokens) for your API tests. Below is a structured guide to using pre-request scripts in Postman on Linux, covering setup, core functionalities, practical examples, and debugging tips.
Postman’s Linux version (installed via Snap or .deb package) follows the same interface as other platforms. To add a pre-request script:
All pre-request scripts are scoped to the request level by default, but you can also define them at the collection or folder level (executed in order: collection > folder > request).
Pre-request scripts leverage the pm
(Postman) object to interact with requests, variables, and the environment. Below are the most commonly used features:
Postman supports environment variables, global variables, collection variables, and local variables (script-scoped). Use these to store and retrieve dynamic values (e.g., tokens, timestamps) across requests.
const envVar = pm.environment.get("variable_name"); // Environment variable
const globalVar = pm.globals.get("global_variable"); // Global variable
const collectionVar = pm.collectionVariables.get("collection_var"); // Collection variable
pm.environment.set("timestamp", new Date().getTime()); // Set environment variable
pm.globals.set("api_key", "12345-abcde"); // Set global variable
pm.environment.unset("old_variable"); // Remove environment variable
Use pm.request
to dynamically change request headers, URL parameters, or body before sending.
pm.request.headers.add({ key: "Authorization", value: "Bearer " + pm.environment.get("token") });
pm.request.url.query.add({ key: "userId", value: pm.variables.get("userId") });
pm.request.body.raw = JSON.stringify({ key: "value", timestamp: pm.environment.get("timestamp") });
Use pm.sendRequest
to call external APIs (e.g., to fetch an authentication token) before the main request. This is useful for chained API workflows.
pm.sendRequest({
url: "https://api.example.com/auth",
method: "POST",
body: {
mode: "raw",
raw: JSON.stringify({ username: "test", password: "pass" })
}
}, (err, response) => {
if (err) console.error(err);
else {
const token = response.json().access_token;
pm.environment.set("auth_token", token); // Store token for main request
}
});
Postman includes libraries like crypto-js
(for encryption) and moment.js
(for date formatting). Load them using pm.require()
:
const moment = pm.require('moment');
const timestamp = moment().format("YYYY-MM-DD HH:mm:ss");
pm.environment.set("current_time", timestamp);
Use console.log()
to output variable values or script flow to the Postman Console (View > Show Postman Console). This helps troubleshoot issues like missing variables or incorrect script logic.
console.log("Timestamp:", pm.environment.get("timestamp"));
console.log("Auth Token:", pm.environment.get("auth_token"));
Here are real-world scenarios where pre-request scripts save time:
Create a unique user ID for each request to avoid conflicts in testing:
const userId = Math.floor(Math.random() * 1000000); // Random number between 0-999999
pm.environment.set("userId", userId); // Store in environment variable
console.log("Generated User ID:", userId);
Automatically attach a Bearer token (from an environment variable) to every request:
const token = pm.environment.get("auth_token");
if (token) {
pm.request.headers.add({ key: "Authorization", value: "Bearer " + token });
} else {
console.warn("Auth token not found!");
}
Encrypt sensitive data (e.g., user credentials) using a public key before sending:
const crypto = pm.require('crypto-js');
const publicKey = pm.environment.get("public_key");
const requestBody = { username: "testuser", password: "securepass123" };
// Convert request body to string and encrypt
const encryptedBody = crypto.AES.encrypt(JSON.stringify(requestBody), publicKey).toString();
pm.request.body.raw = JSON.stringify({ data: encryptedBody });
console.log("Encrypted Body:", encryptedBody);
Check if required parameters exist to prevent invalid requests:
const amount = pm.request.body.formdata.find(param => param.key === "amount");
if (amount && parseFloat(amount.value) < 1.0) {
throw new Error("Payment amount must be at least 1.0");
}
console.log("Amount validation passed:", amount.value);
console.log()
) to verify script execution and variable values.try-catch
blocks to handle exceptions gracefully:try {
const token = pm.environment.get("token");
if (!token) throw new Error("Token not found!");
pm.request.headers.add({ key: "Authorization", value: "Bearer " + token });
} catch (err) {
console.error("Pre-request error:", err.message);
}
By mastering pre-request scripts, you can automate repetitive tasks, reduce manual errors, and create more robust API tests in Postman—regardless of your operating system. The Linux version behaves identically to other platforms, so focus on learning the JavaScript API and leveraging Postman’s built-in tools to streamline your workflow.