Postman
01 / 02

Collections, Variables & Scripts

Collections, Variables & Scripts

Variables & Environments

Variables resolve from narrowest to broadest scope: Local > Data > Environment > Collection > Global — a narrower-scope variable silently wins over a broader one with the same name. Reference any of them the same way: {{variableName}}.

GET {{baseUrl}}/users/{{userId}}
Authorization: Bearer {{authToken}}

# Environment: "Staging"
baseUrl = https://staging-api.example.com

# Environment: "Production"
baseUrl = https://api.example.com

# Switching the active environment in the dropdown retargets every
# request in the collection with zero edits to the requests themselves.

Pre-request Scripts & Chaining Requests

// Pre-request Script tab — runs BEFORE the request is sent
pm.environment.set('timestamp', Date.now());

// Refresh an expired token before the main request proceeds
const expiry = pm.environment.get('tokenExpiry');
if (!expiry || Date.now() > expiry) {
  pm.sendRequest({
    url: pm.environment.get('baseUrl') + '/auth/refresh',
    method: 'POST',
    body: { mode: 'raw', raw: JSON.stringify({ refreshToken: pm.environment.get('refreshToken') }) },
  }, (err, res) => {
    const body = res.json();
    pm.environment.set('authToken', body.accessToken);
    pm.environment.set('tokenExpiry', Date.now() + body.expiresIn * 1000);
  });
}

Test Scripts

// Test tab — runs AFTER the response is received
pm.test('status is 200', () => {
  pm.response.to.have.status(200);
});

pm.test('response has expected user shape', () => {
  const body = pm.response.json();
  pm.expect(body).to.have.property('id');
  pm.expect(body.email).to.match(/@/);
});

// Chain to a later request — save a value from THIS response
pm.test('save auth token for next request', () => {
  const body = pm.response.json();
  pm.environment.set('authToken', body.token);
});

// Dynamic variables — fresh value generated at send time, no setup needed
// {{$timestamp}}  {{$guid}}  {{$randomEmail}}

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free