API TESTING

Testing Webhooks: A Practical Approach for the Agent Era

Webhooks flip the usual API testing model. With a REST endpoint you send the request and inspect the response, so the control flow is yours. With a webhook, another service decides when to push a payload to you, and your job is to receive it, verify it and handle it correctly every time, including the second and third time it arrives. I've seen suites that cover REST endpoints thoroughly and have no automated tests at all for the webhooks the same services fire.

Webhooks now matter in agentic systems as well. They're a common way to start agent work: an issue is opened, a payment fails, a deploy finishes, and a webhook kicks off an agent to triage or respond. That makes the payload untrusted input travelling toward a model, which is a different risk from a bad database write. Coding agents also write a lot of webhook handlers now, and the parts they most often get wrong are the parts that matter: signature checks and duplicate delivery.

This article covers how I test the receiving side, the sending side, and the boundary between a webhook and an agent, in Python and pytest.

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

Make the handler testable without a server

The biggest improvement to webhook testing is structural. If the logic lives inside a framework route, every test needs a running app. I keep the decision-making in a plain function that takes the raw body and headers and returns a status code. The route just calls it.

import hashlib
import hmac
import json

SECRET = b"test-secret"


def sign(body: bytes, secret: bytes = SECRET) -> str:
    return "sha256=" + hmac.new(secret, body, hashlib.sha256).hexdigest()


def handle_webhook(body: bytes, headers: dict, store, secret: bytes = SECRET) -> int:
    expected = sign(body, secret).encode()
    received = headers.get("X-Signature-256", "").encode()
    if not hmac.compare_digest(expected, received):
        return 401
    try:
        event = json.loads(body)
    except ValueError:
        return 400
    if not isinstance(event, dict) or not {"event_id", "type", "data"} <= event.keys():
        return 400
    if not store.seen(event["event_id"]):
        store.enqueue(event)
    return 200

Three details matter. The signature is computed over the raw bytes, before any JSON parsing, because re-serialising changes the bytes. The comparison uses hmac.compare_digest, not ==. And the handler only enqueues the event. Heavy work happens elsewhere, so the sender gets a fast response. Header names and signature formats vary by provider, so check your provider's documentation and match it exactly.

Test signatures, including the rejections

The happy path proves almost nothing on its own. The tests that protect you are the ones where the request should be refused:

import pytest


class FakeStore:
    def __init__(self):
        self.queued = []

    def seen(self, event_id):
        return any(e["event_id"] == event_id for e in self.queued)

    def enqueue(self, event):
        self.queued.append(event)


BODY = json.dumps({"event_id": "evt_1", "type": "order.created",
                   "data": {"order_id": "ord_1"}}).encode()


def test_valid_signature_is_accepted():
    store = FakeStore()
    assert handle_webhook(BODY, {"X-Signature-256": sign(BODY)}, store) == 200
    assert len(store.queued) == 1


@pytest.mark.parametrize("body, headers", [
    (BODY + b" ", {"X-Signature-256": sign(BODY)}),           # tampered body
    (BODY, {"X-Signature-256": sign(BODY, b"wrong-secret")}),  # wrong secret
    (BODY, {}),                                                # header missing
])
def test_bad_signatures_are_rejected(body, headers):
    store = FakeStore()
    assert handle_webhook(body, headers, store) == 401
    assert store.queued == []

Notice the second assertion in each: a rejected request must not have side effects. Then do the same for malformed JSON and missing required fields, which should return 400 once the signature is valid. I validate the event shape with the same schema approach I use for responses, described in validating API response schemas automatically.

Duplicates, retries and ordering

Webhook producers retry when you're slow or return a 5xx, and many document at-least-once delivery. So the same event will arrive twice, and the handler has to be idempotent:

def test_duplicate_delivery_is_processed_once():
    store = FakeStore()
    headers = {"X-Signature-256": sign(BODY)}
    assert handle_webhook(BODY, headers, store) == 200
    assert handle_webhook(BODY, headers, store) == 200
    assert len(store.queued) == 1

Returning 200 for the duplicate is deliberate. You accepted the event the first time, so telling the sender it failed would only trigger more retries. The status code is a contract: 2xx means "accepted, stop", 4xx generally means "this will never succeed", and 5xx means "try again later". Test that an unexpected exception in your handler doesn't turn a bad payload into an endless retry loop. For the deeper side of duplicate handling, see testing idempotency in APIs that handle payments or orders.

Ordering is the other trap. A payment.refunded can arrive before the payment.completed it depends on. Whatever your design does (defer, reorder by sequence number, or re-fetch the current state from the API), write the test that sends events in the wrong order and asserts the final state.

Test your outbound webhooks with a local receiver

If your service sends webhooks, you need a real URL to send to. An in-process server on a random port covers this without tunnels or third-party tools:

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


class Capture(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        self.server.received.put({"headers": dict(self.headers),
                                  "body": self.rfile.read(length)})
        self.send_response(204)
        self.end_headers()

    def log_message(self, format, *args):
        pass


@pytest.fixture
def receiver():
    server = HTTPServer(("127.0.0.1", 0), Capture)
    server.received = queue.Queue()
    threading.Thread(target=server.serve_forever, daemon=True).start()
    yield f"http://127.0.0.1:{server.server_address[1]}", server.received
    server.shutdown()
    server.server_close()


def test_outbound_event_is_signed(receiver):
    url, received = receiver
    send_order_event(url, {"event_id": "evt_9", "type": "order.shipped", "data": {}})
    got = received.get(timeout=3)
    assert got["headers"]["X-Signature-256"] == sign(got["body"])

send_order_event is your own sender code. Extend the capture handler to return 500 on the first call and you can test your retry and backoff behaviour too. Delivery is asynchronous by nature, so the waiting patterns in testing async APIs when there is no immediate response apply here as well.

When a webhook starts an agent

When a webhook triggers an AI agent, the payload's text fields (an issue body, a customer message, a commit description) are written by someone you don't control, and they're about to reach a model. Testing can't make prompt injection impossible. What it can do is pin down the plumbing that limits the damage:

  • Only verified events reach the agent. The signature tests above become a security boundary. Add one asserting that a 401 path never calls the agent.
  • Untrusted text stays in a data field. The code that builds the agent's input should place payload text in a clearly delimited content field, never into the instructions. Test it with a payload containing "ignore previous instructions" and assert the instructions are byte-for-byte unchanged.
  • Webhook-triggered runs get fewer tools. If the agent can comment on an issue, it probably shouldn't be able to merge or deploy from that same run. Assert the tool list for that entry point.

The same lens helps when an agent writes your handler. When I review generated webhook code, I check three things first: is the signature computed over raw bytes, is the comparison constant-time, and is there a duplicate check. Those are the omissions I see most often, and the tests above catch all three.

Webhooks aren't a special case outside your normal strategy. They're HTTP endpoints with the direction reversed. Model the sender, test the rejections, prove idempotency, and treat the payload as untrusted wherever it goes next. If you want to practise this kind of API testing with Copilot alongside, my API testing courses cover it step by step.