Open In App

What are pre-request scripts in Postman, and how are they used?

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Postman is an API(application programming interface) development tool which helps to build, test and modify APIs. It has the ability to make various types of HTTP requests(GET, POST, PUT, PATCH), saving environments for later use, converting the API to code for various languages(like JavaScript, Python). In this article, we will learn What are pre-request scripts in Postman, and how are they used?

Prerequisites

What is pre-request script?

A pre-request script associated with a request will execute before the request is sent. You can write pre-request scripts for your Postman API requests in JavaScript. The Pre request tab allows for any pre- request processing before a request is sent.

Steps to execute pre-request scripts in Postman

Step 1: After downloading and installing the Postman, open the software. Add a new Collection and give it a name like “GFG”. Here, we can see, multiple tabs like Authorization, Pre-request scripts, Tests , Variables.

postman

Step 2: Click on Pre-request scripts. Now in the right side pane, we can multiple snippets arrived. We can use any of the available snippet or create our own code based on our requirement. Code is written in Javascript.

z167

Step 3: We will add a pre-request script that will generate random numbers. We will use those random numbers to set a variable ‘id’ that is already stored as a global variable in our environment as shown below

z168

Pre-request Script:

var random=Math.floor(Math.random()*10);
pm.variables.set('id',random)

Step 4: Click on Save

Step 5: When you hover, on the name of your collection, 3 dots will appear. Click on those 3 dots, and then click on “Add new request”

z159

Step 6: Now You can simply paste the API in the space provided and select the API type you are requesting from the dropdown like GET,POST, PUT, DELETE etc. Output will be shown in the body with the status code.

We use global variable in our request using {{id}}

API USED:

https://reqres.in/api/user/{{id}}

Output:

Recording-2023-12-04-at-004001

Note: Pre-request script first generated a number , that id was not available.Then it generated 6,then 5 then 1 etc.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads