# myLife API Documentation - Phase 1 MVP

**Base URL:** `http://api.mylifeapp.local/api/v1` (replace with actual domain)  
**API Version:** v1  
**Authentication:** Bearer Token (Laravel Sanctum)  
**Last Updated:** April 15, 2026

---

## Table of Contents

1. [Authentication](#authentication)
2. [User Profile](#user-profile)
3. [Medications](#medications)
4. [Education Content](#education-content)
5. [Offline Sync](#offline-sync)
6. [Error Handling](#error-handling)
7. [Integration Guide](#integration-guide)

---

## Authentication

### Register User

**Endpoint:** `POST /auth/register`  
**Authentication:** None  
**Rate Limit:** 10 requests/hour per IP

**Request Body:**
```json
{
  "name": "Jane Doe",
  "email": "jane@example.com",
  "password": "SecurePassword123",
  "password_confirmation": "SecurePassword123",
  "phone": "+234801234567",
  "lmp_date": "2026-01-15",
  "consent_given_for_data_sharing": true
}
```

**Response (201):**
```json
{
  "message": "User registered successfully",
  "user": {
    "id": 1,
    "name": "Jane Doe",
    "email": "jane@example.com",
    "phone": "+234801234567"
  },
  "token": "eyJ0eXAiOiJKV1QiLCJhbGc..."
}
```

**Validation Rules:**
- `name`: required, string, max 255
- `email`: required, email, unique
- `password`: required, min 8 chars, must have confirmation
- `phone`: optional, max 20
- `lmp_date`: optional, must be before today
- `consent_given_for_data_sharing`: optional, boolean

---

### Login

**Endpoint:** `POST /auth/login`  
**Authentication:** None

**Request Body:**
```json
{
  "email": "jane@example.com",
  "password": "SecurePassword123"
}
```

**Response (200):**
```json
{
  "message": "Login successful",
  "user": {
    "id": 1,
    "name": "Jane Doe",
    "email": "jane@example.com",
    "phone": "+234801234567"
  },
  "token": "eyJ0eXAiOiJKV1QiLCJhbGc..."
}
```

---

### Get Current User

**Endpoint:** `GET /auth/user`  
**Authentication:** Required (Bearer Token)

**Response (200):**
```json
{
  "user": {
    "id": 1,
    "name": "Jane Doe",
    "email": "jane@example.com",
    "phone": "+234801234567",
    "email_verified_at": null,
    "created_at": "2026-04-15T10:30:00Z",
    "user_profile": {
      "id": 1,
      "lmp_date": "2026-01-15",
      "calculated_due_date": "2026-10-21",
      "trimester": 2,
      "art_regimen_id": 3,
      "consent_given_for_data_sharing": true
    }
  }
}
```

---

### Logout

**Endpoint:** `POST /auth/logout`  
**Authentication:** Required

**Response (200):**
```json
{
  "message": "Logged out successfully"
}
```

---

## User Profile

### Get Profile

**Endpoint:** `GET /profile`  
**Authentication:** Required

**Response (200):**
```json
{
  "profile": {
    "id": 1,
    "user_id": 1,
    "lmp_date": "2026-01-15",
    "calculated_due_date": "2026-10-21",
    "trimester": 2,
    "art_regimen_id": 3,
    "art_regimen": {
      "id": 3,
      "name": "TDF/FTC/DTG",
      "description": "Tenofovir/Emtricitabine/Dolutegravir",
      "components": ["Tenofovir 300mg", "Emtricitabine 200mg", "Dolutegravir 50mg"]
    },
    "consent_given_for_data_sharing": true,
    "created_at": "2026-04-15T10:30:00Z",
    "updated_at": "2026-04-15T10:30:00Z"
  }
}
```

---

### Update Profile

**Endpoint:** `PUT /profile`  
**Authentication:** Required

**Request Body:**
```json
{
  "lmp_date": "2026-01-20",
  "art_regimen_id": 5,
  "clinical_notes": "Patient showing good adherence"
}
```

**Response (200):**
```json
{
  "message": "Profile updated successfully",
  "profile": {
    "id": 1,
    "user_id": 1,
    "lmp_date": "2026-01-20",
    "calculated_due_date": "2026-10-26",
    "trimester": 2,
    "art_regimen_id": 5,
    "updated_at": "2026-04-15T11:30:00Z"
  }
}
```

---

### Get Health Metadata

**Endpoint:** `GET /profile/health-metadata`  
**Authentication:** Required  
**Use:** Get all pregnancy and treatment information needed for the app UI

**Response (200):**
```json
{
  "lmp_date": "2026-01-15",
  "due_date": "2026-10-21",
  "weeks_pregnant": 13,
  "trimester": 2,
  "trimester_guidance": "Second Trimester (Weeks 13-27): Continue ART regimen, monitor health, prepare for third trimester.",
  "art_regimen": {
    "id": 3,
    "name": "TDF/FTC/DTG",
    "description": "Tenofovir/Emtricitabine/Dolutegravir",
    "components": ["Tenofovir 300mg", "Emtricitabine 200mg", "Dolutegravir 50mg"]
  },
  "consent_status": {
    "given": true,
    "timestamp": "2026-04-15T10:30:00Z",
    "version": "1.0"
  }
}
```

---

## Medications

### List All Medications

**Endpoint:** `GET /medications`  
**Authentication:** Required

**Response (200):**
```json
{
  "medications": [
    {
      "id": 1,
      "user_id": 1,
      "medication_name": "Tenofovir 300mg",
      "frequency": "daily",
      "times_per_day": 1,
      "schedule_times": ["08:00"],
      "start_date": "2026-01-15",
      "end_date": null,
      "is_active": true,
      "created_at": "2026-04-15T10:30:00Z",
      "updated_at": "2026-04-15T10:30:00Z"
    }
  ],
  "count": 1
}
```

---

### Create Medication Reminder

**Endpoint:** `POST /medications`  
**Authentication:** Required

**Request Body:**
```json
{
  "medication_name": "Emtricitabine 200mg",
  "frequency": "daily",
  "times_per_day": 1,
  "schedule_times": ["20:00"],
  "start_date": "2026-04-15",
  "end_date": null
}
```

**Response (201):**
```json
{
  "message": "Medication reminder created successfully",
  "medication": {
    "id": 2,
    "user_id": 1,
    "medication_name": "Emtricitabine 200mg",
    "frequency": "daily",
    "times_per_day": 1,
    "schedule_times": ["20:00"],
    "start_date": "2026-04-15",
    "is_active": true,
    "created_at": "2026-04-15T12:00:00Z"
  }
}
```

---

### Log Dose Taken

**Endpoint:** `POST /medications/{id}/log`  
**Authentication:** Required  
**Use:** Record that a dose was taken (called when user clicks "I took my dose")

**Request Body:**
```json
{
  "status": "taken",
  "notes": "Took with food",
  "taken_at": "2026-04-15T08:15:00Z",
  "device_id": "550e8400-e29b-41d4-a716-446655440000"
}
```

**Response (201):**
```json
{
  "message": "Dose logged successfully",
  "log": {
    "id": 5,
    "medication_reminder_id": 1,
    "user_id": 1,
    "taken_at": "2026-04-15T08:15:00Z",
    "status": "taken",
    "notes": "Took with food",
    "device_id": "550e8400-e29b-41d4-a716-446655440000",
    "created_at": "2026-04-15T12:00:00Z",
    "updated_at": "2026-04-15T12:00:00Z"
  }
}
```

---

### Get Adherence Statistics

**Endpoint:** `GET /medications/{id}/adherence`  
**Authentication:** Required

**Response (200):**
```json
{
  "medication_id": 1,
  "medication_name": "Tenofovir 300mg",
  "adherence_weekly": 85.5,
  "adherence_monthly": 89.5,
  "adherence_all_time": 92.1,
  "current_streak_days": 7,
  "total_doses_logged": 45,
  "recent_logs": [
    {
      "date": "2026-04-15",
      "status": "taken",
      "notes": null
    },
    {
      "date": "2026-04-14",
      "status": "taken",
      "notes": null
    }
  ],
  "status": "active"
}
```

---

### Get Adherence Summary

**Endpoint:** `GET /medications/adherence/summary`  
**Authentication:** Required  
**Use:** Get overview of all medications' adherence

**Response (200):**
```json
{
  "total_active_medications": 3,
  "average_adherence_monthly": 87.3,
  "medications": [
    {
      "medication_id": 1,
      "medication_name": "Tenofovir 300mg",
      "adherence_weekly": 85.5,
      "adherence_monthly": 89.5,
      "current_streak_days": 7,
      "total_doses_logged": 45,
      "status": "active"
    }
  ]
}
```

---

## Education Content

### List Education Modules

**Endpoint:** `GET /education/modules`  
**Authentication:** Not Required  
**Query Parameters:**
- `category` - Filter by category
- `trimester` - Filter by trimester (1, 2, 3, or 0 for all)
- `language` - Filter by language code (default: en)
- `search` - Search by title
- `page` - Pagination (default: 1)

**Example:** `GET /education/modules?trimester=2&category=nutrition`

**Response (200):**
```json
{
  "modules": [
    {
      "id": 1,
      "title": "Nutrition During Pregnancy",
      "slug": "nutrition-during-pregnancy",
      "description": "Guidelines for healthy eating while pregnant",
      "content_type": "text",
      "category": "nutrition",
      "trimester_relevant": 2,
      "version": 1,
      "language": "en"
    }
  ],
  "pagination": {
    "total": 25,
    "per_page": 20,
    "current_page": 1,
    "last_page": 2
  }
}
```

---

### Get Module Content

**Endpoint:** `GET /education/modules/{id}`  
**Authentication:** Not Required

**Response (200):**
```json
{
  "module": {
    "id": 1,
    "title": "Nutrition During Pregnancy",
    "slug": "nutrition-during-pregnancy",
    "description": "Guidelines for healthy eating while pregnant",
    "content_type": "text",
    "content": "Detailed module content...",
    "category": "nutrition",
    "trimester_relevant": 2,
    "version": 1,
    "language": "en",
    "quizzes": 1,
    "created_at": "2026-04-15T10:00:00Z"
  }
}
```

---

### Get Quiz

**Endpoint:** `GET /education/quizzes/{quizId}`  
**Authentication:** Required

**Response (200):**
```json
{
  "quiz": {
    "id": 1,
    "title": "Nutrition Quiz",
    "description": "Test your knowledge about nutrition in pregnancy",
    "passing_score": 70,
    "total_questions": 5
  },
  "questions": [
    {
      "id": 1,
      "question_text": "Which nutrient is most important for fetal development?",
      "options": {
        "a": "Protein",
        "b": "Fat",
        "c": "Carbohydrates",
        "d": "Sugar"
      },
      "question_type": "single_choice",
      "order": 0
    }
  ]
}
```

**Note:** Correct answers are intentionally omitted to prevent cheating.

---

### Submit Quiz Answers

**Endpoint:** `POST /education/quizzes/{quizId}/submit`  
**Authentication:** Required

**Request Body:**
```json
{
  "answers": [
    {
      "question_id": 1,
      "answer": "a"
    },
    {
      "question_id": 2,
      "answer": "b"
    }
  ]
}
```

**Response (200):**
```json
{
  "score": 80,
  "passed": true,
  "correct": 4,
  "total": 5,
  "passing_score": 70,
  "feedback": "Congratulations! You passed the quiz."
}
```

---

## Offline Sync

### Initialize Sync

The sync endpoint is the most important for offline-first functionality. Call this periodically (every 6 hours or when user opens the app).

**Endpoint:** `POST /sync`  
**Authentication:** Required

**Request Body:**
```json
{
  "device_id": "550e8400-e29b-41d4-a716-446655440000",
  "last_sync_timestamp": 1713181800,
  "changed_records": [
    {
      "type": "medication_log",
      "data": {
        "medication_reminder_id": 1,
        "taken_at": "2026-04-15T08:15:00Z",
        "status": "taken",
        "notes": "Offline log",
        "device_id": "550e8400-e29b-41d4-a716-446655440000"
      },
      "timestamp": 1713181800
    }
  ]
}
```

**Response (200):**
```json
{
  "status": "success",
  "profile": {
    "id": 1,
    "user_id": 1,
    "lmp_date": "2026-01-15",
    "calculated_due_date": "2026-10-21",
    "trimester": 2,
    "art_regimen_id": 3,
    "consent_given_for_data_sharing": true,
    "updated_at": 1713181800
  },
  "medications": [
    {
      "id": 1,
      "medication_name": "Tenofovir 300mg",
      "frequency": "daily",
      "times_per_day": 1,
      "schedule_times": ["08:00"],
      "start_date": "2026-01-15",
      "is_active": true,
      "updated_at": 1713181800
    }
  ],
  "medication_logs": [
    {
      "id": 5,
      "medication_reminder_id": 1,
      "taken_at": 1713181800,
      "status": "taken",
      "notes": "Dose logged",
      "device_id": "550e8400-e29b-41d4-a716-446655440000",
      "created_at": 1713181800,
      "updated_at": 1713181800
    }
  ],
  "server_timestamp": 1713185400,
  "next_sync_recommended_at": 1713206400,
  "merge_conflicts": [],
  "sync_status": "complete"
}
```

---

### Check Sync Needed

**Endpoint:** `POST /sync/check`  
**Authentication:** Required

**Request Body:**
```json
{
  "device_id": "550e8400-e29b-41d4-a716-446655440000",
  "last_check_timestamp": 1713181800
}
```

**Response (200):**
```json
{
  "sync_needed": true,
  "last_sync_timestamp": 1713181800,
  "reason": "new_data_available",
  "recommended_action": "sync_now"
}
```

---

### Get Sync Health

**Endpoint:** `GET /sync/health`  
**Authentication:** Required  
**Use:** Debug endpoint - shows which devices are syncing properly

**Response (200):**
```json
{
  "total_devices": 2,
  "devices": [
    {
      "device_id": "550e8400-e29b-41d4-a716-446655440000",
      "last_sync": "2026-04-15 12:30:00",
      "hours_since_sync": 2,
      "is_active": true,
      "records_synced": 15
    }
  ]
}
```

---

## Error Handling

### Standard Error Response

All errors return JSON with status code and message:

```json
{
  "message": "Validation failed",
  "errors": {
    "email": ["The email field is required."],
    "password": ["The password must be at least 8 characters."]
  }
}
```

### Common Error Codes

| Status | Message | Resolution |
|--------|---------|-----------|
| 401 | Unauthorized | Token missing or expired - login again |
| 403 | Forbidden | No permission to access resource |
| 404 | Not Found | Resource doesn't exist |
| 422 | Validation Failed | Check request body format |
| 429 | Too Many Requests | Wait before making more requests |
| 500 | Server Error | Contact support |

---

## Integration Guide

### Mobile App Setup

1. **Install UUID library** for device ID generation
2. **Generate device UUID** on first app launch: `550e8400-e29b-41d4-a716-446655440000`
3. **Store device UUID** in secure local storage

### Registration Flow

```
1. User fills registration form
2. POST /auth/register → receive token
3. Store token in secure storage
4. Initialize local database with user data
5. Ready to use app offline
```

### Offline Medication Logging

```
1. User clicks "I took my dose" button
2. Create local MedicationLog entry with:
   - medication_reminder_id
   - current timestamp
   - device_id
   - status: "taken"
3. Queue for sync (store in local queue)
4. Show confirmation message
```

### Sync Flow (Run Every 6 Hours or on App Launch)

```
1. Check if online → if offline, skip
2. Get all queued offline records from local DB
3. POST /sync with:
   - device_id
   - last_sync_timestamp (from last sync)
   - changed_records (queued logs)
4. Receive server updates
5. Merge results:
   - Update local profile
   - Update local medications
   - Handle merge conflicts (server-wins)
6. Clear offline queue
7. Update last_sync_timestamp
8. Notify UI of updates
```

### Sample Code (TypeScript/React Native)

```typescript
// Generate device ID (first launch only)
function getDeviceId(): string {
  let deviceId = localStorage.getItem('device_id');
  if (!deviceId) {
    deviceId = generateUUID();
    localStorage.setItem('device_id', deviceId);
  }
  return deviceId;
}

// Sync function
async function syncWithServer() {
  const token = getToken();
  const deviceId = getDeviceId();
  const lastSync = getLastSyncTimestamp();
  const queuedRecords = getQueuedRecords();

  const response = await fetch(`${API_BASE}/sync`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      device_id: deviceId,
      last_sync_timestamp: lastSync,
      changed_records: queuedRecords,
    }),
  });

  const data = await response.json();

  // Merge results into local database
  if (data.status === 'success') {
    mergeServerData(data);
    setLastSyncTimestamp(data.server_timestamp);
    clearQueuedRecords();
  }
}
```

---

## Support & Contact

For API issues or feature requests, contact the backend team at: `backend@mylifeapp.local`

