# Usage & Analytics API

Track and analyze your API usage with detailed analytics, monitoring, and reporting capabilities.

## Base URL

```
https://api.zaits.net/v1/usage
```

## Authentication

All requests require your API key in the Authorization header:

```http
Authorization: Bearer YOUR_API_KEY
```

{% hint style="info" %}
**Note:** Usage analytics require **read permissions** on your API key.
{% endhint %}

***

## Usage Summary

Get a comprehensive overview of your API usage for the current month.

### Endpoint

```http
GET /v1/usage/summary
```

### Request Example

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET https://api.zaits.net/v1/usage/summary \
  -H "Authorization: Bearer YOUR_API_KEY"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const response = await fetch("https://api.zaits.net/v1/usage/summary", {
  method: "GET",
  headers: {
    Authorization: "Bearer YOUR_API_KEY",
  },
});

const data = await response.json();
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

response = requests.get(
    'https://api.zaits.net/v1/usage/summary',
    headers={'Authorization': 'Bearer YOUR_API_KEY'}
)

data = response.json()
```

{% endtab %}
{% endtabs %}

### Response

```json
{
  "success": true,
  "summary": {
    "current_month_calls": 1247,
    "previous_month_calls": 892,
    "limit": 2500,
    "percent_used": "49.88",
    "trend": "39.79",
    "remaining_calls": 1253
  },
  "by_endpoint": {
    "face": 687,
    "ocr": 423,
    "signing": 137
  },
  "subscription_tier": "basic",
  "period": {
    "start": "2024-01-01T00:00:00.000Z",
    "end": "2024-01-15T14:30:22.123Z"
  }
}
```

### Response Fields

| Field                  | Type          | Description                                         |
| ---------------------- | ------------- | --------------------------------------------------- |
| `current_month_calls`  | number        | Total API calls this month                          |
| `previous_month_calls` | number        | Total API calls last month                          |
| `limit`                | number/string | Monthly API call limit ("unlimited" for enterprise) |
| `percent_used`         | string        | Percentage of monthly limit used                    |
| `trend`                | string        | Percentage change from previous month               |
| `remaining_calls`      | number/string | Remaining calls this month                          |
| `by_endpoint`          | object        | API calls broken down by service                    |
| `subscription_tier`    | string        | Current subscription plan                           |
| `period`               | object        | Date range for the summary                          |

***

## Detailed Usage Statistics

Get detailed usage statistics with filtering and pagination.

### Endpoint

```http
GET /v1/usage/stats
```

### Query Parameters

| Parameter    | Type   | Required | Description                              |
| ------------ | ------ | -------- | ---------------------------------------- |
| `start_date` | string | No       | Start date (ISO 8601 format)             |
| `end_date`   | string | No       | End date (ISO 8601 format)               |
| `endpoint`   | string | No       | Filter by endpoint path                  |
| `limit`      | number | No       | Items per page (default: 100, max: 1000) |
| `page`       | number | No       | Page number (default: 1)                 |

### Request Examples

{% tabs %}
{% tab title="Basic Request" %}

```bash
curl -X GET "https://api.zaits.net/v1/usage/stats" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

{% endtab %}

{% tab title="With Filters" %}

```bash
curl -X GET "https://api.zaits.net/v1/usage/stats?start_date=2025-01-01&endpoint=face&limit=50" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const params = new URLSearchParams({
  start_date: "2025-01-01",
  end_date: "2025-01-31",
  endpoint: "face",
  limit: 50,
  page: 1,
});

const response = await fetch(`https://api.zaits.net/v1/usage/stats?${params}`, {
  headers: {
    Authorization: "Bearer YOUR_API_KEY",
  },
});

const data = await response.json();
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

params = {
    'start_date': '2025-01-01',
    'end_date': '2025-01-31',
    'endpoint': 'face',
    'limit': 50,
    'page': 1
}

response = requests.get(
    'https://api.zaits.net/v1/usage/stats',
    headers={'Authorization': 'Bearer YOUR_API_KEY'},
    params=params
)

data = response.json()
```

{% endtab %}
{% endtabs %}

### Response

```json
{
  "success": true,
  "data": [
    {
      "id": "usage_123456",
      "user_id": "user_789",
      "endpoint": "/v1/face/verify",
      "method": "POST",
      "status_code": 200,
      "response_time": 1.245,
      "created_at": "2024-01-15T14:30:22.123Z",
      "request_size": 1024,
      "response_size": 512,
      "ip_address": "203.0.113.1",
      "user_agent": "MyApp/1.0"
    }
  ],
  "pagination": {
    "total": 1247,
    "page": 1,
    "limit": 100,
    "total_pages": 13
  },
  "statistics": {
    "total_calls": 100,
    "avg_response_time": "1.234",
    "min_response_time": "0.123",
    "max_response_time": "3.456",
    "status_codes": {
      "200": 95,
      "400": 3,
      "429": 2
    }
  },
  "filters": {
    "start_date": "2024-01-01",
    "end_date": null,
    "endpoint": "face"
  }
}
```

### Data Fields

| Field           | Type   | Description                |
| --------------- | ------ | -------------------------- |
| `id`            | string | Unique usage record ID     |
| `endpoint`      | string | API endpoint called        |
| `method`        | string | HTTP method used           |
| `status_code`   | number | HTTP response status       |
| `response_time` | number | Processing time in seconds |
| `created_at`    | string | Timestamp of the request   |
| `request_size`  | number | Request size in bytes      |
| `response_size` | number | Response size in bytes     |
| `ip_address`    | string | Client IP address          |
| `user_agent`    | string | Client user agent          |

***

## Real-time Usage Monitoring

Get real-time usage statistics for monitoring and alerting.

### Endpoint

```http
GET /v1/usage/realtime
```

### Query Parameters

| Parameter  | Type   | Required | Description                                    |
| ---------- | ------ | -------- | ---------------------------------------------- |
| `window`   | string | No       | Time window: `1h`, `6h`, `24h` (default: `1h`) |
| `interval` | string | No       | Data interval: `1m`, `5m`, `15m`, `1h`         |

### Request Example

```bash
curl -X GET "https://api.zaits.net/v1/usage/realtime?window=6h&interval=15m" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Response

```json
{
  "success": true,
  "data": {
    "current_rate": 12.5,
    "peak_rate": 45.2,
    "total_calls": 2847,
    "error_rate": 2.1,
    "avg_response_time": 1.234,
    "by_endpoint": {
      "face": 1823,
      "ocr": 724,
      "signing": 300
    },
    "timeseries": [
      {
        "timestamp": "2024-01-15T14:00:00Z",
        "calls": 45,
        "errors": 1,
        "avg_response_time": 1.123
      },
      {
        "timestamp": "2024-01-15T14:15:00Z",
        "calls": 38,
        "errors": 0,
        "avg_response_time": 1.089
      }
    ]
  },
  "window": "6h",
  "interval": "15m"
}
```

***

## Usage Alerts

Configure usage alerts to monitor your API consumption.

### Create Alert

```http
POST /v1/usage/alerts
```

### Request Body

```json
{
  "name": "High Usage Alert",
  "type": "threshold",
  "condition": {
    "metric": "calls_per_hour",
    "operator": "greater_than",
    "value": 100
  },
  "notification": {
    "webhook_url": "https://your-app.com/webhooks/alerts",
    "email": "admin@yourcompany.com"
  },
  "enabled": true
}
```

### List Alerts

```http
GET /v1/usage/alerts
```

### Update Alert

```http
PUT /v1/usage/alerts/{alert_id}
```

***

## Credit Usage

Track credit consumption for paid APIs.

### Endpoint

```http
GET /v1/usage/credits
```

### Response

```json
{
  "success": true,
  "data": {
    "total_purchased": 10000,
    "total_used": 7542,
    "remaining": 2458,
    "usage_by_service": {
      "face_verification": 3421,
      "ocr_extraction": 2876,
      "document_signing": 1245
    },
    "estimated_monthly_burn": 4820,
    "days_remaining": 15.3
  }
}
```

***

## Export Usage Data

Export usage data for analysis or compliance.

### Endpoint

```http
POST /v1/usage/export
```

### Request Body

```json
{
  "format": "csv",
  "start_date": "2024-01-01",
  "end_date": "2024-01-31",
  "include_details": true,
  "email_to": "analytics@yourcompany.com"
}
```

### Response

```json
{
  "success": true,
  "export_id": "export_abc123",
  "status": "processing",
  "estimated_completion": "2024-01-15T15:00:00Z",
  "download_url": null
}
```

### Check Export Status

```http
GET /v1/usage/export/{export_id}
```

***

## Subscription Limits

Different subscription tiers have different usage limits:

| Tier           | Credits / Month | Real-time Monitoring | Export History | Alerts    |
| -------------- | --------------- | -------------------- | -------------- | --------- |
| **Free**       | 20              | No                   | 7 days         | No        |
| **Basic**      | 4,000           | Yes                  | 30 days        | 1 alert   |
| **Pro**        | 20,000          | Yes                  | 90 days        | 5 alerts  |
| **Enterprise** | Unlimited       | Yes                  | 1 year         | Unlimited |

***

## Error Responses

### Common Error Codes

| Error Code                 | HTTP Status | Description                     |
| -------------------------- | ----------- | ------------------------------- |
| `insufficient_permissions` | 403         | API key lacks read permissions  |
| `invalid_date_range`       | 400         | Invalid start/end date format   |
| `limit_exceeded`           | 400         | Requested limit exceeds maximum |
| `export_quota_exceeded`    | 429         | Too many exports requested      |

### Error Response Format

```json
{
  "success": false,
  "error": {
    "code": "invalid_date_range",
    "message": "Start date cannot be after end date",
    "details": {
      "start_date": "2024-01-31",
      "end_date": "2024-01-01"
    }
  }
}
```

## Best Practices

### Monitoring Your Usage

* **Set up alerts** before reaching 80% of your monthly limit
* **Monitor trends** to predict future usage patterns
* **Track error rates** to identify issues early

### Performance Optimization

* **Use date filters** to reduce data transfer
* **Implement pagination** for large datasets
* **Cache usage summaries** to reduce API calls

### Security Considerations

* **Use read-only API keys** for analytics
* **Restrict IP access** for production monitoring
* **Rotate analytics keys** regularly

***

**Next:** [White-Label Deployment API](https://github.com/ZaitsLLC/platform/blob/master/docs/api/deployments.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zaits.gitbook.io/api/api-reference/usage-analytics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
