Pre-request Script in Postman on Ubuntu: A Step-by-Step Guide
Pre-request scripts in Postman are JavaScript code snippets that execute before sending an API request. They are commonly used to dynamically set variables (e.g., tokens, timestamps), modify request headers/parameters, or send preliminary requests to prepare data for the main call. Below is a structured guide to using pre-request scripts in Postman on Ubuntu.
Before using pre-request scripts, ensure Postman is installed. You can choose one of three methods:
sudo snap install postman --classic
.tar -xzf Postman-linux-x64-*.tar.gz -C /opt
, and create a desktop shortcut.sudo add-apt-repository https://dl.bintray.com/postman/apt
), update (sudo apt update
), and install (sudo apt install postman
).postman
).To add a pre-request script to a request:
Pre-request scripts leverage the pm
object (Postman’s scripting API) to interact with requests and variables. Below are practical examples:
Use pm.environment.set()
or pm.globals.set()
to store dynamic values (e.g., random strings, timestamps) for use in the request or subsequent scripts.
// Generate a 10-character random string (letters + numbers)
const randomStr = Math.random().toString(36).substr(2, 10);
pm.environment.set("randomParam", randomStr);
// Generate a timestamp (seconds since epoch)
const timestamp = Math.floor(Date.now() / 1000);
pm.globals.set("requestTimestamp", timestamp.toString());
These variables can be referenced in the request URL, headers, or body using {{variable_name}}
(e.g., {{randomParam}}
).
Modify the request headers before sending. For example, add an Authorization header with a Bearer token (stored in an environment variable):
const token = pm.environment.get("authToken");
pm.request.headers.add({
key: "Authorization",
value: `Bearer ${token}`
});
This ensures the token is included in the request without hardcoding it.
Use pm.sendRequest()
to call an external API (e.g., to fetch a token) and store the response in a variable.
const getTokenRequest = {
url: "https://api.example.com/auth",
method: "POST",
header: {
"Content-Type": "application/json"
},
body: {
mode: "raw",
raw: JSON.stringify({ username: "user", password: "pass" })
}
};
pm.sendRequest(getTokenRequest, (error, response) => {
if (error) {
console.error("Error fetching token:", error);
} else {
const token = response.json().access_token;
pm.environment.set("authToken", token); // Store token for main request
}
});
The main request will wait for this script to finish before executing.
Dynamically generate the request body (e.g., JSON payload with current timestamp).
const requestBody = {
userId: 123,
action: "login",
timestamp: new Date().toISOString()
};
pm.request.body.raw = JSON.stringify(requestBody);
This is useful for APIs that require up-to-date data in the request body.
console.log()
in your script to output debug information. Open the “Console” (View > Show Postman Console) to see the logs.console.log(pm.environment.get("variable_name"))
to verify variables are set correctly.pm.sendRequest()
in a try-catch block to handle errors (e.g., network issues).By following these steps, you can effectively use pre-request scripts in Postman on Ubuntu to automate API testing and streamline workflows. Pre-request scripts are a powerful tool for dynamic request preparation, and mastering them will significantly improve your API testing efficiency.