Pre-request ScriptsPre-request scripts are a piece of code that will run before the execution of a request. It runs in the Postman sandbox and allows us to add dynamic behavior to request execution. We can apply the pre-request scripts at a request level, a collection level, or a folder level, which means that a pre-request script will apply to all the requests that are part of that collection or folder. However, if we have defined scripts in all three means in the request, collection and folder, then the script must run in a given order:
We can use the pre-request script for a pre-processing task like setting parameters, variable values, body data, and headers. We may also use pre-request scripts to debug the code, such as by logging output to the console. Also, using the concept of the pre-request script, we can get the output of the function such as date, time, timestamp, etc. Let's look at a simple example to prove that pre-request scripts are running before a request is executed:
Clear the old logs from the console.
Here, you can see that the pre-request script is running prior to the request execution. Creating Variables by Pre-request ScriptHere, we will use the environment variable.
This will create a variable inside the "Development" environment with the name "username" and value "Nikita".
Here, we can see the created "username" variable available in the environment. Similarly, add the following script in the pre-request script editor: Again check the Development environment variable: Hence, we can perform multiple tasks in the pre-request script before script execution without going through the process of creating and deleting variables again and again. Next TopicTest Scripts |