REST API
Beginner
1 min read
Testing REST APIs with Postman
Example
// Postman: Pre-request Script — auto-refresh expired JWT
const tokenExpiry = pm.environment.get('tokenExpiry');
const now = Math.floor(Date.now() / 1000);
if (!tokenExpiry || now >= tokenExpiry - 60) {
pm.sendRequest({
url: pm.environment.get('baseUrl') + '/auth/refresh',
method: 'POST',
header: { 'Content-Type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify({ refreshToken: pm.environment.get('refreshToken') })
}
}, (err, response) => {
const json = response.json();
pm.environment.set('accessToken', json.accessToken);
pm.environment.set('tokenExpiry', now + json.expiresIn);
});
}
// Postman: Test Script — assert response shape
pm.test('Status is 200', () => pm.response.to.have.status(200));
pm.test('Has data array', () => {
const json = pm.response.json();
pm.expect(json).to.have.property('data').that.is.an('array');
pm.expect(json.data.length).to.be.greaterThan(0);
});
pm.test('First product has required fields', () => {
const product = pm.response.json().data[0];
pm.expect(product).to.have.all.keys('id', 'name', 'price', 'status');
pm.expect(product.price).to.be.a('number').and.above(0);
});
pm.test('Response time < 500ms', () => pm.expect(pm.response.responseTime).to.be.below(500));