AUTOMATION FRAMEWORKS

Writing API Tests That Cover Chained Request Dependencies

Most API tests I see in the wild test endpoints in isolation: send a request, assert the response, move on. That works fine until you're dealing with workflows where one call feeds the next — create an order, then pay for it, then confirm shipment. When those chains break, isolated tests won't catch it. The failure shows up in production, usually at the worst possible moment, because the integration between steps was never exercised as a unit.

Chained request dependencies are the norm in real systems, not the exception. A user registration flow might require a POST to create an account, a GET to retrieve the confirmation token, and a PUT to activate it — and each step depends on data returned by the previous one. If you're not threading that data through your tests deliberately, you're leaving a whole category of bugs untested. In practice, I've seen teams spend days chasing a bug that a single well-structured chain test would have caught in minutes.

This article walks through the patterns I rely on to write tests that cover these dependencies properly — how to pass state between requests, how to make failures readable, and how to structure chains so they don't become brittle maintenance nightmares. The examples use Python with pytest and requests, but the patterns translate directly to Behave and other frameworks.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

Extracting and Forwarding Response Data Across Chained API Calls

The core mechanic of a chained test is simple: capture something from response A and inject it into request B. The mistake most teams make is doing this inline without any guard rails — they assume the first call succeeded and just reach into the response body without checking. When that assumption breaks, you get a KeyError or a None-type error that points at the wrong line and obscures the real failure.

The better pattern is to assert at each step before moving on. Treat every intermediate response as a checkpoint, not a pass-through:

import requests

BASE_URL = "https://api.example.com"

def test_order_payment_chain():
    # Step 1: Create an order
    create_resp = requests.post(f"{BASE_URL}/orders", json={
        "product_id": "SKU-001",
        "quantity": 2
    })
    assert create_resp.status_code == 201, f"Order creation failed: {create_resp.text}"
    order_id = create_resp.json()["order_id"]
    assert order_id, "order_id missing from create response"

    # Step 2: Submit payment using the order_id
    pay_resp = requests.post(f"{BASE_URL}/payments", json={
        "order_id": order_id,
        "method": "card",
        "token": "tok_test_visa"
    })
    assert pay_resp.status_code == 200, f"Payment failed: {pay_resp.text}"
    payment_status = pay_resp.json()["status"]
    assert payment_status == "approved", f"Unexpected payment status: {payment_status}"

    # Step 3: Confirm the order reflects the payment
    order_resp = requests.get(f"{BASE_URL}/orders/{order_id}")
    assert order_resp.status_code == 200
    assert order_resp.json()["payment_status"] == "paid"

Notice the assertion message at each step includes the response body. That's intentional. When step 2 fails, you want to know why step 2 failed — not just that something in the test function blew up. This is especially important for debugging failed tests faster, where the difference between a useful error and a cryptic one comes down to what you logged at the point of failure.

One more thing worth naming: always extract the dependency value into a clearly named variable before using it. order_id = create_resp.json()["order_id"] is readable. requests.post(..., json={"order_id": create_resp.json()["order_id"]}) is not — and it makes the chain harder to debug when something goes wrong mid-expression.

Structuring Chained Tests in Behave So Scenarios Stay Readable

In Behave, chained dependencies live in the context object. Each step function can write to it and read from it, which makes it the natural place to carry state across a scenario. The trap here is letting context become a dumping ground — if every step writes ten attributes with no structure, you end up with a scenario that's impossible to reason about when it fails.

A pattern that works well in practice is namespacing by resource. Instead of context.order_id floating loose, store a dict: context.order = {"id": ..., "status": ...}. That way each step is explicit about what it's reading and what it's contributing.

# features/steps/order_steps.py

@given('a new order is created for product "{product_id}"')
def step_create_order(context, product_id):
    resp = context.client.post("/orders", json={"product_id": product_id, "quantity": 1})
    assert resp.status_code == 201, f"Expected 201, got {resp.status_code}: {resp.text}"
    context.order = resp.json()
    assert "order_id" in context.order, "Response missing order_id"

@when('the customer submits a card payment')
def step_submit_payment(context):
    assert hasattr(context, "order"), "No order in context — did the previous step run?"
    resp = context.client.post("/payments", json={
        "order_id": context.order["order_id"],
        "method": "card",
        "token": "tok_test_visa"
    })
    assert resp.status_code == 200, f"Payment step failed: {resp.text}"
    context.payment = resp.json()

@then('the order status should be "paid"')
def step_verify_order_paid(context):
    order_id = context.order["order_id"]
    resp = context.client.get(f"/orders/{order_id}")
    assert resp.status_code == 200
    assert resp.json()["payment_status"] == "paid"

The assert hasattr(context, "order") guard in the payment step is deliberate. If someone runs the when step without the given, or if the feature file gets reorganized carelessly, you get a clear message about what's missing rather than an AttributeError that points at the wrong line. This kind of defensive assertion is especially valuable in BDD suites where steps get reused across multiple scenarios.

This also connects to a broader principle: tests that document business rules should read like a workflow, not a list of HTTP calls. A well-structured Behave scenario for a chained dependency tells the story of what the system is supposed to do — and when it fails, it fails at the step that broke the contract, not somewhere downstream.

Keeping Chained Tests From Becoming Fragile as the API Evolves

The biggest long-term problem with chained tests isn't writing them — it's maintaining them. APIs change. A field gets renamed, a new required parameter appears, or the response shape for step 1 shifts slightly. When that happens, a poorly structured chain test fails in a way that makes it look like step 3 is broken when the real problem is in step 1. The test is technically correct but the signal is noise.

Three practices keep chains maintainable over time:

1. Validate response shapes at each step, not just status codes. If your chain depends on order_id coming back from the create call, assert that it's present and the right type before you use it. This is the same principle behind catching missing fields before production does — the earlier you assert structure, the more precise your failure signal. A missing field assertion at step 1 is infinitely more useful than a KeyError at step 3.

def assert_order_shape(data):
    assert "order_id" in data, f"Missing order_id in: {data}"
    assert isinstance(data["order_id"], str), f"order_id should be str, got {type(data['order_id'])}"
    assert "status" in data, f"Missing status in: {data}"

Pulling this into a helper function means you can reuse the shape assertion anywhere the order resource appears, and updating it in one place fixes all the chain tests that depend on it.

2. Use fixtures or factory functions to set up chain preconditions, not inline setup. If three different test scenarios all need an existing paid order as a starting point, don't repeat the create-and-pay chain in each test. Write a pytest fixture that returns the paid order, and let each test start from that known state. This isolates the "setup chain" from the "assertion under test" and makes failures much easier to attribute.

import pytest

@pytest.fixture
def paid_order(api_client):
    create_resp = api_client.post("/orders", json={"product_id": "SKU-001", "quantity": 1})
    assert create_resp.status_code == 201
    order_id = create_resp.json()["order_id"]

    pay_resp = api_client.post("/payments", json={"order_id": order_id, "token": "tok_test_visa"})
    assert pay_resp.status_code == 200

    return {"order_id": order_id, "payment": pay_resp.json()}

3. Tag chain tests so CI can run them at the right frequency. Full end-to-end chains are slower and more stateful than unit-level API tests. They shouldn't necessarily run on every commit the same way a smoke test does. Using tags to separate them — @chain, @workflow, or @e2e — gives your CI pipeline the flexibility to run them on merge to main without blocking every pull request. This is exactly the kind of problem that tagging tests for CI subsets is designed to solve.

Chained tests are worth the extra investment. They catch a class of bug that no amount of isolated endpoint testing will surface — the kind where each piece works perfectly on its own and the system still breaks when you put it together. Build the chains deliberately, assert at every step, and structure them so the failure message tells you exactly where the contract broke.