How & When To Use Postman Pre Request And Post Request Scripts?

In This Tutorial, we will Explain How and When to Use Postman Pre-request Scripts and Post Request Scripts or Tests with the Help of Simple Examples:

In analogy to the unit testing world, the pre-request script is nothing but the setup that will happen before a test is executed. Similarly in Postman, if you want to modify the request in a certain way, the pre-request script is the place to put that logic or code that guarantees before the request execution starts.

=> Watch Out The Simple Postman Training Series Here.

Postman - Pre and Post Request Scripts

Postman Request Flow

First, let’s try to understand how Postman enables or allows the pre and test scripts to get executed in the context of request execution. Postman has a powerful runtime which is Node JS based that allows adding scripting capabilities before and after request execution.

The scripts are nothing but Javascript code that the Postman sandbox understands and executes as desired.

Refer to the below figure to understand Postman Request Flow.

Request Execution Flow

Here is a Video Tutorial:

The pre-request script is the entry point for request execution in Postman. If there is any script/logic added as a part of the pre-request script that gets executed first following which the actual request execution takes place and once the response is received, the tests or the post request scripts get executed.

Pre-request Scripts

Pre-request scripts are logic or piece of code that are guaranteed to execute before the request execution begins. It allows for adding dynamic behavior to request execution.

It’s important to note here that, pre-request scripts can also be applied at a collection level which indirectly means that a pre-request script will apply to all the requests that are part of that collection.

Please refer to the below figure to see the Request flow when the collection level pre-request script and tests are there.

Pre-request Scripts

Add Script

When To Use Pre-Request Scripts?

Pre request scripts are generally useful when pre-processing is required before a request is executed.

#1) For example, suppose your request expects a security token that needs to be retrieved from a third party server and as this value changes with every request execution, it could not be persisted with the environment/global variables as well.

Pre-request scripts are the perfect place to execute such logic and then use the same with request execution.

Let’s see an example of how to use the pre-request script in this case. We will be using the same GET API endpoint to illustrate https://reqres.in/api/users/{{randomVal}}

Here {{randomVal}} is a random integer between 1 to 10 that would be calculated in the pre-request script.

Here is the script flow.

  • Add logic in the pre-request script tab. Generate a random number between 1 t0 10.
var random = Math.floor(Math.random() * 10);
pm.variables.set('randomVal',random)
  • Store the generated random number in an environment or local variable. In the above code snippet, you can see that we have generated a random value between 1 and 10 and stored it in a local variable named ‘randomVal’.
  • Use the environment variable as a part of the request body.
  • Execute the request.
  • Validate the result. You can try hitting the request multiple times and see the request getting hit for different values of userIds that got generated through the random variable pre-script.

#2) Pre request scripts are also useful when you want certain header related operations. For example, request header expecting a session ID that needs to be randomly generated and needs some other conversions like base 64 encoding or processing in general.

Using Pre-Request & Post-Request Scripts With Collections

As discussed above, pre-request scripts can also be applied at the collection level. Those scripts would apply to all the requests that are available in the collection. Similar to pre-request scripts, tests or post-request scripts can also be applied to a collection.

Let’s look at an illustration of collection-level pre-request scripts and tests, and see the scripts getting into action for each of the requests inside the collection.

We will use a Postman collection with 2 requests with the following test endpoints.

  • GET https://reqres.in/api/users/1
  • POST https://reqres.in/api/register with request body as JSON with 2 fields i.e. emailId and password.

We will add the following collection level scripts for these requests.

  • Pre request: Add a new header named “Content-Type” and set the value of the header to “application/json”.
  • Test: As test or post request validation, we will check whether the response returned is having HTTP Status code 200 or not.

Please Follow The Below Steps

#1) Create a new Postman collection with the above requests GET and POST.

#2) Right-click Collection -> Select edit to add pre-request scripts and tests at the collection level.

a) For the Pre-request script, select the Pre-request Scripts tab in the collection edit window and add the below script (This script will add a header named “Content-Type” with value application/JSON for all the requests inside the collection).

pm.request.headers.add({
key: 'Content-Type',
value: 'application/json'
});

Pre-Request Script Tab

b) To Add tests or Post-request script, add the below script in the “Tests” tab. (This script will add a test to validate the response with HTTP Status 200 for all the requests present inside the collection).

pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});

Add Collection Level Post Request Scripts

c) Once the scripts are added click “Update” to save the changes done.

#3) Now, let’s try running the requests inside the collection and see if the pre-request scripts and tests specified at the collection level are set up properly or not.

#4) Open the first GET request and execute it by clicking on the “Send” button. To view the request headers, we can make use of the Postman console, which shows the complete request-response details for all the requests that go through the Postman Application.

We will discuss Postman console in detail later, but in this tutorial, we will just use it to validate request headers.

To open the console, either click the console icon in the bottom left of the Postman application or select the console option from the Window menu (Please note similar options are available for Windows OS as well as for Postman application).

postman-console

Postman Console Menu

Request Header Added

#5) To validate the post-request scripts or tests, simply validate the “Tests” tab of the executed request and you should see the test for validating the Status code that was added at the collection level to be 200.

Tests Added in Collection

With Collection Level Scripts we have achieved,

  • Adding pre-request scripts and tests at the collection level makes them easy to maintain. Examples, include adding common headers to all the requests, generating session tokens for the requests through the third party, etc.
  • Common script/tests like validating response codes can be placed at the collection level to avoid repetition.

Conclusion

In this tutorial, we dwelled into pre-request scripts and tests or post request scripts. We also walked through an example of using these scripts at the collection level to avoid repetition and placing common scripts at the collection level itself.

Both pre-request scripts and tests are a very powerful and important feature of Postman and they add a lot of value in creating an end to end integration test particularly for REST-based API endpoints.

=> Visit Here To Learn Postman From Scratch.