Event Callbacks
Overview and use cases
Webhooks The service pushes domain events within a project (such as database table/row create, update, and delete operations, storage bucket file uploads, user registration and session login, team changes, function deployment and execution, etc.) in real time to the callback endpoint of an external business system via asynchronous HTTP POST requests. It is independent of the platform's internal Function event triggers and is suitable for integrating with enterprise internal support ticket centers, audit archival services, CRM/ERP systems, or billing reconciliation pipelines.
In enterprise intelligent customer service and knowledge platforms (such as the demo project enterprise-ai-hub-210), when a new support ticket is created in the enterprise_biz_db.customer_tickets table (e.g., TK-20261022-001) or its status is updated, the platform can deliver the event payload, along with the HMAC signature header (X-Appwrite-Webhook-Signature), to the enterprise's internal alerting gateway via the configured Webhook.
Prerequisites
Client initialization and authentication:
Available only on the server side and Console side: requires the Server SDK
Client(setEndpoint,setProject,setKey; the API Key must have thewebhooks.readandwebhooks.writescopes) or the Console SDK (Console Session / short-lived JWT).Not available in the Client / Web SDK: the browser side has no permission to manage project-level Webhooks.
Network requirements for the callback endpoint: the target
urlmust be a publicly reachable or instance-network-reachable HTTP/HTTPS address (subject to the 2.6.0+ SSRF protection constraints, which reject loopback addresses127.0.0.1, private network segments, and cloud provider metadata addresses), and it should return an2xxstatus code within a few seconds.
Usage workflow
Initialize the client and the
Webhooksservice: load theAPPBASE_ENDPOINT,APPBASE_PROJECT_ID, and anAPPBASE_API_KEYwith thewebhooks.writescope.Create a Webhook (
webhooks.create): specify a unique identifierwebhookId, namename, callback URLurl, array of listened event patternsevents(up to 100 entries, e.g.,databases.*.tables.*.rows.create), enabled statusenabled: true, TLS certificate validationsecurity: true, and optional HTTP Basic Auth credentials (httpUser/httpPass).Save the signing key and verify signatures: read the
signatureKeyfrom the creation or detail response, and in the receiving HTTP service compare the HMAC-SHA1 signature of the raw request body combined with theX-Appwrite-Webhook-Signaturerequest header to reject forged requests.Routine inspection and key rotation (
list/get/update/updateSignature/delete): usegetto check the delivery failure countattemptsand recent error logslogs; periodically, or when a leak is suspected, callupdateSignatureto atomically rotate thesignatureKey.
Key parameters and returns
Complete Method List and Parameter Matrix
| SDK Method (Node / Java) | Python Method | Go Method | REST Endpoint | Required Parameters | Optional Parameters | Return Model |
|---|---|---|---|---|---|---|
create({ webhookId, url, name, events, ... }) | create(...) | Create(...) | POST /v1/webhooks | webhookId, url, name (≤128 characters), events (1–100 event strings) | enabled (default true), security (default true, validates the remote TLS certificate), httpUser, httpPass | Webhook |
list({ queries, total }) (both queries and total are optional) | list(...) | List(...) | GET /v1/webhooks | None | queries (pagination/filtering), total (default true) | WebhookList |
get({ webhookId }) | get(...) | Get(...) | GET /v1/webhooks/{webhookId} | webhookId | None | Webhook |
update({ webhookId, name, url, events, ... }) | update(...) | Update(...) | PUT /v1/webhooks/{webhookId} | webhookId、name、url、events | enabled、security、httpUser、httpPass | Webhook |
updateSignature({ webhookId }) | update_signature(...) | UpdateSignature(...) | PATCH /v1/webhooks/{webhookId}/signature | webhookId | None | Webhook (including the new signatureKey) |
delete({ webhookId }) | delete(...) | Delete(...) | DELETE /v1/webhooks/{webhookId} | webhookId | None | Empty (204) |
Webhook Return model fields and callback request headers
| Category | Field / Header | Type | Description |
|---|---|---|---|
Return model Webhook | $id / name / url | string | Webhook ID, name, and target callback URL. |
Return model Webhook | events | string[] | List of subscribed platform event wildcards (e.g., ["databases.enterprise_biz_db.tables.customer_tickets.rows.*"]). |
Return model Webhook | security / enabled | boolean | Whether to verify certificates (true enforce certificate validity) and whether delivery is enabled. |
Return model Webhook | signatureKey | string | Platform-generated signing key, used to verify the callback request header X-Appwrite-Webhook-Signature. |
Return model Webhook | attempts / logs | integer / string | Number of consecutive delivery failures and the response diagnostic log of the most recent delivery failure. |
| Callback HTTP request header | X-Appwrite-Webhook-Id | string | ID of the Webhook that triggered this delivery. |
| Callback HTTP request header | X-Appwrite-Webhook-Events | string | List of event names matched in this delivery (comma-separated). |
| Callback HTTP request header | X-Appwrite-Webhook-Project-Id | string | ID of the owning project (e.g., enterprise-ai-hub-210). |
| Callback HTTP request header | X-Appwrite-Webhook-User-Id | string | User ID of the operator who triggered the event (empty when triggered by a server-side API Key). |
| Callback HTTP request header | X-Appwrite-Webhook-Signature | string | base64(hmac_sha1(url + rawBody, signatureKey)) Signature value. |
Errors and boundaries
Event pattern validation failure (
400 general_argument_invalid):eventsEach string in the array must match a valid platform event namespace (e.g.,users.*,databases.*.tables.*.rows.*,buckets.*.files.*,functions.*), and a single Webhook can bind at most 100 event rules.External URL SSRF interception (
400): SSRF protection is enabled by default starting from 2.6.0+;urlURLs pointing tolocalhost,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16, or169.254.169.254will be rejected.Delivery retries, automatic circuit breaking, and consumer idempotency: When the callback endpoint returns a non-
2xxresponse or times out, the backgroundwebhooksqueue Worker retries with exponential backoff; if the consecutive failure count (attempts) reaches the system limit, the Webhook is automatically set toenabled: falseandlogsis recorded. The receiving end should first enqueue the request locally and immediately return200 OK, while performing idempotent deduplication based on the resource$id+$updatedAtin the event payload.
SDK Category Differences
| SDK category | Coverage | Authentication method | Typical scenarios |
|---|---|---|---|
| Server SDK (Node.js / Java / Python / Go) | Full CRUD and updateSignature | Project API Key (webhooks.read / webhooks.write) | Backend services automatically register callbacks, periodically rotate signing keys, and inspect failing Webhooks |
| Console SDK (Node.js / Java / Python / Go) | Full CRUD and updateSignature | Admin Console Session / short-lived JWT | Console Webhook management pages and operations scripts |
| Client / Web SDK (Web) | None Webhooks Service | — | Browsers cannot manage Webhooks |
Examples by language
Credentials: Project API Key (webhooks.* scope) or Console Session; not available in browsers, no web tab.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
import { Client, Webhooks, AgentbaseException } from 'agentbase-node-sdk';
import { createHmac, timingSafeEqual } from 'node:crypto';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT ?? 'https://appbuild-sit.oceanbase.com/v1')
.setProject(process.env.APPBASE_PROJECT_ID ?? 'enterprise-ai-hub-210')
.setKey(process.env.APPBASE_API_KEY!);
const webhooks = new Webhooks(client);
try {
// 1. Create support ticket and billing event callbacks
const hook = await webhooks.create({
webhookId: 'wh_billing_events',
url: 'https://example.com/hooks/agentbase',
name: '计费与工单事件回调',
events: ['databases.tables.update', 'databases.collections.update'],
enabled: true,
security: true, // Enforce validation of the target HTTPS certificate and verify the signature with the returned signatureKey
});
console.log('Webhook 创建成功, signatureKey:', hook.signatureKey);
// 2. List and rotate signature keys (REST equivalent PATCH /v1/webhooks/{webhookId}/signature)
const list = await webhooks.list();
const rotated = await webhooks.updateSignature({ webhookId: 'wh_billing_events' });
console.log('当前 Webhook 总数:', list.total, '轮换后新密钥长度:', rotated.signatureKey.length);
} catch (err) {
if (err instanceof AgentbaseException) {
console.error(`Webhooks 调用失败 [${err.code} ${err.type}]: ${err.message}`);
}
throw err;
}
// Appendix: utility function for verifying X-Appwrite-Webhook-Signature on the receiver side
export function verifyWebhookSignature(webhookUrl: string, rawBody: string, signatureHeader: string, signatureKey: string): boolean {
const expected = createHmac('sha1', signatureKey).update(webhookUrl + rawBody).digest('base64');
return expected.length === signatureHeader.length &&
timingSafeEqual(Buffer.from(expected), Buffer.from(signatureHeader));
}import io.agentbase.Client;
import io.agentbase.services.Webhooks;
import io.agentbase.exceptions.AppBaseException;
import java.util.List;
Client client = new Client()
.setEndpoint("https://appbuild-sit.oceanbase.com/v1")
.setProject("enterprise-ai-hub-210")
.setKey(System.getenv("APPBASE_API_KEY"));
Webhooks webhooks = new Webhooks(client);
try {
var hook = webhooks.create("wh_billing_events", "https://example.com/hooks/agentbase",
"计费事件回调", List.of("databases.tables.update", "databases.collections.update"),
true, true, null, null); // enabled / security; optional httpUser / httpPass
var list = webhooks.list(null, true); // get / update / delete maintain the same webhook
var rotated = webhooks.updateSignature("wh_billing_events"); // Rotate signing keys
System.out.println("Total=" + list.getTotal() + ", sigKey=" + rotated.getSignatureKey());
} catch (AppBaseException e) {
System.err.println("HTTP " + e.getCode() + " type=" + e.getType() + ": " + e.getMessage());
}import os
from agentbase.client import Client
from agentbase.services.webhooks import Webhooks
from agentbase.exception import AgentbaseException
client = (
Client()
.set_endpoint(os.environ.get('APPBASE_ENDPOINT', 'https://appbuild-sit.oceanbase.com/v1'))
.set_project(os.environ.get('APPBASE_PROJECT_ID', 'enterprise-ai-hub-210'))
.set_key(os.environ['APPBASE_API_KEY'])
)
webhooks = Webhooks(client)
try:
hook = webhooks.create(
webhook_id='wh_billing_events',
url='https://example.com/hooks/agentbase',
name='计费事件回调',
events=['databases.tables.update', 'databases.collections.update'],
enabled=True,
security=True,
)
listed = webhooks.list()
rotated = webhooks.update_signature(webhook_id='wh_billing_events')
print(listed.total, rotated.signature_key)
except AgentbaseException as exc:
print(f"Webhooks error {exc.code} ({exc.type}): {exc.message}")package main
import (
"fmt"
"os"
"agentbase-go-sdk/agentbase"
)
func main() {
cl := agentbase.NewClient(
agentbase.WithEndpoint("https://appbuild-sit.oceanbase.com/v1"),
agentbase.WithProject("enterprise-ai-hub-210"),
agentbase.WithKey(os.Getenv("APPBASE_API_KEY")),
)
webhooks := agentbase.NewWebhooks(cl)
hook, _ := webhooks.Create("wh_billing_events", "https://example.com/hooks/agentbase",
"计费事件回调", []string{"databases.tables.update", "databases.collections.update"},
webhooks.WithCreateEnabled(true),
webhooks.WithCreateSecurity(true), // Platform pushes carry a signature header; use the returned signatureKey to verify the source
)
list, _ := webhooks.List() // Get / Update / Delete maintain the same webhook
rotated, _ := webhooks.UpdateSignature("wh_billing_events")
fmt.Println(hook.Id, list.Total, rotated.SignatureKey)
}# 1. Create a Webhook (POST /v1/webhooks)
curl -sS -X POST "$APPBASE_ENDPOINT/webhooks" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{
"webhookId": "wh_billing_events",
"name": "计费事件回调",
"url": "https://example.com/hooks/agentbase",
"events": ["databases.tables.update", "databases.collections.update"],
"enabled": true,
"security": true,
"httpUser": "hook-user",
"httpPass": "hook-pass"
}'
# 2. Query the Webhook list and details (GET /v1/webhooks, GET /v1/webhooks/{webhookId})
curl -sS "$APPBASE_ENDPOINT/webhooks/wh_billing_events" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY"
# 3. Rotate the Webhook signature key (PATCH /v1/webhooks/{webhookId}/signature)
curl -sS -X PATCH "$APPBASE_ENDPOINT/webhooks/wh_billing_events/signature" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY"Example Guide
JavaScript / TypeScript full example: ../examples/javascript.md
Python full example: ../examples/python.md
Java full example: ../examples/java.md
Go full example: ../examples/go.md