0
0
Postmantesting~15 mins

API key authentication in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify API key authentication for accessing user profile endpoint
Preconditions (3)
Step 1: Open Postman and create a new GET request
Step 2: Enter the user profile API endpoint URL in the request URL field
Step 3: In the Headers tab, add a new header with key 'x-api-key' and value as the valid API key
Step 4: Send the request
Step 5: Observe the response status code and body
Step 6: Remove the API key header
Step 7: Send the request again without the API key
Step 8: Observe the response status code and body
✅ Expected Result: When the API key is included, the response status code is 200 and the user profile data is returned. When the API key is missing, the response status code is 401 Unauthorized with an error message.
Automation Requirements - Postman test scripts
Assertions Needed:
Verify response status code is 200 when API key is present
Verify response body contains expected user profile fields
Verify response status code is 401 when API key is missing
Verify response body contains error message for missing API key
Best Practices:
Use environment variables to store API key securely
Use pre-request scripts to set headers dynamically
Write clear and concise test assertions in the Tests tab
Avoid hardcoding sensitive data in the request
Automated Solution
Postman
pm.test('Status code is 200 with API key', function () {
    pm.response.to.have.status(200);
});
pm.test('Response has user profile fields', function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('id');
    pm.expect(jsonData).to.have.property('name');
    pm.expect(jsonData).to.have.property('email');
});

The first test checks that the response status code is 200, which means the request with the API key was successful.

The second test verifies that the response body contains the expected user profile fields: id, name, and email. This confirms that the API returned the correct data.

These tests should be placed in the Tests tab of the Postman request that includes the API key in the header.

To test the missing API key scenario, create a separate request without the API key header and add tests to verify the 401 status and error message.

Common Mistakes - 3 Pitfalls
Hardcoding the API key directly in the request headers
Not checking the response status code before parsing the response body
Writing tests only for the successful case and ignoring error scenarios
Bonus Challenge

Now add data-driven testing with 3 different API keys: one valid, one invalid, and one empty

Show Hint