Debugging Failed API Tests Faster With Better Logging
Few things slow down a test review more than a failure that tells you almost nothing. You see AssertionError: assert 404 == 200, and then you're re-running the test locally, adding a print statement, re-running again and trying to reconstruct a request you can't quite see. Most of that time is avoidable. If the test had recorded what it sent and what it got back, the cause would usually be obvious from the first failure.
Good failure output has a new reader too. More teams now hand failing runs to an AI assistant or a coding agent to triage: "why did this fail, and is it the test or the API?" The assistant can only reason about what's in the output. A bare assertion error gets you a confident guess. A failure with the method, URL, status, response body and a request ID gets you a useful answer, and a person can check it quickly.
Here's the logging structure I use so API test failures explain themselves: capturing the request and response at the moment of failure, writing assertion messages that carry context, and configuring pytest so you see the right amount in VS Code and in CI, without leaking secrets into logs that both people and agents read.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Log the full request and response at the moment of failure
The key detail is when the information is captured. By the time you re-run a failing test, the data may have changed, the token may have expired, or the bug may not reproduce. So I log every request and response as it happens, at debug level, and let pytest show those logs only for the tests that fail.
A requests response hook makes this automatic for every call through the session:
import logging
import requests
log = logging.getLogger("api")
REDACT = {"authorization", "cookie", "x-api-key"}
def _headers(headers):
return {k: ("***" if k.lower() in REDACT else v) for k, v in headers.items()}
def _body(body):
if isinstance(body, bytes):
body = body.decode("utf-8", errors="replace")
return (body or "")[:2000]
def log_exchange(response, *args, **kwargs):
req = response.request
log.debug(
"%s %s -> %s in %.2fs\nrequest headers: %s\nrequest body: %s\n"
"response headers: %s\nresponse body: %s",
req.method, req.url, response.status_code, response.elapsed.total_seconds(),
_headers(req.headers), _body(req.body),
_headers(response.headers), response.text[:4000],
)
def make_session(headers):
session = requests.Session()
session.headers.update(headers)
session.hooks["response"].append(log_exchange)
return session
The redaction matters. These logs end up in CI artefacts, in bug reports and, increasingly, pasted into an AI chat or read by an agent. Strip tokens, cookies and API keys at the source so nobody has to remember to do it later. If responses can contain personal data, mask those fields too before logging.
Truncating bodies keeps logs readable when an endpoint returns a large list. Pick a limit that keeps the start of the payload, which is where error envelopes usually live.
Let pytest show the logs only when a test fails
Pytest captures log records during each test and includes them in the report for failed tests, under a "Captured log call" section. Passing tests stay quiet. You only need to capture at the right level:
[pytest]
log_level = DEBUG
log_format = %(asctime)s %(levelname)s %(name)s: %(message)s
log_date_format = %H:%M:%S
When I want to watch requests live while working on a single test in VS Code, I turn on live logging for that run only:
pytest tests/api/test_orders.py -k cancel -o log_cli=true --log-cli-level=DEBUG
Traceback length is the other dial. Locally I often use --tb=short so the failure and my assertion message are easy to find. In CI I keep the default, because nobody can step through the code there and the extra frames sometimes matter. Adding -ra prints a short summary of every non-passing test at the end of the run, which is a quick index into a long log.
# local, focused
pytest --tb=short -ra
# CI, keep the evidence
pytest -ra --junitxml=results.xml
Structure assertion messages so the failure explains itself
Logs show what happened. The assertion message should say what was expected and why it matters, in one place, without making anyone scroll:
def test_cancelled_order_cannot_be_shipped(api, cancelled_order):
response = api.post(f"/orders/{cancelled_order['id']}/ship")
assert response.status_code == 409, (
f"shipping a cancelled order should be rejected with 409, got "
f"{response.status_code}; order={cancelled_order['id']} "
f"request_id={response.headers.get('X-Request-Id')} body={response.text[:500]}"
)
A good message answers three questions: what rule was being checked, what actually happened, and how to find this request elsewhere. Use whatever request or correlation header your API returns; with it, a developer can go straight to the server logs.
A small helper keeps this consistent and stops every test author, human or agent, from inventing a different format:
def expect_status(response, expected, rule):
assert response.status_code == expected, (
f"{rule}: expected {expected}, got {response.status_code} for "
f"{response.request.method} {response.request.url}; "
f"request_id={response.headers.get('X-Request-Id')}; body={response.text[:500]}"
)
Failure output that an AI assistant can actually use
When a failure reaches an assistant, whether you paste it into chat or an agent reads the CI log, the same output that helps a person helps the model. A few habits make the difference between a useful diagnosis and a plausible guess:
- Keep the whole exchange together. Request, response and assertion message in one block, so the assistant doesn't have to match them up across a long log.
- State the rule in words. "Shipping a cancelled order should be rejected" lets the assistant reason about whether the test or the API is wrong. A bare number comparison doesn't.
- Include environment and version. Base URL, build or commit, and the test environment name. Many "bugs" are a test pointed at the wrong place.
- Never include secrets. Redaction at the source is the only reliable way.
I also give agents a rule in the repository instructions: when diagnosing a failure, quote the evidence from the log that supports the conclusion. That makes the diagnosis checkable, and it surfaces quickly when the assistant is guessing. I write more about that workflow in using AI to explain a test failure you did not write.
The same logging carries over if you test agents themselves. An agent run is a chain of model calls and tool calls, and when one fails you need each step's input and output in order, with the same redaction and the same correlation IDs. The habit is identical, just applied to a longer chain.
From one failure to many
Once every failure carries the same structured context, patterns across a run become visible: the same endpoint, the same status, the same environment. That's where grouping failures pays off, which I cover in organizing API test failures so patterns surface fast. And when it's a real bug, the same output becomes most of the report; see turning a failing test run into a useful bug report.
Better logging isn't more logging. It's capturing the exchange when it happens, redacting it, and putting the rule and the evidence in the failure message, so the first failure is enough for you, a teammate or an assistant to understand. If you'd like to build that kind of client and suite step by step in VS Code with GitHub Copilot, that's part of what my API testing courses cover.