Server implementation
These are sample server implementations of webhook endpoints in different programming languages.
info
We will gladly provide you with sample code in other languages/frameworks if you need it.
Node.js Example
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhook', (req, res) => {
const event = req.body;
console.log('Received webhook event:', JSON.stringify(event, null, 2));
// Validate the event
if (!event.organizationCode || !event.type || !event.operation || !event.doc) {
return res.status(400).send('Invalid event payload');
}
// Process based on operation type
switch(event.operation) {
case 'create':
handleDocumentCreated(event.doc);
break;
case 'update':
handleDocumentUpdated(event.doc);
break;
case 'delete':
handleDocumentDeleted(event.doc);
break;
default:
console.log('Unknown operation:', event.operation);
}
// Return a 200 OK to acknowledge receipt
res.status(200).send('Event received');
});
function handleDocumentCreated(doc) {
console.log(`Document created: ${doc.id} - ${doc.name}`);
// Your business logic here
}
function handleDocumentUpdated(doc) {
console.log(`Document updated: ${doc.id} - ${doc.name}`);
// Your business logic here
}
function handleDocumentDeleted(doc) {
console.log(`Document deleted: ${doc.id} - ${doc.name}`);
// Your business logic here
}
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Webhook server listening on port ${PORT}`);
});
Python Example
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
event = request.json
print(f"Received webhook event: {event}")
# Validate the event
if not all(k in event for k in ['organizationCode', 'type', 'operation', 'doc']):
return jsonify({'error': 'Invalid event payload'}), 400
# Process based on operation type
if event['operation'] == 'create':
handle_document_created(event['doc'])
elif event['operation'] == 'update':
handle_document_updated(event['doc'])
elif event['operation'] == 'delete':
handle_document_deleted(event['doc'])
else:
print(f"Unknown operation: {event['operation']}")
# Return a 200 OK to acknowledge receipt
return jsonify({'status': 'success'}), 200
def handle_document_created(doc):
print(f"Document created: {doc['id']} - {doc['name']}")
# Your business logic here
def handle_document_updated(doc):
print(f"Document updated: {doc['id']} - {doc['name']}")
# Your business logic here
def handle_document_deleted(doc):
print(f"Document deleted: {doc['id']} - {doc['name']}")
# Your business logic here
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)
Best Practices
- Always respond quickly: Webhooks expect a fast response (within a few seconds). For long-running processes, acknowledge the webhook immediately and process the event asynchronously.
- Implement retry logic: Stonal may retry failed webhook deliveries. Implement idempotency in your handlers to avoid duplicate processing.
- Secure your endpoint: Consider using HTTPS.
- Set up monitoring: Monitor your webhook endpoint for availability and response times.
- Handle errors gracefully: Log errors for debugging, but ensure your webhook endpoint still returns a
200 OK
response when you've successfully received the event, even if your processing has errors.