API Tests That Cover Chained Request Dependencies
Most API tests I see check endpoints in isolation: send a request, assert the response, move on. That's fine until one call feeds the next. Create an order, pay for it, confirm shipment. When the hand-off between those steps breaks, isolated tests stay green and the failure turns up in production, because the chain was never exercised as a unit.
Chains are the norm in real systems. A registration flow might create an account, fetch a confirmation token and then activate the account, each step depending on data from the one before. If your tests don't thread that data through deliberately, a whole category of bugs goes untested.
An AI agent that calls your API is a chain too. It reads an ID from one tool result and passes it to the next tool, and when it gets that wrong, it often invents a plausible-looking ID instead. In this article I'll show how I pass state between requests with pytest and Behave, how I keep failures readable, how I stop chains from becoming brittle, and how I test that an agent's chain uses real values.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Assert at every link before you forward data
A chained test captures something from response A and sends it in request B. The common mistake is reaching into the body without checking the first call worked. When it didn't, you get a KeyError that points at the wrong line and hides the real failure. Treat every intermediate response as a checkpoint:
def test_order_payment_chain(client, api_base_url):
# 1. Create an order
created = client.post(f"{api_base_url}/orders",
json={"product_id": "SKU-001", "quantity": 2}, timeout=10)
assert created.status_code == 201, f"Order creation failed: {created.text}"
order_id = created.json().get("order_id")
assert order_id, f"order_id missing from create response: {created.text}"
# 2. Pay for it using the order_id from step 1
paid = client.post(f"{api_base_url}/payments",
json={"order_id": order_id, "method": "card",
"token": "test-card-token"}, timeout=10)
assert paid.status_code == 200, f"Payment failed: {paid.text}"
assert paid.json()["status"] == "approved", paid.text
# 3. The order reflects the payment
order = client.get(f"{api_base_url}/orders/{order_id}", timeout=10)
assert order.status_code == 200, order.text
assert order.json()["payment_status"] == "paid"
Each assertion message includes the response body, so when step 2 fails you see why, not just that something in the function blew up. And I always pull the forwarded value into a named variable. order_id = ... is easy to read and easy to inspect; a nested created.json()["order_id"] buried inside the next request is neither. More on readable failures in debugging failed API tests faster with better logging.
Carry state through Behave's context without making a mess
In Behave, the chain lives on context. The trap is letting it become a dumping ground of loose attributes nobody can reason about. I namespace by resource and guard every read:
# features/steps/order_steps.py
from behave import given, when, then
@given('a new order is created for product "{product_id}"')
def step_create_order(context, product_id):
resp = context.session.post(f"{context.base_url}/orders",
json={"product_id": product_id, "quantity": 1}, timeout=10)
assert resp.status_code == 201, f"Expected 201, got {resp.status_code}: {resp.text}"
context.order = resp.json()
assert "order_id" in context.order, f"Response missing order_id: {resp.text}"
@when("the customer submits a card payment")
def step_submit_payment(context):
assert hasattr(context, "order"), "No order on context: did the Given step run?"
resp = context.session.post(f"{context.base_url}/payments",
json={"order_id": context.order["order_id"],
"method": "card", "token": "test-card-token"},
timeout=10)
assert resp.status_code == 200, f"Payment step failed: {resp.text}"
context.payment = resp.json()
@then('the order payment status is "paid"')
def step_order_paid(context):
resp = context.session.get(
f"{context.base_url}/orders/{context.order['order_id']}", timeout=10)
assert resp.status_code == 200, resp.text
assert resp.json()["payment_status"] == "paid"
The hasattr guard is there for when steps get reused or a feature file is reorganised. You get a clear message about what's missing instead of an AttributeError. A scenario built this way reads like a workflow, and it fails at the step that broke the contract rather than somewhere downstream.
Keep chains from becoming brittle
Writing chain tests is the easy part. Maintaining them as the API changes is harder. When step 1's response shape shifts, a badly built chain fails at step 3 and sends you looking in the wrong place. Three habits help.
Check shape at each link. If the chain depends on order_id, assert it's present and the right type before using it. A shared helper keeps that in one place:
def assert_order_shape(data: dict) -> None:
assert isinstance(data.get("order_id"), str), f"Bad or missing order_id in: {data}"
assert "status" in data, f"Missing status in: {data}"
Move setup chains into fixtures. If several tests start from "a paid order", build it once in a fixture and let each test begin from that known state. Setup failures then show up as fixture errors, separate from the behaviour under test:
import pytest
@pytest.fixture
def paid_order(client, api_base_url):
created = client.post(f"{api_base_url}/orders",
json={"product_id": "SKU-001", "quantity": 1}, timeout=10)
assert created.status_code == 201, created.text
order_id = created.json()["order_id"]
paid = client.post(f"{api_base_url}/payments",
json={"order_id": order_id, "token": "test-card-token"}, timeout=10)
assert paid.status_code == 200, paid.text
return {"order_id": order_id, "payment": paid.json()}
Tag chains and run them at the right frequency. Full chains are slower and more stateful than single-endpoint checks. A workflow marker or tag lets CI run them on merge to main without slowing every pull request. I cover that in tagging API tests so CI can run the right subset.
Chains written by agents, and chains run by agents
When a coding agent writes a chain test, watch for one habit: it runs the flow once, sees "order_id": "ord_8f2a" in the output, and hardcodes that ID into a later step. The test passes once and fails against a fresh environment. My instructions file (.github/copilot-instructions.md, or the equivalent for your agent) says: every value passed between requests must come from an earlier response in the same test or from a fixture, never a literal copied from a previous run. In review, I search new chain tests for ID-shaped literals.
When an AI agent in your product calls your API, the chain moves to runtime. The agent calls create_order, reads the result, then calls pay_order with an ID. If it misreads the result or loses track of it, models tend to produce something that looks like an ID rather than stop. Your API will reject most of those with a 404, but you want to know how often the agent tries. I record the tool trace and check that every ID the agent sends appeared in an earlier tool result:
def test_agent_only_uses_ids_it_was_given(run_agent, checkout_scenarios):
problems = []
for scenario in checkout_scenarios:
trace = run_agent(scenario) # [{"name", "args", "result"}, ...] in call order
seen_ids = set()
for call in trace:
sent = call["args"].get("order_id")
if sent is not None and sent not in seen_ids:
problems.append((scenario, call["name"], sent))
result = call.get("result") or {}
if "order_id" in result:
seen_ids.add(result["order_id"])
assert not problems, problems
run_agent is a fixture around your own agent loop, which keeps the test independent of any vendor SDK. Because model behaviour varies between runs, I run each scenario several times. An invented ID is a hard failure on any run; it's the agent version of the KeyError above.
Worth the extra effort
Chained tests catch the bugs where every piece works on its own and the system still breaks when you put it together. Assert at each link, keep setup in fixtures, and hold agents, whether they write the chain or run it, to the rule that every value comes from somewhere real. My API testing courses build this kind of workflow testing into a pytest or Behave suite using VS Code and GitHub Copilot.