Master Postman: Advanced Environment Variables and Pre‑request Scripts for API Testing
This guide explores Postman's powerful yet often overlooked features—environment and collection variables, pre‑request scripts, and test scripts—showing how to automate API testing, manage multiple environments, and streamline token handling for more efficient backend development.
Environment Variables
Postman allows you to define global and environment‑specific variables such as host and port, which can be referenced in request URLs using the {{variable}} syntax. You can create multiple environments (e.g., local, test) and switch between them, with the active environment overriding globals when names clash.
Pre‑request Script
Running JavaScript
Pre‑request scripts execute JavaScript before a request is sent. For example, you can set variables programmatically:
pm.globals.set("key1","value1");
pm.environment.set("key2","value2");You can also delete variables:
pm.globals.unset("key1");
pm.environment.unset("key2");Sending a GET request from a script
Use pm.sendRequest to issue an auxiliary GET request and log the result to the console:
pm.sendRequest({url: "http://localhost/api", method: "GET"}, function (err, res) { console.log(res); });Sending a POST request for token acquisition
When an API requires authentication, you can fetch a JWT token in a pre‑request script, store it in a collection variable, and reuse it in subsequent requests:
pm.sendRequest({url: "http://localhost/login", method: "POST", body: {mode: "raw", raw: JSON.stringify({user:"admin",pass:"123"})}}, function (err, res) { var token = res.json().data.token; pm.collectionVariables.set("TOKEN", token); });Later, include the token in request headers using {{TOKEN}}.
Tests
Test scripts run after a request completes. They can also store values, such as caching a JWT token to avoid repeated logins:
var token = pm.response.json().data.token; pm.collectionVariables.set("TOKEN", token);The execution order is: collection‑level pre‑request scripts first, then folder‑level, then request‑level; after the request, the same hierarchy applies to test scripts.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
