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

# Statistics

> Get aggregated event statistics by type — for user behavior tracking and rule-based fraud detection in gu1, with examples for stats use cases.

## Overview

Retrieves aggregated statistics about user events, grouped by event type. This endpoint provides a quick overview of event distribution, counts, and last occurrence timestamps, perfect for building dashboards and monitoring user activity patterns.

## Endpoint

```
GET https://api.gu1.ai/events/user/stats
```

## Authentication

Requires a valid API key in the Authorization header:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

## Query Parameters

<ParamField query="user_id" type="string">
  Filter statistics by user identifier. If not provided, returns stats across all users in your organization.

  Example: `?user_id=user_12345`
</ParamField>

## Response

<ResponseField name="success" type="boolean">
  Indicates if the request was successful
</ResponseField>

<ResponseField name="stats" type="array">
  Array of statistics objects grouped by event type

  <ResponseField name="stats[].event_type" type="string">
    The event type (e.g., "LOGIN\_SUCCESS", "TRANSFER\_SUCCESS")
  </ResponseField>

  <ResponseField name="stats[].count" type="number">
    Total number of events of this type
  </ResponseField>

  <ResponseField name="stats[].last_occurrence" type="string">
    Timestamp of the most recent event of this type (ISO 8601)
  </ResponseField>
</ResponseField>

## Examples

### Get Stats for All Users

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.gu1.ai/events/user/stats \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.gu1.ai/events/user/stats', {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY'
    }
  });

  const data = await response.json();
  console.log(data.stats);
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      'https://api.gu1.ai/events/user/stats',
      headers={'Authorization': 'Bearer YOUR_API_KEY'}
  )

  data = response.json()
  print(data['stats'])
  ```
</CodeGroup>

### Get Stats for Specific User

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://api.gu1.ai/events/user/stats?user_id=user_12345" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'https://api.gu1.ai/events/user/stats?user_id=user_12345',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  console.log(data.stats);
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      'https://api.gu1.ai/events/user/stats',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={'user_id': 'user_12345'}
  )

  data = response.json()
  print(data['stats'])
  ```
</CodeGroup>

## Response Example

```json theme={null}
{
  "success": true,
  "stats": [
    {
      "event_type": "LOGIN_SUCCESS",
      "count": 45,
      "last_occurrence": "2026-01-30T14:30:00Z"
    },
    {
      "event_type": "LOGIN_FAILED",
      "count": 3,
      "last_occurrence": "2026-01-30T08:15:00Z"
    },
    {
      "event_type": "TRANSFER_SUCCESS",
      "count": 12,
      "last_occurrence": "2026-01-30T12:00:00Z"
    },
    {
      "event_type": "PROFILE_UPDATED",
      "count": 2,
      "last_occurrence": "2026-01-25T10:30:00Z"
    },
    {
      "event_type": "PASSWORD_CHANGE",
      "count": 1,
      "last_occurrence": "2026-01-20T16:45:00Z"
    }
  ]
}
```

## Error Responses

### 401 Unauthorized

```json theme={null}
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or missing API key"
  }
}
```

### 403 Forbidden

```json theme={null}
{
  "success": false,
  "error": {
    "code": "FORBIDDEN",
    "message": "Insufficient permissions to read events"
  }
}
```

### 500 Internal Server Error

```json theme={null}
{
  "success": false,
  "error": {
    "code": "STATS_FETCH_FAILED",
    "message": "Failed to fetch event statistics"
  }
}
```

## Use Cases

### Dashboard Summary

Build a dashboard showing event distribution:

```javascript theme={null}
async function buildEventDashboard(userId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  // Group by category
  const authEvents = data.stats.filter(s =>
    ['LOGIN_SUCCESS', 'LOGIN_FAILED', 'LOGOUT'].includes(s.event_type)
  );

  const transferEvents = data.stats.filter(s =>
    ['TRANSFER_SUCCESS', 'TRANSFER_FAILED'].includes(s.event_type)
  );

  return {
    authentication: {
      total: authEvents.reduce((sum, e) => sum + e.count, 0),
      events: authEvents
    },
    transfers: {
      total: transferEvents.reduce((sum, e) => sum + e.count, 0),
      events: transferEvents
    }
  };
}
```

### Fraud Monitoring

Monitor for suspicious activity patterns:

```javascript theme={null}
async function detectSuspiciousActivity(userId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();
  const alerts = [];

  // Check failed login attempts
  const failedLogins = data.stats.find(s => s.event_type === 'LOGIN_FAILED');
  if (failedLogins && failedLogins.count > 5) {
    alerts.push({
      type: 'HIGH_FAILED_LOGINS',
      count: failedLogins.count,
      lastOccurrence: failedLogins.last_occurrence
    });
  }

  // Check transfer activity
  const transfers = data.stats.find(s => s.event_type === 'TRANSFER_SUCCESS');
  if (transfers && transfers.count > 10) {
    alerts.push({
      type: 'HIGH_TRANSFER_VOLUME',
      count: transfers.count,
      lastOccurrence: transfers.last_occurrence
    });
  }

  return alerts;
}
```

### User Activity Report

Generate activity reports:

```javascript theme={null}
async function generateActivityReport(userId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  const report = {
    userId,
    generatedAt: new Date().toISOString(),
    totalEvents: data.stats.reduce((sum, s) => sum + s.count, 0),
    eventsByType: data.stats.map(s => ({
      type: s.event_type,
      count: s.count,
      lastActivity: s.last_occurrence
    })),
    mostRecentActivity: data.stats.reduce((latest, s) =>
      new Date(s.last_occurrence) > new Date(latest.last_occurrence)
        ? s
        : latest
    )
  };

  return report;
}
```

### Analytics Metrics

Calculate key metrics:

```javascript theme={null}
async function calculateMetrics(userId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  // Calculate success rates
  const loginSuccess = data.stats.find(s => s.event_type === 'LOGIN_SUCCESS')?.count || 0;
  const loginFailed = data.stats.find(s => s.event_type === 'LOGIN_FAILED')?.count || 0;
  const loginSuccessRate = loginSuccess / (loginSuccess + loginFailed) * 100;

  const transferSuccess = data.stats.find(s => s.event_type === 'TRANSFER_SUCCESS')?.count || 0;
  const transferFailed = data.stats.find(s => s.event_type === 'TRANSFER_FAILED')?.count || 0;
  const transferSuccessRate = transferSuccess / (transferSuccess + transferFailed) * 100;

  return {
    loginSuccessRate: loginSuccessRate.toFixed(2) + '%',
    transferSuccessRate: transferSuccessRate.toFixed(2) + '%',
    totalLogins: loginSuccess + loginFailed,
    totalTransfers: transferSuccess + transferFailed
  };
}
```

### Comparative Analysis

Compare activity across users:

```javascript theme={null}
async function compareUsers(userIds) {
  const userStats = await Promise.all(
    userIds.map(async userId => {
      const response = await fetch(
        `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
        {
          headers: { 'Authorization': `Bearer ${API_KEY}` }
        }
      );
      const data = await response.json();
      return {
        userId,
        totalEvents: data.stats.reduce((sum, s) => sum + s.count, 0),
        stats: data.stats
      };
    })
  );

  // Sort by total activity
  return userStats.sort((a, b) => b.totalEvents - a.totalEvents);
}
```

## Visualization Examples

### Chart Data Preparation

Prepare data for charts:

```javascript theme={null}
async function prepareChartData(userId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  // For pie chart
  const pieData = data.stats.map(s => ({
    name: s.event_type,
    value: s.count
  }));

  // For bar chart
  const barData = data.stats.map(s => ({
    category: s.event_type,
    count: s.count
  }));

  return { pieData, barData };
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="List Events" icon="list" href="/en/api-reference/events/list">
    Query individual events
  </Card>

  <Card title="Create Event" icon="plus" href="/en/api-reference/events/create">
    Track new events
  </Card>

  <Card title="List by Entity" icon="user" href="/en/api-reference/events/list-by-entity">
    Get events for specific entity
  </Card>

  <Card title="Analytics" icon="chart-line" href="/en/use-cases/transaction-monitoring/overview">
    Build analytics dashboards
  </Card>
</CardGroup>
