Skip to main content
Mock API Builder
Learning Center/Integration/Webhooks & Events
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

Three Ways to Test Webhooks

  1. Webhook inbox — receive POST payloads at /api/webhooks/inbox/{token} and inspect them in your project
  2. Outbound subscriptions — configure URLs in Project Settings → Integrations to receive mock.request and mock.error events with delivery logs
  3. Mock payload endpoints — return realistic webhook JSON from mock endpoints (techniques below)
1. Webhook Inbox (Receiver)

Send test webhooks to your project inbox using the project share token or slug:

# POST a test payload to your inbox
curl -X POST https://www.mockapibuilder.io/api/webhooks/inbox/YOUR_SHARE_TOKEN \
  -H "Content-Type: application/json" \
  -d '{"event":"payment.succeeded","amount":2999}'

# List received payloads (authenticated)
curl https://www.mockapibuilder.io/api/projects/YOUR_PROJECT_ID/webhook-inbox \
  -H "Authorization: Bearer YOUR_JWT"
2. Outbound Webhook Subscriptions

Subscribe external URLs to mock traffic events. Deliveries are retried via the job queue and logged for debugging.

In the UI, manage this from Project Settings → Integrations: add a subscription, toggle it on or off, and scroll down to the delivery log to see each attempt's status code, timestamp, and whether it succeeded or failed.

curl -X POST https://www.mockapibuilder.io/api/projects/YOUR_PROJECT_ID/webhooks \
  -H "Authorization: Bearer YOUR_JWT" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "CI notifier",
    "targetUrl": "https://example.com/hook",
    "events": ["mock.request", "mock.error"]
  }'

# View subscriptions and recent deliveries
curl "https://www.mockapibuilder.io/api/projects/YOUR_PROJECT_ID/webhooks?deliveries=true" \
  -H "Authorization: Bearer YOUR_JWT"

3. Simulating Webhook Payloads with Mock Endpoints

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": "2025-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": "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"
  }
}

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://mockapibuilder.io/api/your-project/webhooks/payment-success'
);
const webhookData = await mockWebhook.json();

3. Send to Your Webhook Handler

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

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

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
Previous: CORS & SecurityNext: Custom Domains & mTLS
Mock API Builder

Built for developers, by developers

DocumentationContactPrivacy PolicyTerms of Service

© 2026 Mock API Builder. All rights reserved.

Double-click for what's new
Learning Center
Learning Center