Writing pre-request scripts
An example usage of pre-request scripting could be as follows:
- You have a series of requests in a collection and are running them in a sequence, e.g. using the collection runner.
- The second request is dependent on a value returned from the first request.
- The value needs to be processed before you pass it to the second request.
- The first request sets the data value from a response field to a variable in its Tests script.
- The second request retrieves the value and processes it in its Pre-request Script, then sets the processed value to a variable (which is referenced in the second request, e.g. in its parameters).
When you click Send, the code will execute before Postman sends the request to the API.
You can add pre-request scripts to entire collections as well as to folders within collections. In both cases, your pre-request script will run before every request in the collection or folder. This allows you to define commonly used pre-processing or debugging steps you need to execute for multiple requests.
To add pre-processing to a group of requests, locate the collection or folder in Collections on the left of Postman. Click ... to View more actions and select Edit.
Open Pre-request Scripts to enter code that will run before every request in the collection or folder.
You can define a pre-request script when you first create a collection or folder, or at any time after that.