Validating responses, negative tests and authentication checks
What to check beyond the status code, how to design negative and boundary tests, and how to test API keys and bearer tokens.
A test that only checks for status 200 can pass while the API returns wrong data. Strong API tests check the whole response and deliberately try inputs that should fail.
What to validate in a response
- Status code: the exact expected code, such as 201 rather than any 2xx.
- Body values: the returned name matches what you sent, totals are correct, ids are present.
- Schema and types: required fields exist,
ageis a number and not a string, dates use the agreed format. - Headers: Content-Type is application/json; a Location header appears after a create if the API promises one.
- Response time: within the agreed limit for that endpoint.
- Side effects: after a POST, a GET returns the new record; after a DELETE, a GET returns 404.
Designing negative tests
Negative tests confirm that bad requests are rejected clearly and safely. For POST /users with a required email field, useful cases are:
- Missing email: expect 400 or 422 with a message naming the field.
- Wrong type, such as
"age": "twenty". - Boundary values, such as a name at the maximum allowed length and one character over.
- Malformed JSON, such as a missing closing brace.
- Duplicate email: expect 409 if the API rejects duplicates.
- Unsupported method, such as DELETE on a collection that does not allow it.
For each, the API should return a 4xx code, a helpful error message, and no internal details such as stack traces or database errors.
Testing authentication
APIs commonly use an API key or a bearer token in a header:
Authorization: Bearer <token>
X-API-Key: <key>The header name for API keys varies by API, so follow its documentation. Core checks are:
- No credentials: expect 401.
- Invalid or expired token: expect 401.
- Valid token, but the user lacks permission: expect 403.
- One user's token cannot read or change another user's data, for example
GET /users/43with user 42's token.
Keep keys and tokens in environment variables in your API client, not inside saved requests or URLs, because URLs often end up in logs.
Checklist for each endpoint: one positive test with full body checks, several negative tests, the four authentication cases, and a follow-up request to confirm side effects.
More in Software testing