Prompt
How do I validate status codes and JSON payloads in API tests?
Latest observation
Oct 6, 2026
OpenAI APIWeb search: off
To validate status codes and JSON payloads in API tests, you typically check two things:
- The HTTP response status
- The response body structure and values
1) Validate status codes
Check that the API returns the expected HTTP code, such as:
200 OKfor successful GET/PUT requests201 Createdfor successful POST requests204 No Contentfor successful deletes400 Bad Requestfor validation errors401 Unauthorized/403 Forbiddenfor auth issues404 Not Foundfor missing resources500 Internal Server Errorfor unexpected failures
Example
- If you call
GET /users/1, expect200 - If you call
POST /userswith valid data, expect201 - If you call
DELETE /users/1, expect204
2) Validate JSON payloads
Verify that the response body:
- is valid JSON
- has the expected fields
- has correct data types
- contains expected values
- does not contain unexpected/malformed data
Example checks
For a response like:
{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}
You might validate:
idis present and is a numbernameequals"Alice"emailis present and matches an email format
3) Common assertions to use
Depending on your test tool/framework, assertions usually look like:
- Status code
assert response.status_code == 200
- JSON key exists
assert "id" in response.json()
- Exact value
assert response.json()["name"] == "Alice"
- Type check
assert isinstance(response.json()["id"], int)
- Array length
assert len(response.json()) > 0
4) Example in Python (requests + pytest)
import requests
def test_get_user():
response = requests.get("https://api.example.com/users/1")
assert response.status_code == 200
data = response.json()
assert data["id"] == 1
assert data["name"] == "Alice"
assert "email" in data
5) Example in JavaScript (fetch + Jest`)
test('get user', async () => {
const response = await fetch('https://api.example.com/users/1');
expect(response.status).toBe(200);
const data = await response.json();
expect(data.id).toBe(1);
expect(data.name).toBe('Alice');
expect(data.email).toBeDefined();
});
6) Good practices
- Validate both happy path and error cases
- Check schema/structure, not only exact values
- Assert critical fields only; avoid overly brittle tests
- Use JSON schema validation for larger payloads
- Separate tests for:
- status code
- response body
- headers
- error handling
7) Schema validation example
If your API has a known contract, use JSON Schema to ensure the payload matches expected structure and types.
Example checks:
- required fields exist
- types are correct
- no extra fields if your contract forbids them
If you want, I can also show you how to do this in Postman, RestAssured, pytest, or Cypress.