Pre-request Scripts - Postman Scripting

Postman scripting is JavaScript that runs around each request: pre-request scripts prepare it (tokens, dynamic data), test scripts check the response (status, body, headers, schema, time). Scripts are what turn a collection of manual requests into an automated API test suite. Every script below was run with Newman against a local API — all 14 assertions passed.

In current Postman versions, both live under a request's Scripts tab as Pre-request and Post-response; older versions show a separate Pre-request Script tab and a Tests tab. The code is the same.

Advertisement

Where Scripts Run

Level Runs Typical use
Collection Before/after every request in the collection Getting an auth token, common checks (response time, JSON content type)
Folder Before/after every request in the folder Setup for one module (e.g. create a test customer)
Request Only for that request Request-specific data and assertions

Order for one request: collection pre-request → folder pre-request → request pre-request → request is sent → collection tests → folder tests → request tests.

Pre-request Scripts

Log in once and reuse the token (collection level) ⭐

if (!pm.collectionVariables.get('token')) {
  pm.sendRequest({
    url: pm.collectionVariables.get('baseUrl') + '/auth',
    method: 'POST',
    header: { 'Content-Type': 'application/json' },
    body: { mode: 'raw', raw: JSON.stringify({ username: 'admin', password: pm.environment.get('password') }) }
  }, (err, res) => {
    if (err) { console.error(err); return; }
    pm.collectionVariables.set('token', res.json().token);
  });
}

Every request then sends Authorization: Bearer {{token}}. pm.sendRequest makes an extra HTTP call from inside a script, so no separate "Login" request has to run first. Keep the real password in an environment variable (marked secret), not in the script.

Unique test data

pm.variables.set('firstname', 'QA_' + Date.now());   // unique every run
// Body: { "firstname": "{{firstname}}", "totalprice": {{$randomInt}} }

Postman also has built-in dynamic variables such as {{$randomInt}}, {{$randomEmail}}, {{$guid}} and {{$timestamp}}. Unique data stops tests failing with "already exists" on the second run.

Test Scripts (Post-response) ⭐

pm.test('201 Created', () => pm.response.to.have.status(201));
pm.test('JSON response', () => pm.response.to.have.header('Content-Type', 'application/json'));

const body = pm.response.json();
pm.test('id is a positive number', () => pm.expect(body.bookingid).to.be.a('number').and.above(0));
pm.test('name echoed back', () => pm.expect(body.booking.firstname).to.eql(pm.variables.get('firstname')));
pm.test('responds in under 1s', () => pm.expect(pm.response.responseTime).to.be.below(1000));

Each pm.test is reported separately, so one failing check doesn't hide the others. Assertions use the Chai library's readable style.

Assertion quick reference

Check Assertion
Status code pm.response.to.have.status(200)
Header pm.response.to.have.header('Content-Type')
Equal value pm.expect(x).to.eql('Asha') (deep equality — use for objects and arrays)
Type pm.expect(x).to.be.a('number') / 'string' / 'array'
Property exists pm.expect(obj).to.have.property('email')
Contains pm.expect(list).to.include('admin')
Pattern pm.expect(name).to.match(/^QA_\d+$/)
Range pm.expect(n).to.be.above(0).and.below(100)
Response time pm.expect(pm.response.responseTime).to.be.below(1000)
Not present pm.expect(pm.response.text()).to.not.include('Traceback')

JSON schema validation

const schema = {
  type: 'object',
  required: ['bookingid', 'booking'],
  properties: {
    bookingid: { type: 'integer' },
    booking: { type: 'object', required: ['firstname', 'totalprice'] }
  }
};
pm.test('matches schema', () => pm.response.to.have.jsonSchema(schema));

A schema check catches contract changes — a renamed, missing or retyped field — that value checks can miss. (Older tutorials use tv4.validate(); jsonSchema() is the current way.) More: JSON Schema Validation.

Negative tests

// GET /bookings/999999
pm.test('404 for unknown id', () => pm.response.to.have.status(404));
pm.test('error message present', () => pm.expect(pm.response.json().error).to.be.a('string').that.is.not.empty);
pm.test('no stack trace leaked', () => pm.expect(pm.response.text()).to.not.include('Traceback'));

Extracting Values

What Code
JSON body pm.response.json() → then .user.id, .items[0].name
Text body pm.response.text()
Header pm.response.headers.get('Location')
Cookie pm.cookies.get('session')
Status / time pm.response.code, pm.response.responseTime

Chaining Requests

// Test script of "Create booking"
pm.collectionVariables.set('bookingId', pm.response.json().bookingid);

// URL of the next request
{{baseUrl}}/bookings/{{bookingId}}

Use collection variables for values created during a run and environment variables for per-environment settings such as the base URL. Full end-to-end chains with negative and data-driven tests: Postman API Chaining.

Debugging Scripts

  • console.log() — output appears in the Postman Console (and in Newman's CLI output); ours printed Created booking 1001.
  • Postman Console — shows every request with its resolved URL, headers and body, so an unresolved {{variable}} is obvious.
  • Guard missing data — throw a clear error in a pre-request script if a required variable is empty.

Running Scripts Automatically

  • Collection Runner — run a whole collection in Postman, optionally with a CSV/JSON data file.
  • Newman — run it from the command line and in CI: newman run collection.json -e qa.json -r cli,junit. See Postman Newman CI/CD.
  • Postman Monitors — run a collection on a schedule from Postman's cloud (for example every hour against staging) and alert when tests fail. Good for API health checks; your CI pipeline remains the place for full regression.

Plan which assertions each endpoint really needs — positive, negative and edge cases — in the API Testing Scenario Lab.

From Real Projects

I've worked with APIs at the level this page covers: CRUD operations, HTTP methods, JSON and XML formats, and extracting and validating values with JSON path. A good habit from that work: test the full create–read–update–delete cycle for a resource and check each response in detail. Testsigma supports web, mobile and API test automation, so understanding APIs was part of understanding the product I was testing. Assert on the response body, not just the status code.

📚 Official documentation: Postman Learning Center · MDN: HTTP

FAQs

What is a pre-request script?

JavaScript that runs before a request is sent — to fetch tokens, set variables, generate unique data or compute signatures.

Where can you add scripts?

At collection, folder and request level. Collection scripts run for every request, which makes them ideal for authentication and common checks.

What is a test script?

JavaScript that runs after the response arrives, using pm.test and pm.expect to validate status, body, headers, schema and response time.

How do you validate a JSON schema in Postman?

pm.response.to.have.jsonSchema(schema) with a JSON Schema object.

How do you pass data between requests?

Save it in a test script with pm.collectionVariables.set() (or an environment variable) and use {{name}} in later requests.

How do you get a token automatically?

Use pm.sendRequest in a collection-level pre-request script to call the login endpoint and store the token when it's missing.