Request Scripting: Pre-Request and Post-Response Scripts Explained
Some things a request needs can’t be hardcoded — a signature computed from the request body, a token fetched moments before the call, a value derived from the previous response. Scripting handles the cases a static request definition can’t: real JavaScript that runs at specific points in a request’s lifecycle.
Pre-Request vs. Post-Response Scripts
- Pre-request scripts run before the HTTP call goes out. Whatever the script sets — a header, a computed value, a variable — is applied to the request before it’s sent.
- Post-response (“test”) scripts run after the response comes back, with the response body, status, and headers available to inspect. This is where assertions typically live: checking that a field matches what you expected, that the status code was 200, that a value from this response should feed into the next request.
A Familiar API Surface
Most API clients that support scripting, HTTP Titan included, expose a
pm-style object (short for the Postman convention this pattern
originated from): pm.environment.get/set and pm.variables.get/set to
read and write variables, pm.request to inspect or modify the outgoing
request, pm.response to read the response, and pm.test(name, fn) with
pm.expect() for assertions. If you’ve scripted against Postman before,
the core object shape is familiar — though no client (this one included)
promises byte-for-byte parity with every Postman-specific API.
// Pre-request script
pm.environment.set('request_time', Date.now());
// Post-response script
pm.test('Status is 200', () => {
pm.expect(pm.response.status).to.equal(200);
});
Sandboxing
Scripts don’t run with the same trust as your own machine’s code. They
execute in an isolated JavaScript sandbox, not in the same context your
browser tab or the API server runs in — no filesystem access, no ability
to make arbitrary network calls of their own, and a hard timeout so a
runaway loop can’t hang the request indefinitely. console.log output is
captured for display rather than treated as trusted system output.
One deliberate restriction worth knowing: scripts can’t read variables
you’ve marked secret — pm.environment.get() returns
nothing for a secret entry, even though the request itself still resolves
and sends it correctly. A script that leaked a secret into a log or a
request body it wasn’t supposed to touch would defeat the point of marking
it secret in the first place.
Testing Scripts in HTTP Titan
HTTP Titan runs pre-request and post-response scripts in a sandboxed
JavaScript environment with a pm/titan-compatible API — variables,
request/response inspection, and pm.test/pm.expect assertions all
work. Anything a pre-request script sets on the request (headers, URL,
body, variables) is applied before the call goes out; anything a
post-response script asserts shows up as a clear pass/fail once the
response comes back.