Pre-request Scripts in Postman run before an API request is sent. They are written in JavaScript and are commonly used to generate dynamic data, set environment variables, create authentication tokens, and prepare request headers or parameters.
? Key Concepts
Executed before every request
Written using JavaScript
Can access environment, globals, and collection variables
Used for authentication, timestamps, random data
Helps automate API testing workflows
? Syntax / Theory
Postman provides a pm API object to interact with variables, requests, and utilities. Pre-request scripts are scoped at request, folder, or collection level.
pm.environment – access environment variables
pm.globals – access global variables
pm.variables – dynamic variable resolution
pm.request – modify request details
? Code Example(s)
? View Code Example
// Generate a random user ID before request
const userId = Math.floor(Math.random() * 10000);
pm.environment.set("user_id", userId);
? View Code Example
// Set current timestamp for request usage
const timestamp = new Date().toISOString();
pm.environment.set("current_time", timestamp);