> ## 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.

# List Webhooks

> Retrieve all webhooks associated with your Devdraft application

The List Webhooks endpoint allows you to retrieve all webhook endpoints associated with your application. This endpoint provides comprehensive information about each webhook including delivery statistics and configuration details.

## Endpoint Details

* **URL**: `/api/v0/webhooks`
* **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.

## Query Parameters

| Parameter | Type    | Description                         | Default | Example        |
| --------- | ------- | ----------------------------------- | ------- | -------------- |
| page      | integer | Page number for pagination          | 1       | `?page=2`      |
| limit     | integer | Number of webhooks per page (1-100) | 20      | `?limit=50`    |
| active    | boolean | Filter by active status             | all     | `?active=true` |

## Response

### Success Response (200 OK)

<CodeGroup>
  ```json Response theme={null}
  {
    "data": [
      {
        "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
        },
        "app": {
          "id": "app_123e4567e89b12d3a456426614174000",
          "name": "Your App Name"
        }
      },
      {
        "id": "wh_660f9500f30c52e5b827557766551111",
        "name": "Order Updates",
        "url": "https://api.example.com/webhooks/orders",
        "isActive": true,
        "encrypted": true,
        "signing_secret": "whsec_b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7",
        "created_at": "2024-03-18T09:15:00.000Z",
        "updated_at": "2024-03-20T16:20:00.000Z",
        "delivery_stats": {
          "total_events": 850,
          "successful_deliveries": 845,
          "failed_deliveries": 5,
          "last_delivery": "2024-03-20T16:15:00.000Z",
          "success_rate": 99.4
        },
        "app": {
          "id": "app_123e4567e89b12d3a456426614174000",
          "name": "Your App Name"
        }
      },
      {
        "id": "wh_770g0611g41d63f6c938668877662222",
        "name": "Test Webhook",
        "url": "https://webhook.site/test-endpoint",
        "isActive": false,
        "encrypted": false,
        "signing_secret": "whsec_c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8",
        "created_at": "2024-03-19T11:45:00.000Z",
        "updated_at": "2024-03-19T11:45:00.000Z",
        "delivery_stats": {
          "total_events": 0,
          "successful_deliveries": 0,
          "failed_deliveries": 0,
          "last_delivery": null,
          "success_rate": 0
        },
        "app": {
          "id": "app_123e4567e89b12d3a456426614174000",
          "name": "Your App Name"
        }
      }
    ],
    "pagination": {
      "current_page": 1,
      "total_pages": 1,
      "total_count": 3,
      "per_page": 20,
      "has_next": false,
      "has_previous": false
    }
  }
  ```
</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  | Statistics about webhook deliveries              |
| app             | object  | Application information                          |

#### Delivery Stats Object

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

## Example Requests

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

  ```bash With Pagination theme={null}
  curl -X GET "https://api.devdraft.ai/api/v0/webhooks?page=2&limit=10" \
    -H "Content-Type: application/json" \
    -H "x-client-key: your-client-key" \
    -H "x-client-secret: your-client-secret"
  ```

  ```bash Filter Active Webhooks theme={null}
  curl -X GET "https://api.devdraft.ai/api/v0/webhooks?active=true" \
    -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 getWebhooks = async (options = {}) => {
    const { page = 1, limit = 20, active } = options;
    
    const params = new URLSearchParams({
      page: page.toString(),
      limit: limit.toString(),
      ...(active !== undefined && { active: active.toString() })
    });

    try {
      const response = await fetch(`https://api.devdraft.ai/api/v0/webhooks?${params}`, {
        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 webhooks: ${response.statusText}`);
      }

      const webhooks = await response.json();
      console.log(`Found ${webhooks.data.length} webhooks`);
      
      return webhooks;
    } catch (error) {
      console.error('Error fetching webhooks:', error);
      throw error;
    }
  };

  // Usage examples
  const allWebhooks = await getWebhooks();
  const activeWebhooks = await getWebhooks({ active: true });
  const page2 = await getWebhooks({ page: 2, limit: 10 });
  ```

  ```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 list_webhooks(self, page: int = 1, limit: int = 20, active: Optional[bool] = None) -> Dict[str, Any]:
          headers = {
              'Content-Type': 'application/json',
              'x-client-key': self.client_key,
              'x-client-secret': self.client_secret
          }
          
          params = {
              'page': page,
              'limit': limit
          }
          
          if active is not None:
              params['active'] = str(active).lower()
          
          response = requests.get(
              f"{self.base_url}/api/v0/webhooks",
              headers=headers,
              params=params
          )
          
          response.raise_for_status()
          return response.json()
      
      def get_webhook_stats(self) -> Dict[str, Any]:
          """Get summary statistics for all webhooks"""
          webhooks_response = self.list_webhooks(limit=100)  # Get all webhooks
          webhooks = webhooks_response['data']
          
          total_webhooks = len(webhooks)
          active_webhooks = sum(1 for w in webhooks if w['isActive'])
          total_events = sum(w['delivery_stats']['total_events'] for w in webhooks)
          total_successful = sum(w['delivery_stats']['successful_deliveries'] for w in webhooks)
          
          return {
              'total_webhooks': total_webhooks,
              'active_webhooks': active_webhooks,
              'inactive_webhooks': total_webhooks - active_webhooks,
              'total_events_sent': total_events,
              'total_successful_deliveries': total_successful,
              'overall_success_rate': (total_successful / total_events * 100) if total_events > 0 else 0
          }

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

  # List all webhooks
  all_webhooks = webhook_manager.list_webhooks()
  print(f"Total webhooks: {all_webhooks['pagination']['total_count']}")

  # List only active webhooks
  active_webhooks = webhook_manager.list_webhooks(active=True)
  print(f"Active webhooks: {len(active_webhooks['data'])}")

  # Get webhook statistics
  stats = webhook_manager.get_webhook_stats()
  print(f"Overall success rate: {stats['overall_success_rate']:.1f}%")
  ```
</CodeGroup>

## Error Responses

<CodeGroup>
  ```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": "Limit must be between 1 and 100"
  }
  ```
</CodeGroup>

## Filtering and Pagination

### Pagination

<AccordionGroup>
  <Accordion title="Page Navigation" icon="arrows-left-right">
    * **page**: Page number (starting from 1)
    * **limit**: Items per page (1-100, default: 20)
    * **Response includes**: Current page, total pages, total count, navigation flags
  </Accordion>

  <Accordion title="Pagination Response" icon="list">
    ```json theme={null}
    "pagination": {
      "current_page": 1,
      "total_pages": 3,
      "total_count": 45,
      "per_page": 20,
      "has_next": true,
      "has_previous": false
    }
    ```
  </Accordion>
</AccordionGroup>

### Filtering

<AccordionGroup>
  <Accordion title="By Active Status" icon="filter">
    * **active=true**: Show only active webhooks
    * **active=false**: Show only inactive webhooks
    * **No filter**: Show all webhooks regardless of status
  </Accordion>

  <Accordion title="Future Filters" icon="roadmap">
    Additional filtering options coming soon:

    * Filter by creation date range
    * Filter by delivery success rate
    * Search by webhook name or URL
  </Accordion>
</AccordionGroup>

## Webhook Management

<CardGroup cols={2}>
  <Card title="Monitor Performance" icon="chart-line">
    Track delivery success rates and identify failing webhooks
  </Card>

  <Card title="Manage Configuration" icon="gear">
    Review webhook settings and update configurations as needed
  </Card>

  <Card title="Debug Issues" icon="bug">
    Analyze delivery statistics to troubleshoot webhook problems
  </Card>

  <Card title="Audit Activity" icon="clipboard-list">
    Review webhook creation and modification history
  </Card>
</CardGroup>

## Use Cases

### Webhook Health Monitoring

<CodeGroup>
  ```javascript Health Check Example theme={null}
  const monitorWebhookHealth = async () => {
    const webhooks = await getWebhooks();
    
    const unhealthyWebhooks = webhooks.data.filter(webhook => {
      const stats = webhook.delivery_stats;
      return stats.success_rate < 95 && stats.total_events > 10;
    });
    
    if (unhealthyWebhooks.length > 0) {
      console.log('Unhealthy webhooks detected:');
      unhealthyWebhooks.forEach(webhook => {
        console.log(`- ${webhook.name}: ${webhook.delivery_stats.success_rate}% success rate`);
      });
      
      // Send alert to monitoring system
      await sendHealthAlert(unhealthyWebhooks);
    }
  };
  ```
</CodeGroup>

### Configuration Audit

<CodeGroup>
  ```javascript Configuration Audit theme={null}
  const auditWebhookConfiguration = async () => {
    const webhooks = await getWebhooks();
    
    const auditReport = {
      total: webhooks.data.length,
      active: webhooks.data.filter(w => w.isActive).length,
      encrypted: webhooks.data.filter(w => w.encrypted).length,
      with_custom_secrets: webhooks.data.filter(w => w.signing_secret?.startsWith('whsec_')).length,
      https_endpoints: webhooks.data.filter(w => w.url.startsWith('https://')).length
    };
    
    console.log('Webhook Configuration Audit:', auditReport);
    
    // Check for security recommendations
    const recommendations = [];
    
    if (auditReport.https_endpoints < auditReport.total) {
      recommendations.push('Consider using HTTPS for all webhook endpoints');
    }
    
    if (auditReport.encrypted < auditReport.total) {
      recommendations.push('Consider enabling encryption for sensitive webhooks');
    }
    
    return { auditReport, recommendations };
  };
  ```
</CodeGroup>

## Best Practices

<Steps>
  <Step title="Regular Health Checks">
    Monitor webhook delivery statistics regularly to identify and resolve issues quickly.
  </Step>

  <Step title="Pagination for Scale">
    Use pagination when dealing with large numbers of webhooks to improve performance.
  </Step>

  <Step title="Filter Efficiently">
    Use status filters to focus on specific webhook categories for management tasks.
  </Step>

  <Step title="Monitor Success Rates">
    Set up alerts for webhooks with success rates below acceptable thresholds.
  </Step>

  <Step title="Security Audit">
    Regularly audit webhook configurations for security best practices.
  </Step>
</Steps>

## Related Endpoints

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