Postman is one of the most popular tools used for testing HTTP requests for web service APIs. It provides a user-friendly graphical interface for making HTTP requests to the API endpoint, inspecting the responses, and organizing the API testing workflow. In this tutorial, we will learn how we can use the pre-request script in Postman with the help of JavaScript.
Sometimes we need to run scripts before hitting the request on the application. Say, for example, that we need a header in our request that should be in some specific format. We can easily achieve this with the help of pre-request script in Postman. In order to run a pre-request script in Postman, we need to write our Java script code and add it to the Pre-Request Script tab in Postman.
Pre-request Script in Postman
Let us assume we need a header in our request, which should be in the following format:
Text_Date_Time
Example:
Paulsofts_DEV_2023-11-03_1699005031513
To achieve the above-formatted message, we will use the following script, where first we take the current date and then format it in “yyyy-MM-dd” format. After this, we take the current system time in milliseconds and append it to the current date, and finally, we combine these with the required text string.
// Get the current date
const currentDate = new Date();
// Format the date in "yyyy-MM-dd" format
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;
// Get the system time in milliseconds
const currentTimeInMilliseconds = new Date().getTime();
// Combine the components into a single string
const combinedString = `Paulsofts_DEV_${formattedDate}_${currentTimeInMilliseconds}`;
// Set the environment variable with the combined string
pm.environment.set("combinedString", combinedString);
After this, we put the above script in our Pre-request Script tab in Postman.
As we can see above, we have set the required message in the environment variable combinedStiring. Now, we have to map the value of combinedString to our header. We will use the following header’s key-value pair:
Key | Value |
MyHeader | {{combinedString}} |
Once we hit the request, we will get the following output: