Webhooks
A webhook is an HTTPS endpoint of yours that DisruptAPI calls when a signal matching your filters is created, escalates, changes or resolves. Each delivery is a signed JSON POST. This page covers events and payloads, signature verification, retries, deduplication and testing.
Create a webhook#
Send the URL and optional filters. You can also create webhooks in the console. Webhooks need a paid plan: Starter allows 3 active webhooks, Pro 20, Enterprise 100.
curl -X POST "https://app.disruptapi.com/v1/webhooks" \
-H "Authorization: Bearer $DISRUPT_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com/webhooks/disrupt",
"filters": {
"types": ["aviation", "weather"],
"min_severity": "severe",
"airports": ["SEA", "PDX"],
"events": ["created", "escalated", "resolved"]
}
}'// Node.js 18+ (built-in fetch), saved as an .mjs file
const res = await fetch("https://app.disruptapi.com/v1/webhooks", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DISRUPT_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
url: "https://example.com/webhooks/disrupt",
filters: {
types: ["aviation", "weather"],
min_severity: "severe",
airports: ["SEA", "PDX"],
events: ["created", "escalated", "resolved"],
},
}),
signal: AbortSignal.timeout(30_000),
});
const json = await res.json();
if (!res.ok) {
throw new Error(`${res.status} ${json.error.code}: ${json.error.message}`);
}
console.log(JSON.stringify(json.data, null, 2));import os
import requests
resp = requests.post(
"https://app.disruptapi.com/v1/webhooks",
headers={"Authorization": f"Bearer {os.environ['DISRUPT_KEY']}"},
json={
"url": "https://example.com/webhooks/disrupt",
"filters": {
"types": ["aviation", "weather"],
"min_severity": "severe",
"airports": ["SEA", "PDX"],
"events": ["created", "escalated", "resolved"],
},
},
timeout=30,
)
if not resp.ok:
err = resp.json()["error"]
raise SystemExit(f"{resp.status_code} {err['code']}: {err['message']}")
print(resp.json()["data"])import os
import httpx
with httpx.Client(
base_url="https://app.disruptapi.com",
headers={"Authorization": f"Bearer {os.environ['DISRUPT_KEY']}"},
timeout=30,
) as client:
resp = client.post(
"/v1/webhooks",
json={
"url": "https://example.com/webhooks/disrupt",
"filters": {
"types": ["aviation", "weather"],
"min_severity": "severe",
"airports": ["SEA", "PDX"],
"events": ["created", "escalated", "resolved"],
},
},
)
if resp.is_error:
err = resp.json()["error"]
raise SystemExit(f"{resp.status_code} {err['code']}: {err['message']}")
print(resp.json()["data"])package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
)
func main() {
body := []byte(`{
"url": "https://example.com/webhooks/disrupt",
"filters": {
"types": ["aviation", "weather"],
"min_severity": "severe",
"airports": ["SEA", "PDX"],
"events": ["created", "escalated", "resolved"]
}
}`)
req, err := http.NewRequest(http.MethodPost, "https://app.disruptapi.com/v1/webhooks", bytes.NewReader(body))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("DISRUPT_KEY"))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
out, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.StatusCode, string(out))
}require "json"
require "net/http"
require "uri"
uri = URI("https://app.disruptapi.com/v1/webhooks")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV.fetch("DISRUPT_KEY")}"
req["Content-Type"] = "application/json"
req.body = <<~JSON
{
"url": "https://example.com/webhooks/disrupt",
"filters": {
"types": ["aviation", "weather"],
"min_severity": "severe",
"airports": ["SEA", "PDX"],
"events": ["created", "escalated", "resolved"]
}
}
JSON
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
http.request(req)
end
json = JSON.parse(res.body)
abort "#{res.code} #{json["error"]["code"]}: #{json["error"]["message"]}" unless res.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(json["data"])<?php
$payload = <<<'JSON'
{
"url": "https://example.com/webhooks/disrupt",
"filters": {
"types": ["aviation", "weather"],
"min_severity": "severe",
"airports": ["SEA", "PDX"],
"events": ["created", "escalated", "resolved"]
}
}
JSON;
$ch = curl_init("https://app.disruptapi.com/v1/webhooks");
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("DISRUPT_KEY"),
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => $payload,
]);
$raw = curl_exec($ch);
if ($raw === false) {
exit("request failed: " . curl_error($ch) . PHP_EOL);
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
$json = json_decode($raw, true);
if ($status >= 400) {
exit("{$status} {$json['error']['code']}: {$json['error']['message']}" . PHP_EOL);
}
print_r($json["data"]);// Java 17+. Run with: java Main.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Main {
public static void main(String[] args) throws Exception {
String body = """
{
"url": "https://example.com/webhooks/disrupt",
"filters": {
"types": ["aviation", "weather"],
"min_severity": "severe",
"airports": ["SEA", "PDX"],
"events": ["created", "escalated", "resolved"]
}
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.disruptapi.com/v1/webhooks"))
.timeout(Duration.ofSeconds(30))
.header("Authorization", "Bearer " + System.getenv("DISRUPT_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}// .NET 7+ console app (top-level statements, C# 11 raw strings)
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("DISRUPT_KEY"));
var body = """
{
"url": "https://example.com/webhooks/disrupt",
"filters": {
"types": ["aviation", "weather"],
"min_severity": "severe",
"airports": ["SEA", "PDX"],
"events": ["created", "escalated", "resolved"]
}
}
""";
using var content = new StringContent(body, Encoding.UTF8, "application/json");
using var response = await http.PostAsync("https://app.disruptapi.com/v1/webhooks", content);
Console.WriteLine((int)response.StatusCode);
Console.WriteLine(await response.Content.ReadAsStringAsync());{
"data": {
"id": "whk_8d2c41f0a6b9e357",
"org_id": "org_5c1f0a9e2b7d4c31",
"url": "https://example.com/webhooks/disrupt",
"secret": "whsec_3b9f0c5e1a7d2846f0b3c9e1a5d7f2b4c6e8a0d1f3b5c7e9",
"filters": {
"airports": ["PDX", "SEA"],
"events": ["created", "escalated", "resolved"],
"min_severity": "severe",
"types": ["aviation", "weather"]
},
"created_at": "2026-11-18T08:05:40Z"
}
}URL rules#
httpsonly, on port 443 or 8443, at most 500 characters, with no user name or password in the URL.- The host must resolve only to public addresses. Private, loopback, link-local and carrier-grade NAT ranges are refused. This is checked when you create the webhook and again before every delivery.
- A refused URL returns
400 invalid_webhookwith the reason.
Filters#
All filters you set must match (AND). Inside a list, any value can match (OR). No filters means every signal change. Lists hold at most 500 entries; unknown filter keys are ignored.
| Filter | Type | Description |
|---|---|---|
types | string[] | Signal types, e.g. ["aviation", "weather"]. |
min_severity | string | minor, moderate, severe or extreme: only signals at or above it. |
countries | string[] | ISO alpha-2 codes; the signal must cover at least one. |
airports | string[] | IATA codes; the signal must list at least one. |
carriers | string[] | IATA airline codes. Matches IT outages that put one of these airlines at medium or high risk. Other signal types never match this filter. |
events | string[] | Any of created, escalated, updated, resolved. Default: all four. |
watchlists | string[] | ["*"] for all your watchlists, or watchlist ids. Only signals that touch an item on them fire, and the payload becomes an exposure.* event listing those items. |
With watchlists, item matching uses every severity, so min_severity on the webhook is what limits severity. For resolutions, items are matched against the signal's last known footprint, so you hear when a disruption that touched your items ends.
Which events are there?#
| Type | When |
|---|---|
signal.created | A new signal, or a resolved one that came back. |
signal.escalated | Severity went up, or more airports are affected. |
signal.updated | Another material change: severity down, title, countries, airports, end time, failure layer. |
signal.resolved | The source no longer lists it, or its end time passed. |
exposure.created, .escalated, .updated, .resolved | The same four events, for webhooks with a watchlists filter, when the signal touches at least one of your watched items. |
Changes that are not material (new wording in details, a different area list) do not fire. See the signal lifecycle.
What does a delivery contain?#
A POST with a UTF-8 JSON body: id (evt_ plus 16 hex characters), type, created_at and data. For signal.* events, data is the signal. For exposure.* events, data holds the signal and the exposed_items. IT outage signals include impact_forecast.
{
"id": "evt_5f1c9a0b2d7e4c83",
"type": "signal.escalated",
"created_at": "2026-11-18T07:21:15Z",
"data": {
"id": "faa_ground_stop_SEA.k3j9x2m1qa",
"type": "aviation",
"subtype": "ground_stop",
"provider": "faa",
"failure_layer": null,
"failure_layer_label": null,
"title": "Ground Stop Program at SEA: low ceilings",
"severity": "severe",
"status": "active",
"countries": ["US"],
"airports": ["SEA"],
"areas": [],
"location": { "lat": 47.449, "lon": -122.309 },
"starts_at": null,
"ends_at": null,
"first_seen_at": "2026-11-18T06:52:10Z",
"updated_at": "2026-11-18T07:20:41Z",
"version": 2,
"source": {
"url": "https://nasstatus.faa.gov/",
"attribution": "FAA NAS Status",
"last_checked_at": "2026-11-18T07:21:02Z",
"stale": false
},
"details": { "reason": "low ceilings", "End_Time": "8:30 am PST" }
}
}{
"id": "evt_a03d6e1f9b24c758",
"type": "exposure.created",
"created_at": "2026-11-18T09:15:02Z",
"data": {
"signal": {
"id": "sp_cloudflare_9x2kd81mzq3r.p2c7d0w5ha",
"type": "it_outage",
"subtype": "provider_incident",
"provider": "cloudflare",
"failure_layer": "edge_cdn_dns",
"failure_layer_label": "Edge, CDN and DNS",
"title": "Elevated errors for requests through our network",
"severity": "severe",
"status": "active",
"countries": [],
"airports": [],
"areas": [],
"location": null,
"starts_at": "2026-11-18T09:12:00Z",
"ends_at": null,
"first_seen_at": "2026-11-18T09:14:33Z",
"updated_at": "2026-11-18T09:40:05Z",
"version": 1,
"source": {
"url": "https://stspg.io/example",
"attribution": "Cloudflare status page",
"last_checked_at": "2026-11-18T09:41:00Z",
"stale": false
},
"details": {
"components": ["CDN/Cache", "DNS"],
"provider_status": "identified"
},
"impact_forecast": {
"basis": "analogs",
"outcomes": ["..."],
"recommended_actions": ["..."]
}
},
"exposed_items": [
{
"item_id": "checkout-cdn",
"kind": "provider",
"watchlist_id": "wl_3f9a1c2b7d4e5f60",
"reasons": ["you depend on cloudflare, which reports this incident"],
"risk_contribution": "severe"
}
]
}
}| Header | Value |
|---|---|
Content-Type | application/json |
Disrupt-Signature | t=<unix seconds>,v1=<hex HMAC-SHA256>. See verification. |
Disrupt-Webhook-Id | The webhook's id, whk_.... Useful when several webhooks point at one URL. |
User-Agent | DisruptAPI-Webhooks/1.0 |
How do I verify the signature?#
Every delivery is signed with your webhook's secret. Verify before you parse or act on the body.
- Read the
Disrupt-Signatureheader and split it on commas intot(Unix seconds) andv1(lowercase hex). - Reject the request if
tis more than 5 minutes from your clock. This stops replays of old deliveries. - Compute HMAC-SHA256 with the whole secret, including the
whsec_prefix, as the key, over the bytest, then., then the raw request body. - Compare your hex digest with
v1in constant time.
// Node.js 18+ with Express 4 or 5. npm install express
import crypto from "node:crypto";
import express from "express";
const SECRET = process.env.DISRUPT_WEBHOOK_SECRET; // whsec_..., shown once when the webhook was created
export function verifyDisruptSignature(secret, rawBody, header, toleranceSec = 300) {
if (!header) return false;
let t, v1;
for (const part of header.split(",")) {
const i = part.indexOf("=");
if (i < 0) return false;
const key = part.slice(0, i).trim();
const value = part.slice(i + 1).trim();
if (key === "t") t = value;
if (key === "v1") v1 = value;
}
const ts = Number.parseInt(t ?? "", 10);
if (!Number.isSafeInteger(ts) || !v1) return false;
if (Math.abs(Math.floor(Date.now() / 1000) - ts) > toleranceSec) return false;
// Signed content: "<t>." followed by the raw request body, exactly as received.
const expected = crypto.createHmac("sha256", secret).update(`${ts}.`).update(rawBody).digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(v1);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
const app = express();
// express.raw keeps the body as a Buffer. Do not parse JSON before verifying.
app.post("/webhooks/disrupt", express.raw({ type: "application/json" }), (req, res) => {
if (!verifyDisruptSignature(SECRET, req.body, req.get("Disrupt-Signature"))) {
return res.status(400).send("bad signature");
}
const event = JSON.parse(req.body.toString("utf8"));
res.status(204).end(); // answer fast, then do the work
console.log(event.type, event.data.signal?.id ?? event.data.id);
});
app.listen(3000);// Node.js 18+, framework-free. Works with any server that gives you the raw body.
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
export function verifyDisruptSignature(
secret: string,
rawBody: Buffer,
header: string | undefined,
toleranceSec = 300,
): boolean {
if (!header) return false;
const parts = new Map<string, string>();
for (const part of header.split(",")) {
const i = part.indexOf("=");
if (i < 0) return false;
parts.set(part.slice(0, i).trim(), part.slice(i + 1).trim());
}
const ts = Number.parseInt(parts.get("t") ?? "", 10);
const v1 = parts.get("v1");
if (!Number.isSafeInteger(ts) || !v1) return false;
if (Math.abs(Math.floor(Date.now() / 1000) - ts) > toleranceSec) return false;
const expected = createHmac("sha256", secret).update(`${ts}.`).update(rawBody).digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(v1);
return a.length === b.length && timingSafeEqual(a, b);
}
const secret = process.env.DISRUPT_WEBHOOK_SECRET ?? "";
createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
req.on("end", () => {
const body = Buffer.concat(chunks);
const header = req.headers["disrupt-signature"];
if (!verifyDisruptSignature(secret, body, Array.isArray(header) ? header[0] : header)) {
res.writeHead(400).end("bad signature");
return;
}
res.writeHead(204).end();
const event = JSON.parse(body.toString("utf8"));
console.log(event.type);
});
}).listen(3000);# Python 3.9+. Flask is only for the example route: pip install flask
import hashlib
import hmac
import json
import os
import time
from flask import Flask, request
SECRET = os.environ["DISRUPT_WEBHOOK_SECRET"] # whsec_...
def verify_disrupt_signature(secret: str, raw_body: bytes, header: str, tolerance_s: int = 300) -> bool:
try:
parts = dict(p.strip().split("=", 1) for p in header.split(","))
ts = int(parts["t"])
received = parts["v1"]
except (ValueError, KeyError, AttributeError):
return False
if abs(time.time() - ts) > tolerance_s:
return False
expected = hmac.new(secret.encode(), f"{ts}.".encode() + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received)
app = Flask(__name__)
@app.post("/webhooks/disrupt")
def disrupt_webhook():
raw = request.get_data() # the raw bytes; do not use request.json before verifying
if not verify_disrupt_signature(SECRET, raw, request.headers.get("Disrupt-Signature", "")):
return "bad signature", 400
event = json.loads(raw)
print(event["type"])
return "", 204package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
// VerifyDisruptSignature checks a Disrupt-Signature header (t=<unix>,v1=<hex>).
func VerifyDisruptSignature(secret string, body []byte, header string, tolerance time.Duration) bool {
var ts, sig string
for _, part := range strings.Split(header, ",") {
k, v, ok := strings.Cut(strings.TrimSpace(part), "=")
if !ok {
return false
}
switch k {
case "t":
ts = v
case "v1":
sig = v
}
}
t, err := strconv.ParseInt(ts, 10, 64)
if err != nil || sig == "" {
return false
}
age := time.Since(time.Unix(t, 0))
if age > tolerance || age < -tolerance {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(strconv.FormatInt(t, 10) + "."))
mac.Write(body)
expected := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(expected), []byte(sig))
}
func main() {
secret := os.Getenv("DISRUPT_WEBHOOK_SECRET")
http.HandleFunc("/webhooks/disrupt", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, 5<<20))
if err != nil {
http.Error(w, "read error", http.StatusBadRequest)
return
}
if !VerifyDisruptSignature(secret, body, r.Header.Get("Disrupt-Signature"), 5*time.Minute) {
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
var event struct {
ID string `json:"id"`
Type string `json:"type"`
}
if err := json.Unmarshal(body, &event); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusNoContent)
log.Println(event.Type, event.ID)
})
log.Fatal(http.ListenAndServe(":3000", nil))
}# Ruby 2.6+. Sinatra is only for the example route: gem install sinatra
require "json"
require "openssl"
require "sinatra"
SECRET = ENV.fetch("DISRUPT_WEBHOOK_SECRET")
def verify_disrupt_signature(secret, raw_body, header, tolerance: 300)
return false if header.nil? || header.empty?
pairs = header.split(",").map { |p| p.strip.split("=", 2) }
return false unless pairs.all? { |p| p.size == 2 }
parts = pairs.to_h
ts = Integer(parts["t"].to_s, 10, exception: false)
sig = parts["v1"]
return false if ts.nil? || sig.nil?
return false if (Time.now.to_i - ts).abs > tolerance
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{ts}.".b + raw_body.b)
secure_compare(expected, sig)
end
# Constant-time comparison (Rack::Utils.secure_compare does the same if you use Rack).
def secure_compare(a, b)
return false unless a.bytesize == b.bytesize
diff = 0
a.bytes.zip(b.bytes) { |x, y| diff |= x ^ y }
diff.zero?
end
post "/webhooks/disrupt" do
raw = request.body.read
halt 400, "bad signature" unless verify_disrupt_signature(SECRET, raw, request.env["HTTP_DISRUPT_SIGNATURE"])
event = JSON.parse(raw)
logger.info(event["type"])
status 204
end<?php
// PHP 7.4+. Plain PHP endpoint, e.g. public/webhooks/disrupt.php
function verify_disrupt_signature(string $secret, string $rawBody, string $header, int $tolerance = 300): bool
{
$parts = [];
foreach (explode(',', $header) as $part) {
$kv = explode('=', trim($part), 2);
if (count($kv) !== 2) {
return false;
}
$parts[$kv[0]] = $kv[1];
}
if (!isset($parts['t'], $parts['v1']) || !ctype_digit($parts['t'])) {
return false;
}
$ts = (int) $parts['t'];
if (abs(time() - $ts) > $tolerance) {
return false;
}
$expected = hash_hmac('sha256', $ts . '.' . $rawBody, $secret);
return hash_equals($expected, $parts['v1']);
}
$secret = getenv('DISRUPT_WEBHOOK_SECRET');
$raw = file_get_contents('php://input'); // raw body; do not re-encode it
$header = $_SERVER['HTTP_DISRUPT_SIGNATURE'] ?? '';
if (!verify_disrupt_signature($secret, $raw, $header)) {
http_response_code(400);
exit('bad signature');
}
$event = json_decode($raw, true);
http_response_code(204);
error_log($event['type']);// Java 17+. Run with: java DisruptWebhook.java
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class DisruptWebhook {
public static boolean verify(String secret, byte[] rawBody, String header, long toleranceSeconds) {
if (header == null || header.isEmpty()) return false;
String t = null, v1 = null;
for (String part : header.split(",")) {
String[] kv = part.trim().split("=", 2);
if (kv.length != 2) return false;
if (kv[0].equals("t")) t = kv[1];
else if (kv[0].equals("v1")) v1 = kv[1];
}
if (t == null || v1 == null) return false;
long ts;
try {
ts = Long.parseLong(t);
} catch (NumberFormatException e) {
return false;
}
if (Math.abs(System.currentTimeMillis() / 1000 - ts) > toleranceSeconds) return false;
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
mac.update((ts + ".").getBytes(StandardCharsets.UTF_8));
String expected = HexFormat.of().formatHex(mac.doFinal(rawBody));
return MessageDigest.isEqual(
expected.getBytes(StandardCharsets.UTF_8), v1.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) throws IOException {
String secret = System.getenv("DISRUPT_WEBHOOK_SECRET");
HttpServer server = HttpServer.create(new InetSocketAddress(3000), 0);
server.createContext("/webhooks/disrupt", exchange -> {
byte[] body = exchange.getRequestBody().readAllBytes();
String header = exchange.getRequestHeaders().getFirst("Disrupt-Signature");
boolean ok = verify(secret, body, header, 300);
exchange.sendResponseHeaders(ok ? 204 : 400, -1);
exchange.close();
if (ok) System.out.println(new String(body, StandardCharsets.UTF_8));
});
server.start();
}
}// ASP.NET Core minimal API, .NET 7+ (dotnet new web)
using System.Security.Cryptography;
using System.Text;
var app = WebApplication.CreateBuilder(args).Build();
var secret = Environment.GetEnvironmentVariable("DISRUPT_WEBHOOK_SECRET") ?? "";
app.MapPost("/webhooks/disrupt", async (HttpRequest request) =>
{
using var buffer = new MemoryStream();
await request.Body.CopyToAsync(buffer);
var body = buffer.ToArray(); // raw bytes, before any JSON parsing
var header = request.Headers["Disrupt-Signature"].ToString();
if (!DisruptSignature.Verify(secret, body, header)) return Results.BadRequest("bad signature");
Console.WriteLine(Encoding.UTF8.GetString(body));
return Results.NoContent();
});
app.Run();
static class DisruptSignature
{
public static bool Verify(string secret, byte[] rawBody, string header, long toleranceSeconds = 300)
{
if (string.IsNullOrEmpty(header)) return false;
string? t = null, v1 = null;
foreach (var part in header.Split(','))
{
var kv = part.Trim().Split('=', 2);
if (kv.Length != 2) return false;
if (kv[0] == "t") t = kv[1];
else if (kv[0] == "v1") v1 = kv[1];
}
if (t is null || v1 is null || !long.TryParse(t, out var ts)) return false;
if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - ts) > toleranceSeconds) return false;
var prefix = Encoding.UTF8.GetBytes($"{ts}.");
var signed = new byte[prefix.Length + rawBody.Length];
prefix.CopyTo(signed, 0);
rawBody.CopyTo(signed, prefix.Length);
var mac = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), signed);
var expected = Encoding.UTF8.GetBytes(Convert.ToHexString(mac).ToLowerInvariant());
return CryptographicOperations.FixedTimeEquals(expected, Encoding.UTF8.GetBytes(v1));
}
}Retries and disabling#
A delivery succeeds when your endpoint answers with any 2xx status within 10 seconds. Redirects are not followed and count as failures, as do timeouts, connection errors and other statuses. Only the first 64 KB of your reply is read.
| Attempt | Sent |
|---|---|
| 1 | When the change is detected |
| 2 | 1 minute after attempt 1 fails |
| 3 | 5 minutes after attempt 2 |
| 4 | 30 minutes after attempt 3 |
| 5 | 2 hours after attempt 4 |
| 6 | 6 hours after attempt 5; if it fails, the delivery is marked failed and not retried |
Deliveries are sent by a background loop, so times are approximate. A webhook whose deliveries fail 50 times in a row, counting every attempt, is disabled; any success resets the count. A disabled webhook gets no more deliveries, shows disabled_at in GET /v1/webhooks and no longer counts against your plan. There is no re-enable call: fix the endpoint and create a new webhook.
Idempotency and ordering#
Plan for duplicates and for deliveries arriving out of order:
- Do not deduplicate on the event
id. The payload is built when each attempt is sent, so a retry carries a newid, a newcreated_atand a new signature. - The payload holds the signal as it is when the attempt is sent, which can be newer than the change that queued it. A retried
signal.escalatedcan arrive with a laterversion. - Deduplicate on the signal id and version. Keep the highest
versionyou have processed for each signal id and ignore payloads at or below it. Each webhook gets at most one delivery per signal version. - Order is not guaranteed across signals or across retries. Use
version(orupdated_at) to decide which state is newest.
// Keep the highest version you have processed per signal. Ignore anything older or equal.
async function handle(event, store) {
const signal = event.type.startsWith("exposure.") ? event.data.signal : event.data;
const seen = await store.getVersion(signal.id); // null if never seen
if (seen !== null && signal.version <= seen) return; // duplicate or out of order
await store.saveSignal(signal); // upsert by signal.id
await store.setVersion(signal.id, signal.version);
if (event.type.startsWith("exposure.")) await notifyOwners(event.data.exposed_items, signal);
}Answer quickly. Return 2xx as soon as the signature checks out, and do slow work (emails, rebooking logic) in a queue. A handler that takes longer than 10 seconds is treated as failed and the delivery is retried.
How do I test webhooks locally?#
DisruptAPI only delivers to public HTTPS addresses, so localhost cannot be registered directly. There is no endpoint that sends a test event. Two ways to test:
- Unit-test your handler with a signed sample. Sign a body yourself with your secret and post it to your local server. If your code accepts this, it accepts real deliveries.
- End to end through a tunnel. Run an HTTPS tunnel that gives your local port a public address on port 443, register that URL as a webhook (with broad filters, for example
{"min_severity": "minor"}), and wait for the next signal change. Delete the webhook afterwards.
# Send a correctly signed test event to your local handler.
SECRET="whsec_your_test_secret"
BODY='{"id":"evt_test0000000001","type":"signal.created","created_at":"2026-11-18T08:00:00Z","data":{"id":"test.signal","version":1}}'
T=$(date +%s)
SIG=$(printf '%s.%s' "$T" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //')
curl -i http://localhost:3000/webhooks/disrupt \
-H "Content-Type: application/json" \
-H "Disrupt-Signature: t=$T,v1=$SIG" \
--data-raw "$BODY"List and delete webhooks#
curl "https://app.disruptapi.com/v1/webhooks" \
-H "Authorization: Bearer $DISRUPT_KEY"// Node.js 18+ (built-in fetch), saved as an .mjs file
const res = await fetch("https://app.disruptapi.com/v1/webhooks", {
method: "GET",
headers: {
Authorization: `Bearer ${process.env.DISRUPT_KEY}`,
},
signal: AbortSignal.timeout(30_000),
});
const json = await res.json();
if (!res.ok) {
throw new Error(`${res.status} ${json.error.code}: ${json.error.message}`);
}
console.log(JSON.stringify(json.data, null, 2));import os
import requests
resp = requests.get(
"https://app.disruptapi.com/v1/webhooks",
headers={"Authorization": f"Bearer {os.environ['DISRUPT_KEY']}"},
timeout=30,
)
if not resp.ok:
err = resp.json()["error"]
raise SystemExit(f"{resp.status_code} {err['code']}: {err['message']}")
print(resp.json()["data"])import os
import httpx
with httpx.Client(
base_url="https://app.disruptapi.com",
headers={"Authorization": f"Bearer {os.environ['DISRUPT_KEY']}"},
timeout=30,
) as client:
resp = client.get("/v1/webhooks")
if resp.is_error:
err = resp.json()["error"]
raise SystemExit(f"{resp.status_code} {err['code']}: {err['message']}")
print(resp.json()["data"])package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"time"
)
func main() {
req, err := http.NewRequest(http.MethodGet, "https://app.disruptapi.com/v1/webhooks", nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("DISRUPT_KEY"))
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
out, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.StatusCode, string(out))
}require "json"
require "net/http"
require "uri"
uri = URI("https://app.disruptapi.com/v1/webhooks")
req = Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{ENV.fetch("DISRUPT_KEY")}"
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
http.request(req)
end
json = JSON.parse(res.body)
abort "#{res.code} #{json["error"]["code"]}: #{json["error"]["message"]}" unless res.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(json["data"])<?php
$ch = curl_init("https://app.disruptapi.com/v1/webhooks");
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("DISRUPT_KEY"),
],
]);
$raw = curl_exec($ch);
if ($raw === false) {
exit("request failed: " . curl_error($ch) . PHP_EOL);
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
$json = json_decode($raw, true);
if ($status >= 400) {
exit("{$status} {$json['error']['code']}: {$json['error']['message']}" . PHP_EOL);
}
print_r($json["data"]);// Java 17+. Run with: java Main.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Main {
public static void main(String[] args) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.disruptapi.com/v1/webhooks"))
.timeout(Duration.ofSeconds(30))
.header("Authorization", "Bearer " + System.getenv("DISRUPT_KEY"))
.GET()
.build();
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}// .NET 7+ console app (top-level statements, C# 11 raw strings)
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("DISRUPT_KEY"));
using var response = await http.GetAsync("https://app.disruptapi.com/v1/webhooks");
Console.WriteLine((int)response.StatusCode);
Console.WriteLine(await response.Content.ReadAsStringAsync());The list includes disabled webhooks with their disabled_at time and failures count. Deleting a webhook disables it at once; pending deliveries are not sent.
curl -X DELETE "https://app.disruptapi.com/v1/webhooks/whk_8d2c41f0a6b9e357" \
-H "Authorization: Bearer $DISRUPT_KEY"// Node.js 18+ (built-in fetch), saved as an .mjs file
const res = await fetch("https://app.disruptapi.com/v1/webhooks/whk_8d2c41f0a6b9e357", {
method: "DELETE",
headers: {
Authorization: `Bearer ${process.env.DISRUPT_KEY}`,
},
signal: AbortSignal.timeout(30_000),
});
const json = await res.json();
if (!res.ok) {
throw new Error(`${res.status} ${json.error.code}: ${json.error.message}`);
}
console.log(JSON.stringify(json.data, null, 2));import os
import requests
resp = requests.delete(
"https://app.disruptapi.com/v1/webhooks/whk_8d2c41f0a6b9e357",
headers={"Authorization": f"Bearer {os.environ['DISRUPT_KEY']}"},
timeout=30,
)
if not resp.ok:
err = resp.json()["error"]
raise SystemExit(f"{resp.status_code} {err['code']}: {err['message']}")
print(resp.json()["data"])import os
import httpx
with httpx.Client(
base_url="https://app.disruptapi.com",
headers={"Authorization": f"Bearer {os.environ['DISRUPT_KEY']}"},
timeout=30,
) as client:
resp = client.delete("/v1/webhooks/whk_8d2c41f0a6b9e357")
if resp.is_error:
err = resp.json()["error"]
raise SystemExit(f"{resp.status_code} {err['code']}: {err['message']}")
print(resp.json()["data"])package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"time"
)
func main() {
req, err := http.NewRequest(http.MethodDelete, "https://app.disruptapi.com/v1/webhooks/whk_8d2c41f0a6b9e357", nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("DISRUPT_KEY"))
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
out, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.StatusCode, string(out))
}require "json"
require "net/http"
require "uri"
uri = URI("https://app.disruptapi.com/v1/webhooks/whk_8d2c41f0a6b9e357")
req = Net::HTTP::Delete.new(uri)
req["Authorization"] = "Bearer #{ENV.fetch("DISRUPT_KEY")}"
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
http.request(req)
end
json = JSON.parse(res.body)
abort "#{res.code} #{json["error"]["code"]}: #{json["error"]["message"]}" unless res.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(json["data"])<?php
$ch = curl_init("https://app.disruptapi.com/v1/webhooks/whk_8d2c41f0a6b9e357");
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => "DELETE",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("DISRUPT_KEY"),
],
]);
$raw = curl_exec($ch);
if ($raw === false) {
exit("request failed: " . curl_error($ch) . PHP_EOL);
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
$json = json_decode($raw, true);
if ($status >= 400) {
exit("{$status} {$json['error']['code']}: {$json['error']['message']}" . PHP_EOL);
}
print_r($json["data"]);// Java 17+. Run with: java Main.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Main {
public static void main(String[] args) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.disruptapi.com/v1/webhooks/whk_8d2c41f0a6b9e357"))
.timeout(Duration.ofSeconds(30))
.header("Authorization", "Bearer " + System.getenv("DISRUPT_KEY"))
.DELETE()
.build();
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}// .NET 7+ console app (top-level statements, C# 11 raw strings)
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("DISRUPT_KEY"));
using var response = await http.DeleteAsync("https://app.disruptapi.com/v1/webhooks/whk_8d2c41f0a6b9e357");
Console.WriteLine((int)response.StatusCode);
Console.WriteLine(await response.Content.ReadAsStringAsync());Last updated 2026-11-18. Questions or a mistake on this page? Contact us.