Writing API Tests That Catch Order-of-Operations Bugs
Order-of-operations bugs are some of the sneakiest failures I've seen in production APIs. The individual endpoints all return 200s, every field is present, every type is correct — and yet the system breaks because something happened in the wrong sequence. A payment was captured before the order was confirmed. A user account was activated before email verification completed. A resource was deleted while a downstream process still held a reference to it. Each endpoint looked fine in isolation. The sequence was the bug.
The root problem is that most test suites are organized around endpoints, not workflows. When you write one test per route, you're validating that a thing can happen — not that it happens at the right time, in the right state, after the right preconditions are met. That's a real coverage gap, and it's the kind that only shows up when real users walk through a full journey. If you've ever had a bug that "couldn't reproduce in testing" but was immediately obvious in prod, sequencing is often the culprit.
In this article I'll show you concrete patterns for writing API tests that treat sequence as a first-class concern — using pytest and Behave to model the order of calls, assert on intermediate states, and fail loudly when a workflow goes sideways. These aren't exotic techniques; they're disciplined habits that pay off every time a developer refactors the business logic underneath your API.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Modeling the Call Sequence Explicitly Instead of Assuming It
The first habit to build is making the sequence of API calls visible in the test itself — not buried in a setup fixture or implied by test file order. When the sequence is explicit, a failing test tells you exactly where in the workflow things went wrong.
Here's a pattern I use in pytest for a typical "create, then act, then verify" workflow — say, creating a cart, adding an item, and then checking out:
import pytest
import requests
BASE = "https://api.example.com"
def test_checkout_requires_item_in_cart(auth_headers):
# Step 1: Create a cart
cart_resp = requests.post(f"{BASE}/carts", headers=auth_headers)
assert cart_resp.status_code == 201, "Cart creation failed"
cart_id = cart_resp.json()["id"]
# Step 2: Add an item — must happen before checkout
item_resp = requests.post(
f"{BASE}/carts/{cart_id}/items",
json={"sku": "WIDGET-42", "qty": 1},
headers=auth_headers,
)
assert item_resp.status_code == 200, "Item add failed"
# Step 3: Checkout — only valid after item is present
checkout_resp = requests.post(
f"{BASE}/carts/{cart_id}/checkout", headers=auth_headers
)
assert checkout_resp.status_code == 200
assert checkout_resp.json()["status"] == "confirmed"
Notice the inline comments marking each step. That's not decoration — it's documentation. Anyone reading this test six months from now can see the intended sequence without having to reverse-engineer it. This connects directly to the idea of tests that document business rules: the sequence is a business rule, and the test should make that obvious.
The next thing to add is a negative test for the wrong order. Don't just test the happy path sequence — explicitly test that skipping a step produces the right error:
def test_checkout_fails_on_empty_cart(auth_headers):
# Create a cart but intentionally skip adding items
cart_resp = requests.post(f"{BASE}/carts", headers=auth_headers)
assert cart_resp.status_code == 201
cart_id = cart_resp.json()["id"]
# Attempt checkout immediately — should be rejected
checkout_resp = requests.post(
f"{BASE}/carts/{cart_id}/checkout", headers=auth_headers
)
assert checkout_resp.status_code == 422
assert "empty" in checkout_resp.json().get("error", "").lower()
If this test passes, you've confirmed the API enforces the sequence. If it fails — if the API lets you check out an empty cart — you've caught an order-of-operations bug before it reaches prod. That's the whole point.
Using Behave Scenarios to Assert on Intermediate State Between Steps
BDD scenarios are a natural fit for sequencing tests because Gherkin's Given / When / Then / And structure mirrors a workflow. The key discipline is asserting on intermediate state — not just the final outcome. If you only check the end result, a bug in step two might be masked by a forgiving step three.
Here's a Behave feature file for an order fulfillment workflow:
Feature: Order fulfillment sequence
Scenario: Payment is only captured after order is confirmed
Given a customer has a pending order
When the order is confirmed by the warehouse
Then the order status is "confirmed"
And the payment capture endpoint is called
And the payment status is "captured"
Scenario: Payment is not captured if order confirmation fails
Given a customer has a pending order
When the warehouse rejects the order
Then the order status is "rejected"
And the payment status remains "authorized"
The second scenario is the one that catches the bug. In the step definitions, you're making an actual API call at each And step and asserting on the intermediate state — not just the final payment status:
# steps/order_steps.py
from behave import given, when, then
import requests
BASE = "https://api.example.com"
@given("a customer has a pending order")
def step_create_pending_order(context):
resp = requests.post(f"{BASE}/orders", json={"customer_id": "test-user"})
assert resp.status_code == 201
context.order_id = resp.json()["id"]
context.initial_payment_status = resp.json()["payment"]["status"]
assert context.initial_payment_status == "authorized"
@when("the warehouse rejects the order")
def step_reject_order(context):
resp = requests.post(
f"{BASE}/orders/{context.order_id}/reject",
json={"reason": "out_of_stock"},
)
assert resp.status_code == 200
context.order_status = resp.json()["status"]
@then('the order status is "rejected"')
def step_assert_order_rejected(context):
assert context.order_status == "rejected"
@then('the payment status remains "authorized"')
def step_assert_payment_not_captured(context):
resp = requests.get(f"{BASE}/orders/{context.order_id}/payment")
assert resp.status_code == 200
assert resp.json()["status"] == "authorized", (
f"Expected 'authorized' but got '{resp.json()['status']}' — "
"payment may have been captured on a rejected order"
)
That last assertion message matters. When this test fails in CI, you want the log to say exactly what went wrong — not just "AssertionError." Good failure messages on sequencing tests save a lot of debugging time. Speaking of which, pairing this with structured logging in your test output makes it much faster to trace which step in a multi-call workflow actually broke.
One pattern I reach for often: store intermediate response bodies on the Behave context object and assert on them in a dedicated Then step rather than silently swallowing them in a When. It keeps the assertion visible and makes the scenario readable as a specification of the expected sequence.
Designing Fixtures and Teardown So Sequencing Bugs Don't Hide Behind Dirty State
Here's a sequencing bug that test suites create for themselves: a test passes because it inherited state from a previous test that ran first. The order of test execution becomes a hidden dependency. Then someone runs the tests in a different order — or in parallel — and suddenly you have intermittent failures with no obvious cause.
The fix is to treat each sequencing test as owning its own state, from creation to cleanup. In pytest, that means using fixtures with explicit teardown rather than relying on module-level setup:
import pytest
import requests
BASE = "https://api.example.com"
@pytest.fixture
def fresh_cart(auth_headers):
"""Creates a cart and guarantees cleanup regardless of test outcome."""
resp = requests.post(f"{BASE}/carts", headers=auth_headers)
assert resp.status_code == 201
cart_id = resp.json()["id"]
yield cart_id # test runs here
# Teardown: always delete the cart after the test
requests.delete(f"{BASE}/carts/{cart_id}", headers=auth_headers)
def test_item_must_exist_before_quantity_update(auth_headers, fresh_cart):
cart_id = fresh_cart
# Try to update quantity on an item that was never added
resp = requests.patch(
f"{BASE}/carts/{cart_id}/items/WIDGET-42",
json={"qty": 5},
headers=auth_headers,
)
assert resp.status_code == 404, (
"Expected 404 when updating a non-existent item, "
f"got {resp.status_code} — possible order-of-operations gap"
)
The yield-based fixture pattern is important here: teardown runs even if the test fails, so you don't accumulate orphaned test data that could influence the next run. Dirty state is one of the most common reasons sequencing bugs become invisible in test suites — a resource that "shouldn't exist yet" already exists because a previous test left it behind.
For more complex workflows that span multiple resource types, I'll sometimes write a dedicated workflow_context fixture that creates every resource in the correct sequence and tears them all down in reverse. That way the sequence of setup is itself tested implicitly — if the fixture breaks, every test that depends on it fails immediately rather than silently skipping the precondition.
It's also worth thinking about where these sequencing tests run in your pipeline. They're integration-level tests by nature — they need a real (or realistic) API to call — so they belong later in the pipeline than unit tests, but they should still run on every PR. If you're still figuring out that placement, thinking through where API tests fit in your CI/CD stages is a good place to start. The short version: sequencing tests that hit a staging environment should gate merges, not just inform them.
Finally, keep an eye on tests that rely on full user journeys rather than individual endpoints — those tests naturally expose sequencing bugs because they model what a real user actually does, in the order they do it. Endpoint-by-endpoint testing will always miss the gaps between the steps. Journey-based tests fill exactly that gap.