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

# Analytics API

> Access analytics data programmatically with the Kaie API

## Analytics API

The Analytics API provides programmatic access to your workflow performance data, customer engagement metrics, and business intelligence. Use this API to build custom dashboards, generate reports, and integrate analytics into your own applications.

## Overview

The Analytics API allows you to:

* Retrieve workflow performance metrics
* Access customer engagement data
* Get real-time analytics
* Export historical data
* Create custom reports

## Authentication

All Analytics API requests require authentication. Include your API key in the `Authorization` header:

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://api.kaie.ai/v1/analytics/workflows
```

## Workflow Analytics

### Get Workflow Metrics

Retrieve comprehensive metrics for a specific workflow.

### Request

```http theme={null}
GET /v1/analytics/workflows/{workflow_id}
```

### Parameters

| Parameter     | Type   | Description                                       |
| ------------- | ------ | ------------------------------------------------- |
| `start_date`  | string | Start date for metrics (ISO 8601)                 |
| `end_date`    | string | End date for metrics (ISO 8601)                   |
| `granularity` | string | Data granularity (`hour`, `day`, `week`, `month`) |
| `metrics`     | array  | Specific metrics to include                       |
| `group_by`    | array  | Group data by fields                              |

### Response

```json theme={null}
{
  "data": {
    "workflow_id": "workflow-123",
    "period": {
      "start_date": "2024-01-01T00:00:00Z",
      "end_date": "2024-01-31T23:59:59Z"
    },
    "metrics": {
      "total_executions": 1250,
      "successful_executions": 1187,
      "failed_executions": 63,
      "success_rate": 0.95,
      "average_duration_ms": 12000,
      "total_messages_sent": 2500,
      "total_messages_received": 1250,
      "unique_customers": 450,
      "customer_satisfaction": 4.2,
      "channel_breakdown": {
        "whatsapp": 800,
        "instagram": 300,
        "voice": 150
      }
    },
    "trends": {
      "execution_trend": "increasing",
      "success_rate_trend": "stable",
      "duration_trend": "decreasing"
    },
    "daily_metrics": [
      {
        "date": "2024-01-01",
        "executions": 45,
        "success_rate": 0.96,
        "average_duration_ms": 11500,
        "messages_sent": 90,
        "messages_received": 45,
        "unique_customers": 25
      }
    ]
  }
}
```

### Get Workflow Performance

Get detailed performance metrics for a workflow.

### Request

```http theme={null}
GET /v1/analytics/workflows/{workflow_id}/performance
```

### Parameters

| Parameter          | Type    | Description                       |
| ------------------ | ------- | --------------------------------- |
| `start_date`       | string  | Start date for metrics (ISO 8601) |
| `end_date`         | string  | End date for metrics (ISO 8601)   |
| `include_nodes`    | boolean | Include node-level metrics        |
| `include_channels` | boolean | Include channel breakdown         |

### Response

```json theme={null}
{
  "data": {
    "workflow_id": "workflow-123",
    "period": {
      "start_date": "2024-01-01T00:00:00Z",
      "end_date": "2024-01-31T23:59:59Z"
    },
    "performance": {
      "execution_time": {
        "average_ms": 12000,
        "median_ms": 11000,
        "p95_ms": 25000,
        "p99_ms": 45000
      },
      "throughput": {
        "executions_per_hour": 15.6,
        "peak_executions_per_hour": 45,
        "peak_hour": "14:00"
      },
      "error_rate": {
        "overall": 0.05,
        "by_error_type": {
          "timeout": 0.03,
          "api_error": 0.01,
          "validation_error": 0.01
        }
      },
      "node_performance": [
        {
          "node_id": "welcome",
          "type": "message",
          "execution_count": 1250,
          "success_rate": 0.99,
          "average_duration_ms": 500,
          "error_count": 12
        }
      ],
      "channel_performance": {
        "whatsapp": {
          "executions": 800,
          "success_rate": 0.96,
          "average_duration_ms": 10000
        },
        "instagram": {
          "executions": 300,
          "success_rate": 0.94,
          "average_duration_ms": 15000
        }
      }
    }
  }
}
```

## Customer Analytics

### Get Customer Engagement

Retrieve customer engagement metrics.

### Request

```http theme={null}
GET /v1/analytics/customers/engagement
```

### Parameters

| Parameter          | Type   | Description                       |
| ------------------ | ------ | --------------------------------- |
| `start_date`       | string | Start date for metrics (ISO 8601) |
| `end_date`         | string | End date for metrics (ISO 8601)   |
| `customer_segment` | string | Filter by customer segment        |
| `channel`          | string | Filter by communication channel   |

### Response

```json theme={null}
{
  "data": {
    "period": {
      "start_date": "2024-01-01T00:00:00Z",
      "end_date": "2024-01-31T23:59:59Z"
    },
    "engagement": {
      "total_customers": 450,
      "active_customers": 380,
      "new_customers": 50,
      "returning_customers": 330,
      "average_session_duration": 300,
      "average_messages_per_session": 5.2,
      "customer_satisfaction": 4.2,
      "net_promoter_score": 8.5,
      "engagement_by_channel": {
        "whatsapp": {
          "customers": 300,
          "average_session_duration": 250,
          "satisfaction": 4.3
        },
        "instagram": {
          "customers": 150,
          "average_session_duration": 400,
          "satisfaction": 4.1
        }
      }
    },
    "trends": {
      "customer_growth": "increasing",
      "engagement_trend": "stable",
      "satisfaction_trend": "increasing"
    }
  }
}
```

### Get Customer Journey

Analyze customer journey patterns.

### Request

```http theme={null}
GET /v1/analytics/customers/journey
```

### Parameters

| Parameter          | Type    | Description                        |
| ------------------ | ------- | ---------------------------------- |
| `start_date`       | string  | Start date for analysis (ISO 8601) |
| `end_date`         | string  | End date for analysis (ISO 8601)   |
| `journey_type`     | string  | Type of journey to analyze         |
| `include_dropoffs` | boolean | Include drop-off analysis          |

### Response

```json theme={null}
{
  "data": {
    "period": {
      "start_date": "2024-01-01T00:00:00Z",
      "end_date": "2024-01-31T23:59:59Z"
    },
    "journey": {
      "total_journeys": 1250,
      "completed_journeys": 1000,
      "completion_rate": 0.8,
      "average_journey_duration": 1800,
      "journey_steps": [
        {
          "step": 1,
          "name": "Welcome",
          "customers": 1250,
          "completion_rate": 1.0,
          "average_duration_ms": 500
        },
        {
          "step": 2,
          "name": "Information Collection",
          "customers": 1200,
          "completion_rate": 0.96,
          "average_duration_ms": 15000
        },
        {
          "step": 3,
          "name": "Resolution",
          "customers": 1000,
          "completion_rate": 0.83,
          "average_duration_ms": 30000
        }
      ],
      "drop_off_points": [
        {
          "step": 2,
          "name": "Information Collection",
          "drop_off_count": 50,
          "drop_off_rate": 0.04,
          "common_reasons": ["timeout", "user_abandoned"]
        }
      ]
    }
  }
}
```

## Real-time Analytics

### Get Real-time Metrics

Retrieve real-time analytics data.

### Request

```http theme={null}
GET /v1/analytics/realtime
```

### Parameters

| Parameter        | Type    | Description                        |
| ---------------- | ------- | ---------------------------------- |
| `workflow_id`    | string  | Filter by specific workflow        |
| `channel`        | string  | Filter by communication channel    |
| `include_system` | boolean | Include system performance metrics |

### Response

```json theme={null}
{
  "data": {
    "timestamp": "2024-01-25T14:30:00Z",
    "current_metrics": {
      "active_workflows": 15,
      "active_executions": 25,
      "messages_in_last_hour": 150,
      "average_response_time_ms": 8000,
      "system_health": "healthy"
    },
    "workflow_metrics": [
      {
        "workflow_id": "workflow-123",
        "name": "Customer Support Bot",
        "active_executions": 5,
        "messages_in_last_hour": 45,
        "average_response_time_ms": 7500
      }
    ],
    "channel_metrics": {
      "whatsapp": {
        "active_conversations": 20,
        "messages_in_last_hour": 100
      },
      "instagram": {
        "active_conversations": 5,
        "messages_in_last_hour": 50
      }
    },
    "system_metrics": {
      "cpu_usage": 45.2,
      "memory_usage": 67.8,
      "api_response_time_ms": 150
    }
  }
}
```

## Custom Reports

### Create Custom Report

Create a custom analytics report.

### Request

```http theme={null}
POST /v1/analytics/reports
```

### Request Body

```json theme={null}
{
  "name": "Monthly Performance Report",
  "description": "Monthly performance report for all workflows",
  "metrics": [
    "total_executions",
    "success_rate",
    "average_duration_ms",
    "customer_satisfaction"
  ],
  "filters": {
    "start_date": "2024-01-01T00:00:00Z",
    "end_date": "2024-01-31T23:59:59Z",
    "workflow_ids": ["workflow-123", "workflow-456"]
  },
  "group_by": ["workflow_id", "channel"],
  "granularity": "day"
}
```

### Response

```json theme={null}
{
  "data": {
    "report_id": "report-789",
    "name": "Monthly Performance Report",
    "status": "generating",
    "created_at": "2024-01-25T14:30:00Z",
    "estimated_completion": "2024-01-25T14:35:00Z"
  }
}
```

### Get Report Status

Check the status of a custom report.

### Request

```http theme={null}
GET /v1/analytics/reports/{report_id}
```

### Response

```json theme={null}
{
  "data": {
    "report_id": "report-789",
    "name": "Monthly Performance Report",
    "status": "completed",
    "created_at": "2024-01-25T14:30:00Z",
    "completed_at": "2024-01-25T14:32:00Z",
    "download_url": "https://api.kaie.ai/v1/analytics/reports/report-789/download",
    "expires_at": "2024-02-01T14:30:00Z"
  }
}
```

### Download Report

Download a completed report.

### Request

```http theme={null}
GET /v1/analytics/reports/{report_id}/download
```

### Response

The response will be the report file (CSV, JSON, or PDF depending on the format requested).

## Data Export

### Export Analytics Data

Export analytics data in various formats.

### Request

```http theme={null}
POST /v1/analytics/export
```

### Request Body

```json theme={null}
{
  "data_type": "workflow_metrics",
  "format": "csv",
  "start_date": "2024-01-01T00:00:00Z",
  "end_date": "2024-01-31T23:59:59Z",
  "filters": {
    "workflow_ids": ["workflow-123", "workflow-456"],
    "channels": ["whatsapp", "instagram"]
  },
  "include_metadata": true
}
```

### Response

```json theme={null}
{
  "data": {
    "export_id": "export-123",
    "status": "processing",
    "created_at": "2024-01-25T14:30:00Z",
    "estimated_completion": "2024-01-25T14:35:00Z",
    "download_url": "https://api.kaie.ai/v1/analytics/export/export-123/download"
  }
}
```

## Error Handling

### Common Error Codes

| Status Code | Error Code                 | Description                      |
| ----------- | -------------------------- | -------------------------------- |
| 400         | `INVALID_DATE_RANGE`       | Date range is invalid            |
| 400         | `INVALID_METRICS`          | Requested metrics are invalid    |
| 404         | `WORKFLOW_NOT_FOUND`       | Workflow does not exist          |
| 422         | `INVALID_GRANULARITY`      | Granularity parameter is invalid |
| 429         | `RATE_LIMIT_EXCEEDED`      | Rate limit exceeded              |
| 500         | `REPORT_GENERATION_FAILED` | Report generation failed         |

### Error Response Format

```json theme={null}
{
  "error": {
    "code": "INVALID_DATE_RANGE",
    "message": "Date range is invalid",
    "details": "End date must be after start date",
    "field": "end_date"
  }
}
```

## Rate Limiting

Analytics API endpoints are subject to rate limiting:

* **Real-time metrics**: 1000 requests per hour
* **Historical metrics**: 100 requests per hour
* **Custom reports**: 50 requests per hour
* **Data export**: 20 requests per hour

## Best Practices

### Efficient Data Retrieval

<AccordionGroup>
  <Accordion title="Date Range Selection">
    * Use appropriate date ranges for your needs
    * Avoid requesting data for very long periods
    * Use granularity to reduce data volume
  </Accordion>

  <Accordion title="Metric Selection">
    * Only request metrics you need
    * Use filters to reduce data volume
    * Cache frequently accessed data
  </Accordion>
</AccordionGroup>

### Performance Optimization

<AccordionGroup>
  <Accordion title="Caching">
    * Cache analytics data when possible
    * Use appropriate cache TTL values
    * Implement cache invalidation strategies
  </Accordion>

  <Accordion title="Pagination">
    * Use pagination for large datasets
    * Set appropriate page sizes
    * Implement efficient pagination logic
  </Accordion>
</AccordionGroup>

## Next Steps

Explore more API endpoints:

<CardGroup cols={2}>
  <Card title="Workflows API" icon="diagram-project" href="/api-reference/workflows">
    Manage workflows programmatically
  </Card>

  <Card title="Triggers API" icon="bolt" href="/api-reference/triggers">
    Manage workflow triggers
  </Card>

  <Card title="Webhooks API" icon="webhook" href="/api-reference/webhooks">
    Set up webhook integrations
  </Card>

  <Card title="Authentication" icon="key" href="/api-reference/authentication">
    Learn about API authentication
  </Card>
</CardGroup>
