You can use pre-request scripts in Postman to run JavaScript before a request runs. By including code in the Pre-request tab for a request, collection, or folder, you can carry out pre-processing such as setting variable values, parameters, headers, and body data. You can also use pre-request scripts for debugging code, for example by logging output to the Postman Console.
The following is an example of using pre-request scripts:
To include code you want to run before Postman sends a request, do the following:
Select Collections in the sidebar.
Open the request, then select the Scripts tab.
Select the Pre-request tab.
Enter the JavaScript you need to process before the request runs, then select Save.
Select Send to send the request. The code will run before Postman sends the request to the API.
Postman supports JSDoc for documenting JavaScript functions in your pre-request scripts. Documentation added to your functions using JSDoc will display in a popup window when you call your functions. You can use the official JSDoc documentation to learn how to add documentation to your pre-request scripts.
The following example has documentation for the logger
function using JSDoc. The documentation explains what the function does, and defines what the data
parameter is used for and that it accepts a string data type.
/**
* This function prints a string to the Postman Console.
* @param {string} data - The text to print to the Postman Console.
*/
function logger (data) {
console.log(`Logging information to the console, ${data}`)
}
You can add pre-request scripts to entire collections and folders within collections. In both cases, your pre-request script will run before every request in the collection or direct child request in the folder. This enables you to define commonly used pre-processing or debugging steps you need to run for multiple requests.
You can define a pre-request script when you first create a collection or folder, or at any time after that.
You can also store pre-request scripts in the Package Library. This enables you to maintain commonly used scripts in a single location, share them with your team, and reuse them in your workspaces.
To add pre-request scripts to a collection or folder, do the following:
After learning the basics of writing pre-request scripts, you can extend your scripts:
pm
object, visit the Postman JavaScript reference.Last modified: 2024/05/07
Additional resources
Videos
Blog posts
Case Studies