Verify API authentication protects endpoints
Preconditions (3)
✅ Expected Result: The request without authentication returns 401 Unauthorized or 403 Forbidden. The request with valid authentication returns 200 OK with expected data.
Jump into concepts and practice - no test required
pm.test('Unauthorized request returns 401 or 403', function () { pm.response.to.have.status.oneOf([401, 403]); }); // This test runs only if auth header is present if (pm.request.headers.has('Authorization')) { pm.test('Authorized request returns 200', function () { pm.response.to.have.status(200); }); pm.test('Response body contains expected data', function () { const jsonData = pm.response.json(); pm.expect(jsonData).to.have.property('data'); }); }
This Postman test script checks the API response status and body.
First, it verifies that requests without authentication return 401 or 403 status codes, indicating access is denied.
Then, if the Authorization header is present, it asserts the response status is 200, meaning access is granted.
Finally, it checks the response body contains a 'data' property, confirming the API returned expected content.
Using environment variables for tokens and organizing tests in collections helps keep tests clean and reusable.
Now add data-driven testing with 3 different API tokens: one valid, one expired, and one invalid
pm.test('Status is 401', () => {
pm.response.to.have.status(401);
});pm.test('Unauthorized status', () => {
pm.response.to.have.status(403);
});