Prompt
How do I compare expected vs actual API responses in tests?
Latest observation
Oct 6, 2026
OpenAI APIWeb search: off
A good way to compare expected vs actual API responses in tests is to assert on the shape and important fields rather than doing a brittle full-string comparison.
Common approaches
1. Deep equality for exact responses
If the response should match exactly:
assert actual_response == expected_response
Use this when:
- field order doesn’t matter
- the response is deterministic
- you want to verify every field
2. Compare only important fields
Often APIs include timestamps, IDs, or metadata that change. In that case, assert field-by-field:
assert actual["status"] == "ok"
assert actual["data"]["id"] == expected_id
assert actual["data"]["name"] == "Alice"
This makes tests less brittle.
3. Use partial matching
If you only care about part of the JSON:
expected = {
"status": "ok",
"data": {"name": "Alice"}
}
assert actual["status"] == expected["status"]
assert actual["data"]["name"] == expected["data"]["name"]
In some test frameworks, you can use helpers for partial matches:
- pytest: plain
assert - unittest:
assertEqual,assertDictEqual, etc. - Jest:
toMatchObject - RSpec:
include,match
4. Normalize before comparing
For responses with dynamic values, normalize them first:
actual["data"]["createdAt"] = "<ignored>"
expected["data"]["createdAt"] = "<ignored>"
assert actual == expected
Or remove fields you don’t care about:
actual.pop("timestamp", None)
expected.pop("timestamp", None)
assert actual == expected
5. Compare JSON after parsing
If responses come back as JSON strings, parse them first:
import json
actual = json.loads(response.text)
expected = {"status": "ok"}
assert actual["status"] == expected["status"]
Best practices
- Prefer field-level assertions for important behavior.
- Avoid asserting on the entire raw response if it contains unstable values.
- Use schema validation if you want to verify structure and types.
- Keep one test focused on one behavior.
Example in pytest
def test_get_user(client):
response = client.get("/user/1")
actual = response.json()
assert actual["id"] == 1
assert actual["name"] == "Alice"
assert actual["active"] is True
If you want, I can show the best way to do this in a specific language/framework like Python/pytest, JavaScript/Jest, Java/JUnit, or Postman.