Simulate real-time event notifications and webhook integrations in your mock APIs
Webhooks are automated messages sent from one application to another when a specific event occurs. Instead of polling an API repeatedly, your application receives real-time notifications when data changes.
Get instant notifications when events happen, no polling required
Trigger actions based on specific events like create, update, delete
Example: Stripe uses webhooks to notify your app when a payment succeeds, GitHub sends webhooks when code is pushed, and Shopify triggers webhooks on new orders.
Mock API Builder currently focuses on REST API mocking. Full webhook simulation with automatic notifications is planned for a future release.
However, you can simulate webhook payloads and test your webhook handling logic using the techniques below.
You can create endpoints that return realistic webhook payload structures for testing:
// Create an endpoint: GET /webhooks/payment-success
{
"event": "payment.succeeded",
"id": "evt_1234567890",
"created": "2025-01-15T10:30:00Z",
"data": {
"object": {
"id": "pay_abcdefghijk",
"amount": 2999,
"currency": "usd",
"status": "succeeded",
"customer": {
"id": "cus_xyz789",
"email": "customer@example.com"
}
}
}
}// Create an endpoint: GET /webhooks/user-created
{
"event": "user.created",
"timestamp": "2025-01-15T10:30:00Z",
"webhook_id": "wh_123456",
"data": {
"id": "user_789",
"name": "John Doe",
"email": "john@example.com",
"created_at": "2025-01-15T10:30:00Z"
}
}Test your webhook receiver endpoint by manually sending POST requests with mock payloads:
// Your application's webhook endpoint
app.post('/api/webhooks/payment', async (req, res) => {
const event = req.body;
console.log('Received webhook:', event.event);
if (event.event === 'payment.succeeded') {
// Handle successful payment
await processPayment(event.data);
}
res.status(200).json({ received: true });
});// Get realistic webhook payload from your mock API const mockWebhook = await fetch( 'https://mockapibuilder.io/api/your-project/webhooks/payment-success' ); const webhookData = await mockWebhook.json();
// Simulate webhook delivery to your endpoint
const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';
await fetch(`${BASE_URL}/api/webhooks/payment`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(webhookData)
});Create a test script to simulate webhook events:
// webhook-simulator.js
async function simulateWebhook(eventType, webhookUrl) {
// Fetch mock webhook payload
const mockPayload = await fetch(
`https://mockapibuilder.io/api/your-project/webhooks/${eventType}`
);
const payload = await mockPayload.json();
// Send to your webhook handler
const response = await fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Webhook-Signature': 'mock-signature-123'
},
body: JSON.stringify(payload)
});
console.log(`${eventType}: ${response.status}`);
return response;
}
// Test different events
const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';
await simulateWebhook('payment-success', `${BASE_URL}/api/webhooks/payment`);
await simulateWebhook('user-created', `${BASE_URL}/api/webhooks/user`);
await simulateWebhook('order-placed', `${BASE_URL}/api/webhooks/order`);payment.succeeded - Payment completed successfullypayment.failed - Payment attempt failedpayment.refunded - Payment was refundedsubscription.created - New subscription startedsubscription.canceled - Subscription canceleduser.created - New user registereduser.updated - User profile updateduser.deleted - User account deleteduser.login - User logged inuser.logout - User logged outorder.created - New order placedorder.updated - Order status changedorder.shipped - Order shippedorder.delivered - Order deliveredorder.canceled - Order canceledpost.published - Blog post publishedcomment.created - New comment addedfile.uploaded - File uploadednotification.sent - Notification sentReal webhooks include signatures to verify authenticity. You can simulate this in testing:
// Send webhook with mock signature header
const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';
await fetch(`${BASE_URL}/api/webhooks`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Webhook-Signature': 'sha256=mock-signature-hash',
'X-Webhook-ID': 'wh_123456789',
'X-Webhook-Timestamp': Date.now().toString()
},
body: JSON.stringify(webhookPayload)
});app.post('/api/webhooks', (req, res) => {
const signature = req.headers['x-webhook-signature'];
const timestamp = req.headers['x-webhook-timestamp'];
// In development/testing, you can skip verification
if (process.env.NODE_ENV === 'development') {
console.log('Dev mode: Skipping signature verification');
} else {
// In production, verify the signature
if (!verifyWebhookSignature(req.body, signature)) {
return res.status(401).json({ error: 'Invalid signature' });
}
}
// Process webhook
processWebhook(req.body);
res.status(200).json({ received: true });
});Real webhook services retry failed deliveries. Test your retry handling:
// Simulate webhook retry logic
async function simulateWebhookWithRetry(url, payload, maxRetries = 3) {
let attempts = 0;
while (attempts < maxRetries) {
try {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (response.ok) {
console.log(`✓ Webhook delivered on attempt ${attempts + 1}`);
return true;
}
throw new Error(`HTTP ${response.status}`);
} catch (error) {
attempts++;
console.log(`✗ Attempt ${attempts} failed: ${error.message}`);
if (attempts < maxRetries) {
// Exponential backoff
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, attempts) * 1000)
);
}
}
}
console.log('✗ All retry attempts failed');
return false;
}Scenario: Test your app's response to payment events without real transactions
Scenario: Trigger actions based on user events
Scenario: Automate order fulfillment pipeline
Scenario: Automate content distribution