Full example
This is full example on how to create a webhook endpoint, create a webhook request, get webhook requests, validate webhook request payload.
/* 1. Create new valid webhook endpoint */
interface Webhook {
id: string;
endpoint: string;
}
const webhook: Webhook = await fetch(`${BASE_URL}/webhooks/create`, {
method: "POST",
}).then((res) => res.json());
console.log("Webhook", webhook);
console.assert("id" in webhook && "endpoint" in webhook, "Invalid Webhook");
/* 2. Create new webhook request */
const payload = {
timestamp: Date.now(),
};
type WebhookResponse = { message: "success" } | { error: unknown };
const response: WebhookResponse = await fetch(webhook.endpoint, {
method: "POST",
body: JSON.stringify(payload),
}).then((res) => res.json());
console.log("WebhookResponse", response);
console.assert("message" in response, "Invalid WebhookResponse");
/* 3. Get webhook requests */
interface WebhookResponse {
accessType: "private" | "public";
resourceJwt: string;
receivedRequests: [
{
date: string;
path: string;
id: string;
method: string;
}
];
}
const webhookResponse: WebhookResponse = await fetch(`${BASE_URL}/webhooks/${webhook.id}/received`).then((res) =>
res.json()
);
const receivedRequests = webhookResponse.receivedRequests;
console.log("WebhookRequests", receivedRequests);
console.assert(Array.isArray(requests) && receivedRequests.length, "Invalid WebhookRequests");
/* 4. Validate webhook request payload */
interface PupulatedWebhookRequest {
request: {
resource: string;
path: string;
httpMethod: string;
headers: Record<string, string>;
multiValueHeaders: Record<string, string>;
queryStringParameters: any;
multiValueQueryStringParameters: any;
pathParameters: { id: string };
stageVariables: any;
requestContext: Record<string, unknown>;
body: string;
isBase64Encoded: boolean;
};
response: {
statusCode: number;
body: string;
headers: Record<string, string>;
};
}
const webhookRequest: PupulatedWebhookRequest = await fetch(
`${BASE_URL}/webhooks/${webhook.id}/${requests[0].id}`
).then((res) => res.json());
const request = webhookRequest.request;
console.log("PupulatedWebhookRequest", request);
console.assert("body" in request, "Invalid PupulatedWebhookRequest.");
const body: typeof payload = JSON.parse(request.body);
console.assert(
body.timestamp === payload.timestamp,
`Invalid request body. Expected "timestamp" to be "${payload.timestamp}"`
);