Scripts
Scripts run in a Postman-like JavaScript runtime. The runtime exposes both pm and cm aliases.
Common APIs:
| API | Purpose |
|---|---|
cm.environment.get(name) | Read a selected environment variable. |
cm.environment.set(name, value) | Set an environment variable for the runtime. |
cm.environment.unset(name) | Remove an environment variable for the runtime. |
cm.globals.get(name) | Read a global variable. |
cm.globals.set(name, value) | Set a global variable. |
cm.variables.get(name) | Read merged variables. |
cm.variables.replaceIn(text) | Replace {{variable}} templates in text. |
cm.request.headers.get(name) | Read request header value. |
cm.request.headers.set(name, value) | Set or replace a request header. |
cm.request.headers.remove(name) | Remove a request header. |
cm.request.url.update(url) | Replace the request URL. |
cm.request.body.raw | Read or replace the raw request body. |
cm.response.code | Read response status code in post-response phases. |
cm.response.text() | Read response body as text. |
cm.response.json() | Parse response body as JSON. |
cm.test(name, fn) | Record a test result in the diagnostics console. |
cm.expect(value) | Assertions inside a test: .to.equal(x), .to.include(x), .to.be.within(min, max). |
console.log(...) | Write to the diagnostics console. |
Supported require(...) packages are crypto-js, moment, and uuid.
Script phases
| Protocol | Before phase | After phase |
|---|---|---|
| HTTP | Pre-request | Post-response |
| GraphQL | Before query | After response |
| gRPC | Before invoke, On message | After response |
| WebSocket | Before connect | On message |
Collection and folder scripts run before the request script for the same phase. Request scripts are the most specific scope.
Pre-request example
const uuid = require('uuid');
cm.environment.set('request_id', uuid.v4());
cm.request.headers.set('X-Request-Id', cm.environment.get('request_id'));
cm.request.url.update(cm.variables.replaceIn('{{host}}/healthz'));
console.log('Prepared request', cm.request.url.toString());
Post-response example
cm.test('status is 200', () => {
cm.expect(cm.response.code).to.equal(200);
});
const data = cm.response.json();
if (data.token) {
cm.environment.set('token', data.token);
}
console.log('Response received', cm.response.code);
Where scripts run
The same scripts run in the desktop app, the JetBrains plugin, and the CLI. Collection, folder, and request scripts run in the same order everywhere.