> ## Documentation Index
> Fetch the complete documentation index at: https://devdraft.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Fetch Webhook

> Retrieve detailed information about a specific webhook endpoint

The Fetch Webhook endpoint allows you to retrieve detailed information about a specific webhook, including its configuration, delivery statistics, and recent activity. This endpoint is useful for debugging webhook issues and monitoring individual webhook performance.

## Endpoint Details

* **URL**: `/api/v0/webhooks/{webhook_id}`
* **Method**: `GET`
* **Authentication**: Required (API Key Authentication with Scopes)
* **Content-Type**: `application/json`
* **Required Scope**: `webhook:read`

## Authentication

This endpoint requires API key authentication with specific scopes:

### Required Headers

```json theme={null}
x-client-key: your-client-key
x-client-secret: your-client-secret
```

### Required Scope

Your API key must have the `webhook:read` scope to access this endpoint.

## Path Parameters

| Parameter   | Type   | Description                   | Required |
| ----------- | ------ | ----------------------------- | -------- |
| webhook\_id | string | Unique identifier for webhook | Yes      |

## Query Parameters

| Parameter       | Type    | Description                               | Default | Example                |
| --------------- | ------- | ----------------------------------------- | ------- | ---------------------- |
| include\_events | boolean | Include recent delivery events            | false   | `?include_events=true` |
| events\_limit   | integer | Number of recent events to include (1-50) | 10      | `?events_limit=20`     |

## Response

### Success Response (200 OK)

<CodeGroup>
  ```json Response theme={null}
  {
    "id": "wh_550e8400e29b41d4a716446655440000",
    "name": "Payment Notifications",
    "url": "https://api.example.com/webhooks/payments",
    "isActive": true,
    "encrypted": false,
    "signing_secret": "whsec_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6",
    "created_at": "2024-03-15T10:30:00.000Z",
    "updated_at": "2024-03-20T14:45:00.000Z",
    "delivery_stats": {
      "total_events": 1250,
      "successful_deliveries": 1235,
      "failed_deliveries": 15,
      "last_delivery": "2024-03-20T14:30:00.000Z",
      "success_rate": 98.8,
      "average_response_time": 145,
      "last_24h_events": 45,
      "last_24h_failures": 2
    },
    "app": {
      "id": "app_123e4567e89b12d3a456426614174000",
      "name": "Your App Name"
    },
    "recent_events": [
      {
        "id": "evt_789012345",
        "event_type": "payment.completed",
        "delivery_status": "delivered",
        "response_code": 200,
        "response_time": 125,
        "created_at": "2024-03-20T14:30:00.000Z",
        "delivered_at": "2024-03-20T14:30:01.000Z",
        "retry_count": 0
      },
      {
        "id": "evt_789012344",
        "event_type": "payment.failed",
        "delivery_status": "failed",
        "response_code": 500,
        "response_time": 30000,
        "error_message": "Internal Server Error",
        "created_at": "2024-03-20T14:25:00.000Z",
        "delivered_at": "2024-03-20T14:25:30.000Z",
        "retry_count": 3
      }
    ]
  }
  ```
</CodeGroup>

### Response Fields

#### Webhook Object

| Field           | Type    | Description                                      |
| --------------- | ------- | ------------------------------------------------ |
| id              | string  | Unique identifier for the webhook                |
| name            | string  | Human-readable name for the webhook              |
| url             | string  | Endpoint URL where events are sent               |
| isActive        | boolean | Whether the webhook is currently active          |
| encrypted       | boolean | Whether payloads are encrypted                   |
| signing\_secret | string  | Secret used for signature verification           |
| created\_at     | string  | ISO 8601 timestamp when webhook was created      |
| updated\_at     | string  | ISO 8601 timestamp when webhook was last updated |
| delivery\_stats | object  | Detailed statistics about webhook deliveries     |
| app             | object  | Application information                          |
| recent\_events  | array   | Recent delivery events (if requested)            |

#### Enhanced Delivery Stats

| Field                   | Type   | Description                                 |
| ----------------------- | ------ | ------------------------------------------- |
| total\_events           | number | Total number of events sent to this webhook |
| successful\_deliveries  | number | Number of successfully delivered events     |
| failed\_deliveries      | number | Number of failed delivery attempts          |
| last\_delivery          | string | ISO 8601 timestamp of last delivery attempt |
| success\_rate           | number | Delivery success rate percentage            |
| average\_response\_time | number | Average response time in milliseconds       |
| last\_24h\_events       | number | Events sent in the last 24 hours            |
| last\_24h\_failures     | number | Failed deliveries in the last 24 hours      |

#### Recent Event Object

| Field            | Type   | Description                                     |
| ---------------- | ------ | ----------------------------------------------- |
| id               | string | Unique identifier for the delivery event        |
| event\_type      | string | Type of event that was delivered                |
| delivery\_status | string | Status of delivery (delivered, failed, pending) |
| response\_code   | number | HTTP response code from webhook endpoint        |
| response\_time   | number | Response time in milliseconds                   |
| error\_message   | string | Error message (if delivery failed)              |
| created\_at      | string | When the event was created                      |
| delivered\_at    | string | When delivery was attempted                     |
| retry\_count     | number | Number of retry attempts                        |

## Example Requests

<CodeGroup>
  ```bash Basic Request theme={null}
  curl -X GET "https://api.devdraft.ai/api/v0/webhooks/wh_550e8400e29b41d4a716446655440000" \
    -H "Content-Type: application/json" \
    -H "x-client-key: your-client-key" \
    -H "x-client-secret: your-client-secret"
  ```

  ```bash With Recent Events theme={null}
  curl -X GET "https://api.devdraft.ai/api/v0/webhooks/wh_550e8400e29b41d4a716446655440000?include_events=true&events_limit=20" \
    -H "Content-Type: application/json" \
    -H "x-client-key: your-client-key" \
    -H "x-client-secret: your-client-secret"
  ```

  ```javascript JavaScript/Node.js theme={null}
  const getWebhook = async (webhookId, options = {}) => {
    const { includeEvents = false, eventsLimit = 10 } = options;
    
    const params = new URLSearchParams();
    if (includeEvents) {
      params.append('include_events', 'true');
      params.append('events_limit', eventsLimit.toString());
    }
    
    const url = `https://api.devdraft.ai/api/v0/webhooks/${webhookId}${params.toString() ? '?' + params.toString() : ''}`;

    try {
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'x-client-key': process.env.DEVDRAFT_CLIENT_KEY,
          'x-client-secret': process.env.DEVDRAFT_CLIENT_SECRET
        }
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch webhook: ${response.statusText}`);
      }

      const webhook = await response.json();
      return webhook;
    } catch (error) {
      console.error('Error fetching webhook:', error);
      throw error;
    }
  };

  // Usage examples
  const webhook = await getWebhook('wh_550e8400e29b41d4a716446655440000');
  console.log(`Webhook "${webhook.name}" has ${webhook.delivery_stats.success_rate}% success rate`);

  // Get webhook with recent events
  const webhookWithEvents = await getWebhook(
    'wh_550e8400e29b41d4a716446655440000',
    { includeEvents: true, eventsLimit: 20 }
  );
  console.log(`Recent events: ${webhookWithEvents.recent_events.length}`);
  ```

  ```python Python theme={null}
  import requests
  from typing import Optional, Dict, Any

  class WebhookManager:
      def __init__(self, client_key: str, client_secret: str, base_url: str = 'https://api.devdraft.ai'):
          self.client_key = client_key
          self.client_secret = client_secret
          self.base_url = base_url
          
      def get_webhook(self, webhook_id: str, include_events: bool = False, events_limit: int = 10) -> Dict[str, Any]:
          headers = {
              'Content-Type': 'application/json',
              'x-client-key': self.client_key,
              'x-client-secret': self.client_secret
          }
          
          params = {}
          if include_events:
              params['include_events'] = 'true'
              params['events_limit'] = str(events_limit)
          
          response = requests.get(
              f"{self.base_url}/api/v0/webhooks/{webhook_id}",
              headers=headers,
              params=params
          )
          
          response.raise_for_status()
          return response.json()
      
      def diagnose_webhook(self, webhook_id: str) -> Dict[str, Any]:
          """Diagnose webhook health and performance"""
          webhook = self.get_webhook(webhook_id, include_events=True, events_limit=50)
          stats = webhook['delivery_stats']
          
          diagnosis = {
              'webhook_id': webhook_id,
              'name': webhook['name'],
              'is_healthy': stats['success_rate'] >= 95,
              'performance_grade': self._get_performance_grade(stats),
              'recommendations': []
          }
          
          # Add recommendations based on stats
          if stats['success_rate'] < 95:
              diagnosis['recommendations'].append('Success rate is below 95% - check endpoint reliability')
          
          if stats['average_response_time'] > 5000:
              diagnosis['recommendations'].append('Response time is high - optimize endpoint performance')
          
          if not webhook['isActive']:
              diagnosis['recommendations'].append('Webhook is inactive - enable if needed')
          
          if not webhook['url'].startswith('https://'):
              diagnosis['recommendations'].append('Use HTTPS for better security')
          
          return diagnosis
      
      def _get_performance_grade(self, stats: Dict[str, Any]) -> str:
          success_rate = stats['success_rate']
          response_time = stats['average_response_time']
          
          if success_rate >= 99 and response_time < 1000:
              return 'A'
          elif success_rate >= 95 and response_time < 3000:
              return 'B'
          elif success_rate >= 90 and response_time < 5000:
              return 'C'
          else:
              return 'D'

  # Usage
  webhook_manager = WebhookManager(
      client_key='your-client-key',
      client_secret='your-client-secret'
  )

  # Get webhook details
  webhook = webhook_manager.get_webhook('wh_550e8400e29b41d4a716446655440000')
  print(f"Webhook: {webhook['name']}")
  print(f"Success rate: {webhook['delivery_stats']['success_rate']}%")

  # Diagnose webhook health
  diagnosis = webhook_manager.diagnose_webhook('wh_550e8400e29b41d4a716446655440000')
  print(f"Health status: {'Healthy' if diagnosis['is_healthy'] else 'Unhealthy'}")
  print(f"Performance grade: {diagnosis['performance_grade']}")
  ```
</CodeGroup>

## Error Responses

<CodeGroup>
  ```json 404 Not Found theme={null}
  {
    "statusCode": 404,
    "message": "Webhook not found",
    "error": "Not Found",
    "details": "No webhook found with ID: wh_550e8400e29b41d4a716446655440000"
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "statusCode": 401,
    "message": "Client key or secret missing",
    "error": "Unauthorized",
    "details": "Please provide both x-client-key and x-client-secret headers"
  }
  ```

  ```json 403 Forbidden theme={null}
  {
    "statusCode": 403,
    "message": "Missing required scope",
    "error": "Forbidden",
    "details": "API key does not have the required webhook:read scope"
  }
  ```

  ```json 400 Bad Request theme={null}
  {
    "statusCode": 400,
    "message": "Invalid query parameters",
    "error": "Bad Request",
    "details": "events_limit must be between 1 and 50"
  }
  ```
</CodeGroup>

## Webhook Diagnostics

### Health Indicators

<AccordionGroup>
  <Accordion title="Success Rate" icon="chart-line">
    * **Excellent**: 99%+ success rate
    * **Good**: 95-99% success rate
    * **Warning**: 90-95% success rate
    * **Critical**: Below 90% success rate
  </Accordion>

  <Accordion title="Response Time" icon="clock">
    * **Fast**: Under 1 second average response time
    * **Acceptable**: 1-3 seconds average response time
    * **Slow**: 3-5 seconds average response time
    * **Critical**: Over 5 seconds average response time
  </Accordion>

  <Accordion title="Recent Activity" icon="activity">
    * **Active**: Events delivered in the last 24 hours
    * **Idle**: No events in the last 24 hours
    * **Failing**: Multiple failures in recent deliveries
  </Accordion>
</AccordionGroup>

### Troubleshooting Guide

<Tabs>
  <Tab title="Delivery Failures">
    **Common causes and solutions:**

    * **HTTP 4xx errors**: Check webhook endpoint implementation
    * **HTTP 5xx errors**: Check webhook server health and capacity
    * **Timeout errors**: Optimize webhook response time
    * **Connection errors**: Verify webhook URL and network connectivity
  </Tab>

  <Tab title="Performance Issues">
    **Optimization strategies:**

    * **Async processing**: Process events asynchronously in webhook handler
    * **Quick responses**: Return HTTP 200 immediately, process later
    * **Error handling**: Implement proper error handling and logging
    * **Rate limiting**: Implement rate limiting on webhook endpoint
  </Tab>

  <Tab title="Security Concerns">
    **Security best practices:**

    * **Signature verification**: Always verify webhook signatures
    * **HTTPS only**: Use HTTPS endpoints for all webhooks
    * **IP whitelisting**: Consider IP whitelisting for sensitive webhooks
    * **Payload encryption**: Enable encryption for sensitive data
  </Tab>
</Tabs>

## Use Cases

### Webhook Health Monitoring

<CodeGroup>
  ```javascript Health Monitoring Dashboard theme={null}
  const createWebhookDashboard = async (webhookId) => {
    const webhook = await getWebhook(webhookId, { includeEvents: true, eventsLimit: 50 });
    
    const dashboard = {
      webhook: {
        name: webhook.name,
        status: webhook.isActive ? 'Active' : 'Inactive',
        url: webhook.url,
        encrypted: webhook.encrypted
      },
      performance: {
        successRate: webhook.delivery_stats.success_rate,
        avgResponseTime: webhook.delivery_stats.average_response_time,
        last24hEvents: webhook.delivery_stats.last_24h_events,
        last24hFailures: webhook.delivery_stats.last_24h_failures
      },
      recentActivity: webhook.recent_events.map(event => ({
        type: event.event_type,
        status: event.delivery_status,
        time: event.created_at,
        responseTime: event.response_time
      }))
    };
    
    return dashboard;
  };
  ```
</CodeGroup>

### Performance Analysis

<CodeGroup>
  ```javascript Performance Analysis theme={null}
  const analyzeWebhookPerformance = async (webhookId) => {
    const webhook = await getWebhook(webhookId, { includeEvents: true, eventsLimit: 100 });
    
    const analysis = {
      overall: {
        totalEvents: webhook.delivery_stats.total_events,
        successRate: webhook.delivery_stats.success_rate,
        avgResponseTime: webhook.delivery_stats.average_response_time
      },
      trends: {
        recentFailureRate: (webhook.delivery_stats.last_24h_failures / webhook.delivery_stats.last_24h_events) * 100,
        responseTimeDistribution: analyzeResponseTimes(webhook.recent_events),
        commonErrors: findCommonErrors(webhook.recent_events)
      },
      recommendations: generateRecommendations(webhook)
    };
    
    return analysis;
  };

  const analyzeResponseTimes = (events) => {
    const times = events.map(e => e.response_time).filter(Boolean);
    return {
      min: Math.min(...times),
      max: Math.max(...times),
      avg: times.reduce((a, b) => a + b, 0) / times.length,
      median: times.sort()[Math.floor(times.length / 2)]
    };
  };
  ```
</CodeGroup>

## Best Practices

<Steps>
  <Step title="Regular Health Checks">
    Monitor individual webhook performance and set up alerts for degraded performance.
  </Step>

  <Step title="Include Recent Events">
    Use the `include_events` parameter to debug delivery issues and understand webhook behavior.
  </Step>

  <Step title="Performance Monitoring">
    Track response times and success rates to identify optimization opportunities.
  </Step>

  <Step title="Error Analysis">
    Analyze recent events to identify patterns in delivery failures and errors.
  </Step>

  <Step title="Security Auditing">
    Regularly review webhook configuration for security best practices.
  </Step>
</Steps>

## Related Endpoints

* `POST /api/v0/webhooks` - Create a new webhook
* `GET /api/v0/webhooks` - List all webhooks
* `PATCH /api/v0/webhooks/{id}` - Update webhook configuration
* `DELETE /api/v0/webhooks/{id}` - Delete webhook
