Postman Pre-Request and Test Scripts
In this tutorial, you will learn about Postman Pre. We cover key concepts, practical examples, and best practices to help you master this topic.
Postman scripts are JavaScript code that execute before (pre-request) and after (test) API requests. Pre-request scripts prepare data or authenticate. Test scripts validate responses and extract data for subsequent requests.
What You'll Learn
- Pre-request script patterns and use cases
- Test script assertions with pm.expect
- Chaining requests via environment variables
- Dynamic data generation
- Script order of execution
Why It Matters
Scripts transform Postman from a manual tool into an automated test runner. Pre-request scripts eliminate manual setup. Test scripts provide immediate validation without switching contexts.
Real-World Use
Postman collections for AWS services use pre-request scripts to sign requests. Stripe's collection uses test scripts to validate idempotency keys. Authentication flows use pre-request scripts to obtain tokens.
flowchart LR
Request[Request Execution] --> PreRequest[Pre-request Script]
PreRequest --> Send[Send Request]
Send --> Test[Test Script]
Test --> Result[View Results]
PreRequest --> Auth[Set Auth Token]
PreRequest --> Data[Generate Test Data]
Test --> Assert[Assertions]
Test --> Extract[Extract Data for Next Request]
Teacher Mindset
Pre-request scripts set up the stage. Test scripts validate the performance. Use pre-request for authentication, data generation, and variable setup. Use test scripts for response validation and data extraction.
Code Examples
// Example 1: Pre-request script for authentication
const loginRequest = {
url: pm.environment.get('base_url') + '/auth/login',
method: 'POST',
header: { 'Content-Type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify({
username: pm.environment.get('username'),
password: pm.environment.get('password')
})
}
};
pm.sendRequest(loginRequest, (err, res) => {
if (!err) {
const token = res.json().token;
pm.environment.set('auth_token', token);
}
});
// Example 2: Test script with assertions
pm.test('Status code is 201', () => {
pm.response.to.have.status(201);
});
pm.test('Response has expected structure', () => {
const body = pm.response.json();
pm.expect(body).to.have.property('id');
pm.expect(body).to.have.property('name');
pm.expect(body.name).to.be.a('string');
});
pm.test('Response time is acceptable', () => {
pm.expect(pm.response.responseTime).to.be.below(500);
});
// Example 3: Chaining requests with extracted data
// Test script that extracts data for the next request
const body = pm.response.json();
pm.environment.set('created_user_id', body.id);
pm.environment.set('created_user_email', body.email);
// Conditional logic
if (body.role === 'admin') {
pm.environment.set('requires_admin_test', 'true');
} else {
pm.environment.set('requires_admin_test', 'false');
}
console.log(`Created user ${body.id} with role ${body.role}`);
Common Mistakes
- Putting authentication logic in test scripts instead of pre-request scripts
- Not handling errors in pm.sendRequest callbacks
- Overwriting environment variables from parallel requests
- Using console.log for debugging instead of Postman's console
- Writing scripts that depend on execution order between requests
Practice
- Write a pre-request script that generates a random email address.
- Write a test script that validates status code, body structure, and response time.
- Chain two requests: create a resource, then fetch it by the extracted ID.
- Add conditional logic based on response data.
- Challenge: Build a pre-request script that retries authentication if the token is expired.
FAQ
Mini Project
Build a Postman collection with a login flow: pre-request script authenticates and sets token, a create user request uses the token, a test script validates the created user, and extracts the user ID for a follow-up GET request.
What's Next
Next, you will learn about Newman CLI for running Postman collections in CI/CD.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro