API Documentation - dinesh-git17/my-progress-planner GitHub Wiki

Complete reference for My Progress Planner REST API endpoints.

๐Ÿ”— Base URL

Development: http://localhost:3000/api
Production: https://your-domain.com/api

๐Ÿ” Authentication

Most endpoints require user authentication via Supabase JWT tokens.

Headers

Authorization: Bearer <supabase_jwt_token>
Content-Type: application/json

Response Format

All API responses follow this consistent structure:

interface APIResponse<T> {
  data: T | null;
  error: string | null;
  meta?: {
    total?: number;
    page?: number;
    limit?: number;
  };
}

๐Ÿ“Š Core Endpoints

๐Ÿฝ๏ธ Meals API

Get Today's Meals

GET /api/meals/today

Response:

{
  "data": {
    "breakfast": {
      "id": "uuid",
      "content": "Oatmeal with berries",
      "ai_response": "What a nutritious start to your day! ๐Ÿ’•",
      "logged_at": "2025-01-15T08:30:00Z"
    },
    "lunch": null,
    "dinner": null
  },
  "error": null
}

Log a Meal

POST /api/meals/log

Request Body:

{
  "mealType": "breakfast" | "lunch" | "dinner",
  "content": "Scrambled eggs with toast"
}

Response:

{
  "data": {
    "meal": {
      "id": "uuid",
      "content": "Scrambled eggs with toast",
      "ai_response": "Perfect protein to fuel your morning! ๐ŸŒŸ",
      "logged_at": "2025-01-15T08:30:00Z"
    }
  },
  "error": null
}

Check Meal Status

GET /api/meals/check?type=breakfast

Response:

{
  "data": {
    "exists": true,
    "content": "Oatmeal with berries",
    "logged_at": "2025-01-15T08:30:00Z"
  },
  "error": null
}

๐Ÿ”ฅ Streak API

Get Current Streak

GET /api/streak

Response:

{
  "data": {
    "current_streak": 7,
    "best_streak": 14,
    "streak_start_date": "2025-01-08",
    "total_days": 45
  },
  "error": null
}

๐Ÿ“‹ Summaries API

Get Daily Summaries

GET /api/summaries?page=1&limit=10

Response:

{
  "data": [
    {
      "id": "uuid",
      "summary_date": "2025-01-15",
      "content": "You had an amazing day with all three meals logged! ๐ŸŽ‰",
      "meals_count": 3,
      "created_at": "2025-01-15T23:00:00Z"
    }
  ],
  "meta": {
    "total": 25,
    "page": 1,
    "limit": 10
  },
  "error": null
}

Get Specific Summary

GET /api/summaries/2025-01-15

Response:

{
  "data": {
    "summary_date": "2025-01-15",
    "content": "You had an amazing day with all three meals logged! ๐ŸŽ‰",
    "meals_count": 3,
    "meals": [
      {
        "meal_type": "breakfast",
        "content": "Oatmeal with berries",
        "logged_at": "2025-01-15T08:30:00Z"
      }
    ]
  },
  "error": null
}

๐Ÿค– AI Integration

Generate AI Response

POST /api/ai/chat

Request Body:

{
  "mealType": "breakfast",
  "content": "Greek yogurt with granola",
  "context": {
    "streak": 5,
    "previousMeals": [],
    "timeOfDay": "morning"
  }
}

Response:

{
  "data": {
    "response": "Greek yogurt with granola sounds absolutely delicious! ๐Ÿ’•",
    "metadata": {
      "tokens_used": 45,
      "model": "gpt-4",
      "response_time_ms": 1250
    }
  },
  "error": null
}

Get Daily Quote

GET /api/ai/quote

Response:

{
  "data": {
    "quote": "Every meal is an opportunity to nourish yourself with love! ๐Ÿ’•",
    "cached": true
  },
  "error": null
}

๐Ÿ‘ค User API

Get User Profile

GET /api/user/profile

Response:

{
  "data": {
    "id": "uuid",
    "name": "John Doe",
    "email": "[email protected]",
    "friend_code": "LOVE123",
    "created_at": "2025-01-01T00:00:00Z"
  },
  "error": null
}

Update User Name

PUT /api/user/name

Request Body:

{
  "name": "John Smith"
}

Get Friend Code

GET /api/user/friend-code

Response:

{
  "data": {
    "friend_code": "LOVE123"
  },
  "error": null
}

๐Ÿ‘ฅ Friends API

Search Friends

GET /api/friends/search?code=LOVE456

Response:

{
  "data": {
    "user": {
      "name": "Jane Doe",
      "friend_code": "LOVE456"
    }
  },
  "error": null
}

Get Friends List

GET /api/friends

Response:

{
  "data": [
    {
      "friend_code": "LOVE456",
      "name": "Jane Doe",
      "added_at": "2025-01-10T00:00:00Z"
    }
  ],
  "error": null
}

๐Ÿ”” Push Notifications

Subscribe to Notifications

POST /api/notifications/subscribe

Request Body:

{
  "subscription": {
    "endpoint": "https://fcm.googleapis.com/fcm/send/...",
    "keys": {
      "p256dh": "key_data",
      "auth": "auth_data"
    }
  }
}

Send Test Notification

POST /api/notifications/test

โš™๏ธ Admin API

Note: Requires admin authentication via ADMIN_PASSWORD

Get System Stats

GET /api/admin/stats

Headers:

Authorization: Bearer <admin_password>

Response:

{
  "data": {
    "total_users": 1250,
    "total_meals": 15680,
    "active_users_today": 245,
    "meals_today": 892,
    "avg_streak": 5.2
  },
  "error": null
}

Get All Summaries

GET /api/admin/summaries

Manual Meal Log (Testing)

POST /api/admin/log-meal

Request Body:

{
  "userId": "user_uuid",
  "mealType": "breakfast",
  "content": "Test meal for debugging"
}

๐Ÿ”„ Cron Jobs

Automated Meal Reminders

Lunch Reminder

GET /api/cron/lunch
  • Schedule: Daily at 6:00 PM UTC (18:00)
  • Purpose: Send lunch logging reminders

Dinner Reminder

GET /api/cron/dinner
  • Schedule: Daily at 1:00 AM UTC (01:00)
  • Purpose: Send dinner logging reminders

Authentication:

Authorization: Bearer <CRON_SECRET>

๐Ÿ“Š Error Codes

Code Message Description
400 Bad Request Invalid request data
401 Unauthorized Missing or invalid authentication
403 Forbidden Insufficient permissions
404 Not Found Resource doesn't exist
409 Conflict Meal already logged for this type/date
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Server-side error

Example Error Response

{
  "data": null,
  "error": "Meal already logged for breakfast today"
}

๐Ÿ”’ Rate Limiting

  • General API: 100 requests/hour per user
  • AI Endpoints: 20 requests/hour per user
  • Admin Endpoints: 200 requests/hour per IP

๐Ÿงช Testing

Using curl

# Get today's meals
curl -H "Authorization: Bearer YOUR_JWT" \
     https://your-domain.com/api/meals/today

# Log a meal
curl -X POST \
     -H "Authorization: Bearer YOUR_JWT" \
     -H "Content-Type: application/json" \
     -d '{"mealType":"breakfast","content":"Pancakes"}' \
     https://your-domain.com/api/meals/log

Using JavaScript/TypeScript

// Utility function for API calls
async function apiCall<T>(endpoint: string, options?: RequestInit): Promise<T> {
  const response = await fetch(`/api${endpoint}`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
      ...options?.headers,
    },
    ...options,
  });

  return response.json();
}

// Example usage
const meals = await apiCall('/meals/today');
const result = await apiCall('/meals/log', {
  method: 'POST',
  body: JSON.stringify({
    mealType: 'breakfast',
    content: 'Oatmeal with berries'
  })
});

๐Ÿ”„ Webhooks (Future Feature)

Planned webhook endpoints for external integrations:

  • POST /api/webhooks/meal-logged - Triggered when meal is logged
  • POST /api/webhooks/streak-milestone - Triggered on streak milestones
  • POST /api/webhooks/summary-generated - Triggered when daily summary is created

๐Ÿ“ฑ PWA API Integration

Service Worker Cache Strategy

  • Cache First: /api/ai/quote, /api/user/name
  • Network First: /api/meals/log, /api/ai/chat
  • Stale While Revalidate: /api/meals/check, /api/streak

Background Sync

Failed API calls are queued and retried when connection is restored:

  • Meal logging
  • AI response generation
  • User profile updates

๐Ÿ“ž Support