Integration

Webhooks & Events

Simulate real-time event notifications and webhook integrations in your mock APIs

What are Webhooks?

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.

Real-Time Updates

Get instant notifications when events happen, no polling required

Event-Driven

Trigger actions based on specific events like create, update, delete

How Webhooks Work
  1. Subscribe: You provide a URL endpoint to receive webhook notifications
  2. Event Occurs: Something happens (e.g., new user created, order placed)
  3. Notification Sent: The service sends an HTTP POST request to your URL
  4. Process Event: Your application receives and processes the webhook data

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.

Webhook Simulation with Mock API Builder

Current Feature Status

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.

Simulating Webhook Payloads

You can create endpoints that return realistic webhook payload structures for testing:

Example: Payment Success Webhook

// Create an endpoint: GET /webhooks/payment-success
{
  "event": "payment.succeeded",
  "id": "evt_1234567890",
  "created": "2024-01-15T10:30:00Z",
  "data": {
    "object": {
      "id": "pay_abcdefghijk",
      "amount": 2999,
      "currency": "usd",
      "status": "succeeded",
      "customer": {
        "id": "cus_xyz789",
        "email": "customer@example.com"
      }
    }
  }
}

Example: User Created Webhook

// Create an endpoint: GET /webhooks/user-created
{
  "event": "user.created",
  "timestamp": "2024-01-15T10:30:00Z",
  "webhook_id": "wh_123456",
  "data": {
    "id": "user_789",
    "name": "John Doe",
    "email": "john@example.com",
    "created_at": "2024-01-15T10:30:00Z"
  }
}

Testing Your Webhook Handlers

Manual Webhook Testing

Test your webhook receiver endpoint by manually sending POST requests with mock payloads:

1. Create a Webhook Receiver

// 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 });
});

2. Fetch Mock Webhook Data

// Get realistic webhook payload from your mock API
const mockWebhook = await fetch(
  'https://api.mockbuilder.com/your-project/webhooks/payment-success'
);
const webhookData = await mockWebhook.json();

3. Send to Your Webhook Handler

// Simulate webhook delivery to your endpoint
await fetch('http://localhost:3000/api/webhooks/payment', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(webhookData)
});
Automated Webhook Testing Script

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://api.mockbuilder.com/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
await simulateWebhook('payment-success', 'http://localhost:3000/api/webhooks/payment');
await simulateWebhook('user-created', 'http://localhost:3000/api/webhooks/user');
await simulateWebhook('order-placed', 'http://localhost:3000/api/webhooks/order');

Common Webhook Event Types

Payment Events
  • payment.succeeded - Payment completed successfully
  • payment.failed - Payment attempt failed
  • payment.refunded - Payment was refunded
  • subscription.created - New subscription started
  • subscription.canceled - Subscription canceled
User Events
  • user.created - New user registered
  • user.updated - User profile updated
  • user.deleted - User account deleted
  • user.login - User logged in
  • user.logout - User logged out
Order Events
  • order.created - New order placed
  • order.updated - Order status changed
  • order.shipped - Order shipped
  • order.delivered - Order delivered
  • order.canceled - Order canceled
Content Events
  • post.published - Blog post published
  • comment.created - New comment added
  • file.uploaded - File uploaded
  • notification.sent - Notification sent

Webhook Security Simulation

Signature Verification (Mock)

Real webhooks include signatures to verify authenticity. You can simulate this in testing:

Mock Webhook with Signature:

// Send webhook with mock signature header
await fetch('http://localhost:3000/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)
});

Verify Signature (Test Handler):

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 });
});
Webhook Retry Logic

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;
}

Webhook Testing Use Cases

1. Payment Integration Testing

Scenario: Test your app's response to payment events without real transactions

  • • Create mock payment success/failure webhooks
  • • Test order fulfillment workflows
  • • Verify email notifications are sent
  • • Check database updates for payment records
2. User Lifecycle Events

Scenario: Trigger actions based on user events

  • • Send welcome emails on user.created
  • • Update analytics on user.login
  • • Trigger cleanup tasks on user.deleted
  • • Sync with third-party services
3. E-commerce Order Processing

Scenario: Automate order fulfillment pipeline

  • • Test inventory deduction on order.created
  • • Trigger shipping label generation
  • • Send tracking updates to customers
  • • Handle order cancellations and refunds
4. Content Publishing Workflows

Scenario: Automate content distribution

  • • Post to social media on post.published
  • • Send email newsletters to subscribers
  • • Update search indexes
  • • Trigger CDN cache invalidation

Best Practices

  • Create realistic webhook payloads matching the structure of services you'll integrate
  • Test idempotency ensure your webhook handlers can safely process duplicate events
  • Respond quickly webhook handlers should return 200 OK within seconds, process async
  • Log all webhook events for debugging and audit trails
  • Validate webhook signatures in production to prevent unauthorized requests
  • Handle failures gracefully implement retry logic and dead letter queues
  • Use tools like ngrok to expose local webhook endpoints during development
  • Document your webhook events for team members integrating with your API