> For the complete documentation index, see [llms.txt](https://products.monterosa.co/mic/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://products.monterosa.co/mic/reference/services/audience-api.md).

# Audience API (Beta)

Complete Audience API documentation including public user-facing endpoints and private backend-to-backend APIs for bulk operations and data exports.

The **Audience API** is a dual-interface system providing comprehensive loyalty and gamification features through two distinct APIs:

* **Public API**: User-facing endpoints for self-service profile management (JWT authenticated)
* **Private API**: Backend-to-backend endpoints for bulk operations and admin tasks (API key authenticated)

## Architecture

### Public API (User-Facing)

* JWT token authentication
* User-scoped operations (users can only access their own data)
* Rate limit: 100 requests/minute per user
* Endpoints: Profile, Transactions, Challenges, Notifications, Product Redemption

### Private API (Backend-to-Backend)

* API key + secret authentication
* Organization-scoped operations (full access to org data)
* Rate limit: 10,000 requests/minute per API key
* Endpoints: Bulk operations, User search, Data exports

## Base URL

`https://api.monterosa.cloud/v1/api/audience`

All requests require the `X-Monterosa-Org-ID` header with your organization ID.

***

## Public API Endpoints

### User Profile

#### GET /profile

Get the authenticated user's complete profile including loyalty metrics and active challenges.

**Authentication**: JWT Bearer token (required)

**Response**:

```json
{
  "success": true,
  "data": {
    "userId": "alice",
    "profile": {
      "email": "alice@example.com",
      "displayName": "Alice Smith",
      "customFields": {
        "favoriteTeam": "Liverpool FC"
      }
    },
    "loyalty": {
      "metrics": {
        "points": 1500,
        "xp": 2300,
        "coins": 450
      },
      "tier": "gold",
      "badges": ["early-adopter", "super-fan"]
    },
    "challenges": [
      {
        "campaignId": "campaign_123",
        "name": "Watch 5 Videos",
        "status": "in_progress",
        "progress": { "current": 3, "required": 5 }
      }
    ]
  }
}
```

#### PATCH /profile

Update the authenticated user's profile. Users can update displayName, preferences, and custom fields only.

**Authentication**: JWT Bearer token (required)

**Request Body**:

```json
{
  "profile": {
    "displayName": "Alice Updated",
    "customFields": {
      "favoriteTeam": "Manchester United"
    }
  },
  "preferences": {
    "emailNotifications": true,
    "language": "en"
  }
}
```

**Response**:

```json
{
  "success": true,
  "data": {
    "message": "Profile updated successfully"
  }
}
```

***

### Transactions

#### GET /transactions

List the authenticated user's transaction history with optional filters and pagination.

**Authentication**: JWT Bearer token (required)

**Query Parameters**:

* `limit` (optional): Records per page (default: 50, max: 100)
* `type` (optional): Filter by `credit` or `debit`
* `currency` (optional): Filter by `points`, `xp`, or `coins`
* `lastEvaluatedKey` (optional): Pagination token from previous response

**Example**: `/transactions?type=credit&currency=points&limit=20`

**Response**:

```json
{
  "success": true,
  "data": {
    "transactions": [
      {
        "transactionId": "trans_123",
        "type": "credit",
        "amount": 100,
        "currency": "points",
        "reason": "Completed challenge: Watch 5 videos",
        "metadata": {
          "campaignId": "campaign_123"
        },
        "createdAt": "2025-10-06T10:00:00Z"
      }
    ],
    "lastEvaluatedKey": "eyJ0cmFuc2FjdGlvbklkIjoiLi4uIn0"
  }
}
```

***

### Challenges

#### GET /challenges

List the authenticated user's challenges with optional status filter.

**Authentication**: JWT Bearer token (required)

**Query Parameters**:

* `status` (optional): Filter by `in_progress`, `completed`, or `failed`
* `limit` (optional): Records per page (default: 20)

**Response**:

```json
{
  "success": true,
  "data": {
    "challenges": [
      {
        "campaignId": "campaign_123",
        "name": "Watch 5 Videos",
        "description": "Watch 5 videos to earn 100 points",
        "status": "in_progress",
        "progress": {
          "current": 3,
          "required": 5
        },
        "reward": {
          "points": 100,
          "badge": "video-enthusiast"
        },
        "startedAt": "2025-10-05T10:00:00Z",
        "expiresAt": "2025-10-12T10:00:00Z"
      }
    ]
  }
}
```

***

### Notifications

#### GET /notifications

List the authenticated user's notifications with optional unread filter.

**Authentication**: JWT Bearer token (required)

**Query Parameters**:

* `unread` (optional): If `true`, show only unread notifications
* `limit` (optional): Records per page (default: 50, max: 50)
* `lastEvaluatedKey` (optional): Pagination token

**Response**:

```json
{
  "success": true,
  "data": {
    "notifications": [
      {
        "notificationId": "notif_123",
        "type": "reward",
        "title": "Challenge Completed!",
        "message": "You've earned 100 points",
        "data": {
          "campaignId": "campaign_123",
          "points": 100
        },
        "read": false,
        "createdAt": "2025-10-06T10:00:00Z"
      }
    ]
  }
}
```

#### POST /notifications/{notificationId}/read

Mark a specific notification as read.

**Authentication**: JWT Bearer token (required)

**Response**:

```json
{
  "success": true,
  "data": {
    "message": "Notification marked as read"
  }
}
```

***

### Products

#### GET /products

List products available for redemption (only shows in-stock items).

**Authentication**: JWT Bearer token (required)

**Response**:

```json
{
  "success": true,
  "data": {
    "products": [
      {
        "productId": "prod_123",
        "productName": "Exclusive Jersey",
        "description": "Limited edition team jersey",
        "price": 500,
        "currency": "points",
        "inStock": true,
        "stockLevel": 25,
        "imageUrl": "https://cdn.monterosa.cloud/jersey.jpg"
      }
    ]
  }
}
```

#### POST /products/{productId}/redeem

Redeem a product using loyalty currency (points, XP, or coins).

**Authentication**: JWT Bearer token (required)

**Request Body**:

```json
{
  "quantity": 1,
  "deliveryAddress": {
    "street": "123 Main St",
    "city": "London",
    "postcode": "SW1A 1AA",
    "country": "UK"
  }
}
```

**Response** (201 Created):

```json
{
  "success": true,
  "data": {
    "transactionId": "trans_456",
    "productId": "prod_123",
    "quantity": 1,
    "pointsDeducted": 500,
    "orderNumber": "ORD-1728216000000",
    "status": "pending"
  }
}
```

***

## Private API Endpoints

Private endpoints require API key authentication via `X-API-Key` and `X-API-Secret` headers.

### User Actions

#### POST /internal/actions

Report a single user action for processing by the loyalty rules engine.

**Authentication**: API Key (required)

**Permissions**: `actions:write`

**Request Body**:

```json
{
  "userId": "alice",
  "action": "video_watched",
  "data": {
    "videoId": "vid_123",
    "duration": 300
  },
  "timestamp": "2025-10-06T10:00:00Z",
  "metadata": {
    "platform": "web"
  }
}
```

**Response** (202 Accepted):

```json
{
  "success": true,
  "data": {
    "eventId": "evt_123",
    "processed": false,
    "message": "Action queued for processing"
  }
}
```

#### POST /internal/actions/bulk

Submit multiple user actions in bulk (max 1,000 actions per request).

**Authentication**: API Key (required)

**Permissions**: `actions:write`

**Request Body**:

```json
{
  "actions": [
    {
      "userId": "alice",
      "action": "video_watched",
      "data": { "videoId": "vid_123" }
    },
    {
      "userId": "bob",
      "action": "article_read",
      "data": { "articleId": "art_456" }
    }
  ]
}
```

**Response** (202 Accepted):

```json
{
  "success": true,
  "data": {
    "jobId": "bulk_job_789",
    "totalActions": 2,
    "status": "processing",
    "statusUrl": "/internal/jobs/bulk_job_789"
  }
}
```

***

### User Profiles

#### GET /internal/profiles

Retrieve multiple user profiles in batch (max 100 users per request).

**Authentication**: API Key (required)

**Permissions**: `users:read`

**Query Parameters**:

* `user_ids` (required): Comma-separated list of user IDs

**Example**: `/internal/profiles?user_ids=alice,bob,charlie`

**Response**:

```json
{
  "success": true,
  "data": {
    "users": [
      {
        "userId": "alice",
        "profile": {
          "email": "alice@example.com",
          "displayName": "Alice Smith",
          "customFields": {}
        },
        "loyalty": {
          "metrics": { "points": 1500, "xp": 2300, "coins": 450 },
          "tier": "gold",
          "badges": ["early-adopter"]
        }
      }
    ],
    "notFound": ["charlie"]
  }
}
```

#### POST /internal/profiles/update-batch

Update multiple user profiles in bulk (max 1,000 updates per request).

**Authentication**: API Key (required)

**Permissions**: `users:write`

**Request Body**:

```json
{
  "updates": [
    {
      "userId": "alice",
      "profile": { "displayName": "Alice Updated" },
      "customFields": { "vip": true }
    },
    {
      "userId": "bob",
      "profile": { "displayName": "Bob Updated" }
    }
  ]
}
```

**Response**:

```json
{
  "success": true,
  "data": {
    "total": 2,
    "succeeded": 2,
    "failed": 0,
    "errors": []
  }
}
```

***

### Rewards

#### POST /internal/rewards/bulk

Distribute rewards to multiple users (max 1,000 rewards per request).

**Authentication**: API Key (required)

**Permissions**: `rewards:write`

**Request Body**:

```json
{
  "rewards": [
    {
      "userId": "alice",
      "amount": 100,
      "currency": "points",
      "reason": "Monthly loyalty bonus",
      "metadata": { "campaign": "monthly_bonus_oct" }
    },
    {
      "userId": "bob",
      "amount": 50,
      "currency": "xp",
      "reason": "Referral reward"
    }
  ]
}
```

**Response**:

```json
{
  "success": true,
  "data": {
    "total": 2,
    "succeeded": 2,
    "failed": 0,
    "errors": []
  }
}
```

***

### User Search & Export

#### POST /internal/users/search

Search users with advanced filtering and pagination.

**Authentication**: API Key (required)

**Permissions**: `users:read`

**Request Body**:

```json
{
  "filters": {
    "email": { "contains": "example.com" },
    "tier": ["gold", "platinum"],
    "points": { "min": 1000, "max": 5000 },
    "customFields": { "vip": true },
    "createdAt": {
      "from": "2025-01-01T00:00:00Z",
      "to": "2025-12-31T23:59:59Z"
    }
  },
  "limit": 100,
  "lastEvaluatedKey": null
}
```

**Response**:

```json
{
  "success": true,
  "data": {
    "users": [
      {
        "userId": "alice",
        "email": "alice@example.com",
        "displayName": "Alice Smith",
        "tier": "gold",
        "metrics": { "points": 1500, "xp": 2300, "coins": 450 },
        "createdAt": "2025-01-15T10:00:00Z"
      }
    ],
    "count": 1,
    "lastEvaluatedKey": null,
    "hasMore": false
  }
}
```

#### POST /internal/users/export

Create an encrypted export job for users matching search criteria. Exports are encrypted with AES-256-GCM and auto-expire after 24 hours.

**Authentication**: API Key (required)

**Permissions**: `users:export`

**Request Body**:

```json
{
  "filters": {
    "tier": ["gold", "platinum"]
  },
  "format": "csv",
  "fields": ["userId", "email", "displayName", "metrics.points", "tier"],
  "encrypt": true,
  "notifyEmail": "admin@example.com"
}
```

**Response** (202 Accepted):

```json
{
  "success": true,
  "data": {
    "exportId": "export_abc123",
    "status": "processing",
    "expiresAt": "2025-10-07T12:00:00Z",
    "statusUrl": "/internal/exports/export_abc123"
  }
}
```

#### GET /internal/exports/{exportId}

Get export job status and download information.

**Authentication**: API Key (required)

**Permissions**: `users:read`

**Response**:

```json
{
  "success": true,
  "data": {
    "exportId": "export_abc123",
    "status": "completed",
    "format": "csv",
    "totalUsers": 1250,
    "fileSize": 524288,
    "createdBy": "API Client Name",
    "createdAt": "2025-10-06T12:00:00Z",
    "completedAt": "2025-10-06T12:05:00Z",
    "expiresAt": "2025-10-07T12:00:00Z",
    "isExpired": false,
    "downloadUrl": "https://exports.s3.amazonaws.com/...",
    "password": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
  }
}
```

{% hint style="info" %}
**Export Status Values**:

* `processing` - Export is being generated
* `completed` - Export is ready for download
* `failed` - Export generation failed
* `expired` - Export has passed its 24-hour TTL
  {% endhint %}

{% hint style="warning" %}
**Download URL and password are only included when status is `completed` and export is not expired.**
{% endhint %}

***

## Authentication

### Public API - JWT Tokens

Public endpoints require a JWT Bearer token:

```bash
Authorization: Bearer {jwt_token}
X-Monterosa-Org-ID: {organization_id}
```

JWT tokens should include:

* `sub`: User ID
* `orgId`: Organization ID
* `scope`: Permissions array (e.g., `["audience:read", "audience:write"]`)

### Private API - API Keys

Private endpoints require API key and secret:

```bash
X-API-Key: {api_key}
X-API-Secret: {api_secret}
X-Monterosa-Org-ID: {organization_id}
```

{% hint style="danger" %}
**Never expose API keys or secrets in client-side code.** Private endpoints are for backend-to-backend communication only.
{% endhint %}

***

## Rate Limits

| API Type | Requests/Minute | Requests/Hour | Burst |
| -------- | --------------- | ------------- | ----- |
| Public   | 100             | 1,000         | 20    |
| Private  | 10,000          | 100,000       | 200   |

## Batch Operation Limits

| Operation                   | Maximum Items |
| --------------------------- | ------------- |
| User IDs per batch get      | 100           |
| Profile updates per batch   | 1,000         |
| Actions per bulk submit     | 1,000         |
| Rewards per bulk distribute | 1,000         |
| Users per export            | 1,000,000     |

***

## Error Responses

All endpoints return errors in this format:

```json
{
  "success": false,
  "error": {
    "message": "Error description",
    "code": "ERROR_CODE"
  }
}
```

**Common HTTP Status Codes**:

* `400` - Bad Request (invalid parameters)
* `401` - Unauthorized (missing or invalid auth)
* `403` - Forbidden (insufficient permissions)
* `404` - Not Found
* `429` - Too Many Requests (rate limit exceeded)
* `500` - Internal Server Error

***

## Export Feature Details

### Encryption

Exports are encrypted using AES-256-GCM with:

* Auto-generated 32-character password
* Random salt and initialization vector
* Authentication tag for integrity verification

### File Format

Encrypted files use the format: `{salt}:{iv}:{authTag}:{encryptedData}`

### Expiration

* Exports expire 24 hours after creation (configurable)
* DynamoDB TTL automatically deletes expired job records
* S3 lifecycle policy deletes files after 2 days

### Processing

1. Export job created with status `processing`
2. Scheduled Lambda (every 5 minutes) processes pending exports
3. Users queried and data formatted (CSV or JSON)
4. Content encrypted if requested
5. File uploaded to S3
6. Email sent with download URL and password
7. Job status updated to `completed`

### Decryption

See the [Data Export Guide](/mic/reference/services/audience-api/data-export-guide.md) for decryption instructions.

***

## SDK Support

The Monterosa SDK provides wrapper functions for all Audience API endpoints with automatic:

* Token refresh and management
* Error handling and retry logic
* Request rate limiting
* Response caching

**Recommended**: Use the SDK for production applications instead of calling the API directly.

***

## Additional Resources

* [Authentication Guide](/mic/reference/services/audience-api/authentication.md)
* [Batched Operations](https://github.com/MonterosaAdmin/gitbook-docs/blob/main/extensions/audience-api/batched-operations.md)
* [Data Export Guide](/mic/reference/services/audience-api/data-export-guide.md)
* [SDK Documentation](https://github.com/MonterosaAdmin/gitbook-docs/blob/main/developer-guide/sdk/README.md)
* [API Changelog](https://github.com/MonterosaAdmin/gitbook-docs/blob/main/release-notes/README.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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://products.monterosa.co/mic/reference/services/audience-api.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
