pm.* in practice: a reference and working patterns
The pm object is a script's single entry point to the request, the response and variables of every scope. A token is refreshed by a collection-level script only when it is about to expire, not before every request: the token and its expiry live in variables with a margin, and the helper pm.sendRequest is asynchronous. Polling is built with an attempt counter and an exit so the run cannot hang.
API · Scripts and checks in Postman
A Postman token is refreshed only when needed, not before every request. Which script does that?
A collection of 80 requests calls the authorisation endpoint before each one. The server log is full of tokens and login limits run out. The other extreme: the token is entered by hand and expires mid-run. A script that refreshes the token only when it is really needed fixes both. The lesson gathers a reference of the pm object and four working patterns.
How it works: a pm reference
The pm object is the single entry point to the request, the response and variables:
pm.request: URL, method, headers and body of the current request. In pre-request they can be changed, for examplepm.request.headers.upsert({ key: 'X-Trace-Id', value: pm.variables.replaceIn('{{$guid}}') });pm.response:code,status,json(),text(),headers.get(),responseTime;pm.variables,pm.environment,pm.collectionVariables,pm.globals,pm.iterationData: scope variables withget,set,unset(pm.iterationDatahas noset);pm.info: the request name, the iteration number;pm.sendRequest: a helper HTTP request from a script, asynchronous;pm.execution.setNextRequest: the order in the Runner and Newman.
Pattern 1. A token refreshed only when needed
The token and its expiry time live in variables, and the helper request goes out only if less than the reserve remains.
Refreshing a token on demand
// Pre-request at the collection level
const exp = Number(pm.environment.get('tokenExp') || 0);
if (Date.now() > exp - 30000) { // 30 s reserve
pm.sendRequest({
url: pm.environment.get('baseUrl') + '/auth/token',
method: 'POST',
header: { 'Content-Type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify({
clientId: pm.environment.get('clientId'),
clientSecret: pm.environment.get('clientSecret'),
}),
},
}, (err, res) => {
if (err) throw err;
const b = res.json();
pm.environment.set('token', b.access_token);
pm.environment.set('tokenExp', Date.now() + b.expires_in * 1000);
});
}
A 30 second reserve protects against expiry in the middle of a request. The helper call is asynchronous: Postman waits for the callback to finish before sending the main request, so the callback's value is available to it. The current docs also show const res = await pm.sendRequest(...): then the code after the call waits for the response. The script sits at the collection level so it works for every request.
Pattern 2. Unique data
pm.variables.replaceIn('{{$randomEmail}}') returns the value of a dynamic variable right in the script, so a unique email or key can be put into your own variable and reused in later requests.
Pattern 3. Polling an asynchronous operation with a limit
The operation returns 202 and the result appears later:
// Post-response: polling an operation that returned 202
const tries = Number(pm.variables.get('tries') || 0) + 1;
pm.variables.set('tries', tries);
const status = pm.response.json().status;
if (status !== 'done' && tries < 10) {
pm.execution.setNextRequest(pm.info.requestName);
} else {
pm.variables.set('tries', 0);
pm.test('The operation finished', () => {
pm.expect(status).to.eql('done');
});
}
The counter and the exit are mandatory: without them the loop could run forever. Also setNextRequest without a pause floods the service with requests, so a real run needs a delay between attempts. setNextRequest works in the Collection Runner and Newman, and does nothing in a single run from the request window.
Pattern 4. Signing a request. For HMAC a script uses the built-in Web Crypto (crypto.subtle.importKey with HMAC/SHA-256 and crypto.subtle.sign), and the hex result goes into a header. The secret comes from a variable, not from the code.
Limits and alternatives
A collection script runs for every request, so long computations and extra pm.sendRequest calls there slow everything down: add a condition, as in the token pattern. Complex logic in Postman is hard to test and version. If scripts grow, they ask for code with unit tests. Often the token can be obtained without a script: the built-in OAuth 2.0 authorisation type refreshes a token itself, but only when the server issued a refresh token (client credentials usually has none), and not in Newman, the Postman CLI or monitors.
Common mistakes
- A token before every request. Extra load and noise in the authorisation logs;
- Using data from a
pm.sendRequestresponse outside the callback. The code after the call runs earlier, the value is not there yet; - A loop without an attempts limit. The run never ends;
- A secret in
console.log. It lands in Newman logs and CI artefacts.
Check yourself
The 30 s reserve was removed from the token pattern and it compares Date.now() > exp. What new breakage becomes possible?
Answer
The token can expire between the check and the server handling the request: the script considered it valid and the server already answered 401. The reserve covers network delay and clock skew.
Why does the polling pattern need both a counter and the else exit?
Answer
The counter limits the attempts, and the else branch resets it and does the check. Without a reset the next iteration of the same run starts with the accumulated value, and without a limit the loop does not end if the operation hangs.
pm object gives access to the request, the response and variables. I refresh the token with a script only when it is about to expire, not before every request. Middle/Senior: I keep the token and its expiry in variables with a reserve, and make the helper request through the asynchronous pm.sendRequest: I read its value in the callback or via await, never on the line after a call without await. I build polling with a counter and an exit so the run does not hang. If script logic grows, I move it into code with tests.