Postman's runtime is based on Node.js and lets you add dynamic behavior to requests and collections. You can use pre-request and test scripts to write API tests, build requests that can contain dynamic parameters, pass data between requests, and more.
Pre-request and test scripts execute asynchronously. This enables you to execute multiple scripts without waiting for the previous script to complete. If you'd like scripts to execute in sequence, you can use a callback function.
You can add JavaScript code to execute during two events in the flow:
Postman will prompt you with suggestions as you enter text. Select one to autocomplete your code.
You can add pre-request and test scripts to a collection, a folder, a request within a collection, or a request not saved to a collection.
In Postman, the script execution order for a single request looks like this:
For every request in a collection, scripts will execute in the following order:
For every request in a collection, the scripts will always run according to the same hierarchy. Collection-level scripts (if any) will run first, then folder-level scripts (if any), and then request-level scripts (if any). Note that this order of execution applies to both pre-request and test scripts.
For example, imagine you had the following collection structured with a single folder and two requests within the folder.
If you created log statements in the pre-request and test script sections for the collection, folder, and requests, the execution order is returned in the Postman Console.
The Postman Sandbox is a JavaScript execution environment that's available to you while writing pre-request and test scripts for requests (both in Postman and Newman). Whatever code you write in these sections is executed in this sandbox.
You can build conditional workflows using a collection, and branch and loop over a set of requests. To try out this collection template, select Conditional workflow.
Debugging scripts can be written under either the Pre-request Script tab or the Tests tab, with helpful messages logged in the Postman Console.
Last modified: 2021/01/27
Additional resources
Videos
Blog posts
Case Studies
Public workspaces