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.
Jump into concepts and practice - no test required
This test checks if the API correctly accepts requests with a valid API key and rejects requests without it or with an invalid key.
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'); }); });
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Send GET request to /data with valid API key in header 'x-api-key' | API server receives request with valid API key | Response status code is 200 and JSON contains 'success': true | PASS |
| 2 | Send GET request to /data with invalid API key in header 'x-api-key' | API server receives request with invalid API key | Response status code is 401 and JSON contains 'error': 'Unauthorized' | PASS |
| 3 | Send GET request to /data without API key header | API server receives request missing API key | Response status code is 401 and JSON contains 'error': 'Unauthorized' | PASS |
API key in Postman when testing an API?Authorization header with a Bearer token format for API keys.api_key is not a standard header key; Content-Type and Accept relate to data format, not authentication.GET https://api.example.com/data?api_key=12345
api_key: 12345. The API still returns 401 Unauthorized. What is the most likely issue?Authorization header, not api_key.