0
0
Postmantesting~5 mins

Why pre-request scripts prepare data in Postman

Choose your learning style9 modes available
Introduction

Pre-request scripts run before sending a request to set up or change data. This helps tests use fresh or correct information every time.

When you need to create a token or key before calling an API.
When you want to set the current date or time in your request.
When you need to generate random data like user names or IDs.
When you want to update environment variables based on some logic before the request.
When you want to prepare headers or body data dynamically before sending.
Syntax
Postman
pm.environment.set('variable_key', 'value');
// or
pm.variables.set('variable_key', 'value');

// You can also write JavaScript code here to prepare data
Pre-request scripts use JavaScript to prepare or modify data before the request runs.
Use pm.environment.set() to save data in environment variables accessible in requests.
Examples
This sets an environment variable named authToken with a fixed value.
Postman
pm.environment.set('authToken', '12345abcde');
This saves the current time in ISO format to use in the request.
Postman
const timestamp = new Date().toISOString();
pm.environment.set('currentTime', timestamp);
This generates a random number and saves it as a variable for dynamic use.
Postman
const randomId = Math.floor(Math.random() * 1000);
pm.environment.set('randomUserId', randomId);
Sample Program

This pre-request script creates a random token and saves it as authToken. The test checks that the token exists and is a string longer than 5 characters.

Postman
// Pre-request script
const token = 'token_' + Math.random().toString(36).substring(2, 10);
pm.environment.set('authToken', token);

// Request header uses {{authToken}} variable

// Test script
pm.test('Auth token is set', function () {
    const tokenValue = pm.environment.get('authToken');
    pm.expect(tokenValue).to.be.a('string').and.to.have.lengthOf.above(5);
});
OutputSuccess
Important Notes

Pre-request scripts help keep your tests flexible and up-to-date by preparing data just before sending requests.

Always check that variables set in pre-request scripts are correctly used in your requests and tests.

Summary

Pre-request scripts run before requests to prepare or update data.

They use JavaScript to set variables like tokens, timestamps, or random values.

This makes tests more reliable and dynamic.