API TESTING

Testing Async APIs When There Is No Immediate Response

Most API testing tutorials assume a clean request and response: send, receive, assert. Async APIs break that. You submit a job, get a 202 Accepted and a job ID, and the real result shows up later through a status endpoint or a webhook. I've seen teams struggle with this pattern more than almost any other, because the instinct is to treat it like a sync endpoint, and the result is tests that are flaky or, worse, green when they shouldn't be.

The pattern is more common than ever because of agents. An endpoint that runs an LLM agent, say "research this ticket and draft a reply", takes seconds to minutes and calls several tools on the way, so it's almost always exposed as an async job. Testing it means everything below plus one more thing: the final state isn't just "completed," it's a result whose quality varies from run to run. And when a coding agent writes your async tests, its first move is usually time.sleep(5), which is exactly the habit this article is about removing.

I'll walk through polling with backoff and explicit terminal states, receiving webhooks in a test, structuring async tests so they hold up in CI, and how the same patterns extend to agent runs. Examples are Python and drop into pytest; the helpers work just as well under Behave steps.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Poll until a terminal state, with backoff

The common shape is POST /jobs returning 202 and a job ID, then GET /jobs/{id} reporting status. The test bridges the two with a polling helper. Three things make it reliable: a deadline instead of a fixed number of sleeps, a growing interval so you don't hammer a slow environment or trip a rate limit, and explicit handling of every terminal state.

import os
import time

import requests

ASYNC_TIMEOUT = float(os.getenv("ASYNC_TEST_TIMEOUT", "60"))
TERMINAL = {"completed", "failed", "cancelled"}


def poll_until_done(base_url: str, job_id: str, timeout: float = ASYNC_TIMEOUT) -> dict:
    interval = 0.5
    deadline = time.monotonic() + timeout
    last = None
    while time.monotonic() < deadline:
        response = requests.get(f"{base_url}/jobs/{job_id}", timeout=10)
        assert response.status_code == 200, f"status check failed: {response.status_code}"
        last = response.json()
        if last["status"] in TERMINAL:
            return last
        time.sleep(interval)
        interval = min(interval * 2, 8)
    raise AssertionError(f"job {job_id} not finished after {timeout}s; last state: {last}")


def submit_job(base_url: str, payload: dict) -> str:
    response = requests.post(f"{base_url}/jobs", json=payload, timeout=10)
    assert response.status_code == 202, f"expected 202, got {response.status_code}"
    return response.json()["job_id"]

The helper returns any terminal state rather than asserting "completed", so each test decides what it expects. That matters: a test that only handles completed and loops until timeout on failed turns a quick, clear failure into a slow, vague one. The timeout message includes the last state seen, which is usually the fastest route to a diagnosis. Timeouts come from an environment variable so CI can loosen them for a slower environment without code changes.

Once the job completes, validate the result payload: shape, required fields, types. Defining the schema once and validating against it beats a wall of individual assertions; validating API response schemas automatically covers that approach.

Receive webhooks inside the test

Some async APIs push instead: you register a callback URL and the service POSTs the result when it's done. Now your test has to receive a request. For local and contract testing, a tiny server from the standard library in a fixture is enough:

import json
import queue
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer

import pytest


@pytest.fixture
def callback_server():
    received = queue.Queue()

    class Handler(BaseHTTPRequestHandler):
        def do_POST(self):
            length = int(self.headers.get("Content-Length", 0))
            received.put({"headers": dict(self.headers),
                          "body": json.loads(self.rfile.read(length) or b"{}")})
            self.send_response(200)
            self.end_headers()

        def log_message(self, *args):
            pass

    server = HTTPServer(("127.0.0.1", 0), Handler)  # port 0 = pick a free port
    threading.Thread(target=server.serve_forever, daemon=True).start()
    url = f"http://127.0.0.1:{server.server_address[1]}/callback"
    yield url, received
    server.shutdown()
    server.server_close()


def test_export_job_posts_callback(base_url, callback_server):
    url, received = callback_server
    submit_job(base_url, {"task": "export", "callback_url": url})
    callback = received.get(timeout=ASYNC_TIMEOUT)  # raises queue.Empty on timeout
    assert callback["body"]["status"] == "completed"
    assert callback["body"]["job_id"]

A queue replaces the polling loop: get(timeout=...) blocks until the callback arrives or the deadline passes. Binding to port 0 avoids clashes when tests run in parallel. This only works when the service under test can reach your machine, so it suits a locally running service or one in the same CI network; for a remote environment you'd need a reachable receiver.

Don't stop at "the callback fired." The pushed payload is part of the contract, so validate it like any response. If the API signs webhooks, verify the signature and add a test that a tampered payload is rejected by your receiving code. And if callbacks can be delivered more than once, check that duplicates carry the same event ID so consumers can deduplicate. I cover that side in testing webhooks: a practical approach.

Structure async tests so CI stays calm

  • Separate acceptance from completion. "Returns 202 with a job ID" and "the finished job has a valid result" are different contracts. Separate tests make failures easier to read.
  • Share expensive jobs. If several tests need a completed job, submit it once in a module-scoped fixture and assert against the shared result.
  • Always test the failure path. Submit invalid input and assert the job reaches failed with a meaningful error. Async APIs that silently drop bad work are a common, quiet production bug.
  • Keep credentials out of the code. A multi-step flow may outlive a short-lived token, so fetch tokens through a fixture that can refresh them.
  • Ban fixed sleeps. time.sleep(10) followed by one status check is either slow or flaky, usually both.

That last rule is the one I write into agent instructions, because it's the shortcut assistants reach for first:

## Async endpoints
- Never use time.sleep() to wait for a job. Use poll_until_done() or the callback_server fixture.
- Assert the specific terminal state the test expects; failed jobs must surface their error message.
- Do not raise ASYNC_TEST_TIMEOUT to fix a failing test; report the last observed state instead.

When the async job is an agent run

If your API exposes an agent as a job, the same polling helper applies, but "completed" is only the start of the checks. I split them into two layers.

Deterministic checks on every run. The job reaches a terminal state within the timeout, the result matches its schema, and the run's recorded steps are sensible: which tools were called, in what order, and with what arguments. If your service stores a trace of tool calls, assert on it. For example, a "refund request" run must call lookup_order before issue_refund, must never call issue_refund twice, and must stop within a step limit. Point the service at a stub model with scripted responses and these become ordinary, repeatable pull request tests.

Quality checks over several runs. Against the real model, one run tells you little. Submit the same fixed set of inputs several times and report the pass rate for each check, such as "the reply references the correct order number", and compare it with the last baseline. A drop is a regression even if some individual runs still pass. These run nightly, not on every commit.

Agent runs also make the failure path more important. Test what happens when a tool times out mid-run: does the job end in failed with a useful error, or hang in running forever? A job stuck in a non-terminal state is the async bug users notice first.

Be explicit about time

Async API testing isn't fundamentally harder than sync testing. It asks you to be explicit about time, terminal states and the full shape of deferred results. Build the polling helper and callback receiver once, make timeouts configurable, and async tests become as dependable as the rest of the suite, whether the job is a CSV export or a multi-step agent. If you'd like to build these helpers into a full framework with Behave or Cucumber and GitHub Copilot, my API testing courses walk through it, and the API testing guide covers the fundamentals underneath.