# Notification API Reference

Complete reference for Lilith's notification system including push
notifications, email, in-app messaging, and webhook delivery.

---

## Send Notifications

### Send Single Notification

```http
POST /v1/notifications/send
```

**Request Body:**

```json
{
  "user_id": "user_abc123",
  "channel": "push",
  "template_id": "meditation_reminder",
  "data": {
    "title": "Time for your evening meditation",
    "body": "Your daily practice awaits",
    "deep_link": "lilith://meditation/evening",
    "image_url": "https://cdn.lilith.app/images/sunset.jpg"
  },
  "priority": "normal",
  "ttl_seconds": 3600,
  "collapse_key": "meditation_reminder"
}
```

**Response:**

```json
{
  "notification_id": "notif_xyz789",
  "status": "sent",
  "channel": "push",
  "sent_at": "2026-01-03T18:00:00Z",
  "delivery_estimate": "2026-01-03T18:00:05Z"
}
```

### Send Batch Notifications

```http
POST /v1/notifications/send-batch
```

**Request Body:**

```json
{
  "notifications": [
    {
      "user_id": "user_001",
      "channel": "push",
      "template_id": "daily_reminder"
    },
    {
      "user_id": "user_002",
      "channel": "email",
      "template_id": "weekly_digest"
    }
  ],
  "batch_options": {
    "respect_quiet_hours": true,
    "digest_if_multiple": true
  }
}
```

**Response:**

```json
{
  "batch_id": "batch_abc",
  "total": 2,
  "queued": 2,
  "failed": 0,
  "notifications": [
    { "notification_id": "notif_001", "status": "queued" },
    { "notification_id": "notif_002", "status": "queued" }
  ]
}
```

### Test Notification

```http
POST /v1/notifications/test
```

Send a test notification (staff only, sandbox mode).

**Request Body:**

```json
{
  "channel": "push",
  "template_id": "test_notification",
  "device_token": "test_token_123"
}
```

---

## Push Notifications

### Register Device

```http
POST /v1/notifications/push/devices
```

**Request Body:**

```json
{
  "platform": "ios",
  "device_token": "apns_token_abc123",
  "app_version": "2.1.0",
  "os_version": "17.2",
  "device_model": "iPhone 15 Pro"
}
```

### List Devices

```http
GET /v1/notifications/push/devices
```

### Unregister Device

```http
DELETE /v1/notifications/push/devices/{deviceId}
```

### Push Notification Payload Structure

**iOS (APNS):**

```json
{
  "aps": {
    "alert": {
      "title": "Meditation Reminder",
      "body": "Your practice awaits",
      "subtitle": "Evening Session"
    },
    "sound": "meditation_bell.wav",
    "badge": 1,
    "category": "MEDITATION_REMINDER",
    "mutable-content": 1
  },
  "deep_link": "lilith://meditation/evening",
  "image_url": "https://cdn.lilith.app/images/sunset.jpg"
}
```

**Android (FCM):**

```json
{
  "notification": {
    "title": "Meditation Reminder",
    "body": "Your practice awaits",
    "image": "https://cdn.lilith.app/images/sunset.jpg",
    "click_action": "OPEN_MEDITATION"
  },
  "data": {
    "deep_link": "lilith://meditation/evening",
    "notification_id": "notif_xyz"
  },
  "android": {
    "priority": "high",
    "notification": {
      "channel_id": "meditation_reminders",
      "sound": "meditation_bell"
    }
  }
}
```

---

## Notification Templates

### List Templates

```http
GET /v1/notification-templates
```

**Response:**

```json
{
  "templates": [
    {
      "template_id": "meditation_reminder",
      "name": "Meditation Reminder",
      "channels": ["push", "email"],
      "variables": ["user_name", "session_type", "duration"],
      "locales": ["en", "es", "fr", "de", "ja"],
      "category": "reminders",
      "created_at": "2025-06-01T00:00:00Z"
    }
  ]
}
```

### Get Template

```http
GET /v1/notification-templates/{templateId}
```

**Response:**

```json
{
  "template_id": "meditation_reminder",
  "name": "Meditation Reminder",
  "content": {
    "push": {
      "title": "Time for {{session_type}} meditation",
      "body": "Hi {{user_name}}, your {{duration}}-minute practice awaits"
    },
    "email": {
      "subject": "Your meditation reminder",
      "html_template": "<html>...</html>",
      "text_template": "Hi {{user_name}}..."
    }
  },
  "variables": [
    {"name": "user_name", "type": "string", "required": true},
    {"name": "session_type", "type": "string", "default": "daily"},
    {"name": "duration", "type": "number", "default": 10}
  ],
  "locales": {
    "en": {...},
    "es": {...}
  }
}
```

### Create Template

```http
POST /v1/notification-templates
```

### Update Template

```http
PUT /v1/notification-templates/{templateId}
PATCH /v1/notification-templates/{templateId}
```

### Delete Template

```http
DELETE /v1/notification-templates/{templateId}
```

---

## User Preferences

### Get Notification Preferences

```http
GET /v1/users/{userId}/notification-preferences
```

**Response:**

```json
{
  "user_id": "user_abc123",
  "channels": {
    "push": {
      "enabled": true,
      "quiet_hours": { "start": "22:00", "end": "07:00" }
    },
    "email": { "enabled": true, "frequency": "daily_digest" },
    "sms": { "enabled": false }
  },
  "categories": {
    "meditation_reminders": { "enabled": true, "channels": ["push"] },
    "course_updates": { "enabled": true, "channels": ["push", "email"] },
    "community": { "enabled": false },
    "marketing": { "enabled": false }
  },
  "timezone": "America/New_York"
}
```

### Update Notification Preferences

```http
PUT /v1/users/{userId}/notification-preferences
PATCH /v1/users/{userId}/notification-preferences
```

---

## Delivery Status

### Get Delivery Status

```http
GET /v1/notifications/delivery-status/{notificationId}
```

**Response:**

```json
{
  "notification_id": "notif_xyz789",
  "status": "delivered",
  "channel": "push",
  "sent_at": "2026-01-03T18:00:00Z",
  "delivered_at": "2026-01-03T18:00:02Z",
  "read_at": "2026-01-03T18:05:00Z",
  "clicked_at": "2026-01-03T18:05:15Z",
  "device_info": {
    "platform": "ios",
    "app_version": "2.1.0"
  },
  "delivery_attempts": [
    {
      "attempt": 1,
      "timestamp": "2026-01-03T18:00:00Z",
      "status": "success",
      "provider_response": "accepted"
    }
  ]
}
```

---

## Analytics

### Delivery Analytics

```http
GET /v1/notifications/analytics/delivery
```

**Query Parameters:** | Parameter | Type | Description |
|-----------|------|-------------| | `start_date` | ISO8601 | Start of period |
| `end_date` | ISO8601 | End of period | | `channel` | string | Filter by
channel | | `template_id` | string | Filter by template | | `granularity` |
string | `hour`, `day`, `week` |

**Response:**

```json
{
  "period": {
    "start": "2026-01-01T00:00:00Z",
    "end": "2026-01-03T23:59:59Z"
  },
  "summary": {
    "total_sent": 150000,
    "delivered": 145000,
    "failed": 5000,
    "opened": 80000,
    "clicked": 25000,
    "delivery_rate": 0.967,
    "open_rate": 0.552,
    "click_rate": 0.172
  },
  "by_channel": {
    "push": {
      "sent": 100000,
      "delivered": 98000,
      "delivery_rate": 0.98
    },
    "email": {
      "sent": 50000,
      "delivered": 47000,
      "delivery_rate": 0.94
    }
  },
  "time_series": [
    { "timestamp": "2026-01-01T00:00:00Z", "sent": 5000, "delivered": 4850 }
  ]
}
```

---

## Webhooks

### Create Webhook

```http
POST /v1/notifications/webhooks
```

**Request Body:**

```json
{
  "url": "https://your-app.com/webhooks/notifications",
  "events": [
    "notification.sent",
    "notification.delivered",
    "notification.failed"
  ],
  "secret": "whsec_abc123",
  "enabled": true
}
```

### List Webhooks

```http
GET /v1/notifications/webhooks
```

### Get Webhook

```http
GET /v1/notifications/webhooks/{webhookId}
```

### Update Webhook

```http
PUT /v1/notifications/webhooks/{webhookId}
PATCH /v1/notifications/webhooks/{webhookId}
```

### Delete Webhook

```http
DELETE /v1/notifications/webhooks/{webhookId}
```

### Webhook Payload

```json
{
  "event": "notification.delivered",
  "timestamp": "2026-01-03T18:00:02Z",
  "data": {
    "notification_id": "notif_xyz789",
    "user_id": "user_abc123",
    "channel": "push",
    "template_id": "meditation_reminder",
    "delivered_at": "2026-01-03T18:00:02Z"
  },
  "signature": "sha256=abc123..."
}
```

### Webhook Events

| Event                       | Description                   |
| --------------------------- | ----------------------------- |
| `notification.sent`         | Notification sent to provider |
| `notification.delivered`    | Confirmed delivery            |
| `notification.failed`       | Delivery failed               |
| `notification.opened`       | User opened notification      |
| `notification.clicked`      | User clicked/tapped           |
| `notification.unsubscribed` | User unsubscribed             |

---

## Scheduling

### Schedule Notification

```http
POST /v1/notifications/schedule
```

**Request Body:**

```json
{
  "user_id": "user_abc123",
  "template_id": "meditation_reminder",
  "scheduled_at": "2026-01-04T18:00:00Z",
  "timezone": "America/New_York",
  "recurrence": {
    "type": "daily",
    "time": "18:00",
    "days": ["mon", "tue", "wed", "thu", "fri"]
  }
}
```

### List Scheduled Notifications

```http
GET /v1/notifications/scheduled
```

### Cancel Scheduled Notification

```http
DELETE /v1/notifications/scheduled/{scheduleId}
```

---

## In-App Notifications

### Get User Notifications

```http
GET /v1/users/{userId}/notifications
```

**Query Parameters:** | Parameter | Type | Description |
|-----------|------|-------------| | `status` | string | `unread`, `read`, `all`
| | `category` | string | Filter by category | | `limit` | number | Max results
|

### Mark as Read

```http
POST /v1/users/{userId}/notifications/{notificationId}/read
```

### Mark All as Read

```http
POST /v1/users/{userId}/notifications/read-all
```

### Delete Notification

```http
DELETE /v1/users/{userId}/notifications/{notificationId}
```

---

## Health Check

```http
GET /v1/notifications/health
```

**Response:**

```json
{
  "status": "healthy",
  "providers": {
    "apns": { "status": "healthy", "latency_ms": 45 },
    "fcm": { "status": "healthy", "latency_ms": 62 },
    "ses": { "status": "healthy", "latency_ms": 120 }
  },
  "queue_depth": 150,
  "processing_rate": 500
}
```

---

## Error Codes

| Code                                | Description                      |
| ----------------------------------- | -------------------------------- |
| `notification.invalid_template`     | Template not found or invalid    |
| `notification.invalid_channel`      | Unsupported notification channel |
| `notification.user_unsubscribed`    | User has unsubscribed            |
| `notification.quiet_hours`          | Blocked by quiet hours           |
| `notification.rate_limited`         | Rate limit exceeded              |
| `notification.delivery_failed`      | Provider delivery failure        |
| `notification.invalid_device_token` | Invalid push token               |

---

## Rate Limits

| Endpoint    | Limit                           |
| ----------- | ------------------------------- |
| Send single | 100 req/min                     |
| Send batch  | 10 req/min (max 1000 per batch) |
| Templates   | 50 req/min                      |
| Analytics   | 20 req/min                      |

---

## Related Documentation

- [Notification Service README](/services/notification/README.md)
- [Push Notification Setup Guide](/docs/guides/push-notifications.md)
- [Email Templates Guide](/docs/guides/email-templates.md)
