0
0
Postmantesting~10 mins

API key authentication in Postman - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if the API correctly accepts requests with a valid API key and rejects requests without it or with an invalid key.

Test Code - Postman
Postman
pm.test("API key authentication - valid key", function () {
    pm.sendRequest({
        url: pm.environment.get("api_url") + "/data",
        method: 'GET',
        header: {
            'x-api-key': pm.environment.get("valid_api_key")
        }
    }, function (err, res) {
        pm.expect(err).to.eql(null);
        pm.expect(res).to.have.property('status', 200);
        pm.expect(res.json()).to.have.property('success', true);
    });
});

pm.test("API key authentication - invalid key", function () {
    pm.sendRequest({
        url: pm.environment.get("api_url") + "/data",
        method: 'GET',
        header: {
            'x-api-key': 'invalid_key'
        }
    }, function (err, res) {
        pm.expect(err).to.eql(null);
        pm.expect(res).to.have.property('status', 401);
        pm.expect(res.json()).to.have.property('error', 'Unauthorized');
    });
});

pm.test("API key authentication - missing key", function () {
    pm.sendRequest({
        url: pm.environment.get("api_url") + "/data",
        method: 'GET'
    }, function (err, res) {
        pm.expect(err).to.eql(null);
        pm.expect(res).to.have.property('status', 401);
        pm.expect(res.json()).to.have.property('error', 'Unauthorized');
    });
});
Execution Trace - 3 Steps
StepActionSystem StateAssertionResult
1Send GET request to /data with valid API key in header 'x-api-key'API server receives request with valid API keyResponse status code is 200 and JSON contains 'success': truePASS
2Send GET request to /data with invalid API key in header 'x-api-key'API server receives request with invalid API keyResponse status code is 401 and JSON contains 'error': 'Unauthorized'PASS
3Send GET request to /data without API key headerAPI server receives request missing API keyResponse status code is 401 and JSON contains 'error': 'Unauthorized'PASS
Failure Scenario
Failing Condition: API server does not validate API key correctly or returns wrong status code
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test check when sending a request with a valid API key?
AThe server returns status 401 Unauthorized
BThe server returns status 200 and success true
CThe server ignores the API key
DThe server returns status 500 Internal Server Error
Key Result
Always test API key authentication with valid, invalid, and missing keys to ensure secure access control.