Skip to content

Latest commit

Β 

History

History
749 lines (663 loc) Β· 13.9 KB

api-reference.md

File metadata and controls

749 lines (663 loc) Β· 13.9 KB

πŸ”Œ API Reference

This document provides comprehensive documentation for the OpenLN API endpoints, including authentication, request/response formats, and usage examples.

πŸ“‹ Base Information

  • Base URL: https://api.openln.dev/api/v1 (Production)
  • Development URL: http://localhost:5000/api/v1
  • Content Type: application/json
  • Authentication: JWT Bearer tokens

πŸ” Authentication

Authentication Header

Authorization: Bearer <your-jwt-token>

Token Format

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "user_id",
    "email": "user@example.com",
    "role": "user"
  },
  "expiresIn": "7d"
}

πŸ“ Response Format

Success Response

{
  "success": true,
  "data": {
    // Response data
  },
  "message": "Operation completed successfully"
}

Error Response

{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Error description",
    "details": {} // Additional error details
  }
}

Pagination Response

{
  "success": true,
  "data": {
    "items": [], // Array of items
    "pagination": {
      "currentPage": 1,
      "totalPages": 10,
      "totalItems": 100,
      "itemsPerPage": 10,
      "hasNext": true,
      "hasPrev": false
    }
  }
}

πŸ‘€ Authentication Endpoints

Register User

POST /auth/register

Request Body:

{
  "email": "user@example.com",
  "password": "securePassword123",
  "name": "John Doe",
  "agreeToTerms": true
}

Response:

{
  "success": true,
  "data": {
    "token": "jwt-token-here",
    "user": {
      "id": "60f7b3b3b3b3b3b3b3b3b3b3",
      "email": "user@example.com",
      "name": "John Doe",
      "role": "user",
      "profile": {
        "avatar": null,
        "bio": null,
        "preferences": {}
      },
      "createdAt": "2023-07-25T10:00:00.000Z"
    }
  },
  "message": "User registered successfully"
}

Login User

POST /auth/login

Request Body:

{
  "email": "user@example.com",
  "password": "securePassword123"
}

Response: Same as register response

Google OAuth Login

GET /auth/google

Redirects to Google OAuth consent screen.

Refresh Token

POST /auth/refresh

Request Body:

{
  "refreshToken": "refresh-token-here"
}

Logout

POST /auth/logout

Headers: Authorization: Bearer <token>

Forgot Password

POST /auth/forgot-password

Request Body:

{
  "email": "user@example.com"
}

Reset Password

POST /auth/reset-password

Request Body:

{
  "token": "reset-token-from-email",
  "newPassword": "newSecurePassword123"
}

πŸ‘₯ User Management Endpoints

Get Current User

GET /users/me

Headers: Authorization: Bearer <token>

Response:

{
  "success": true,
  "data": {
    "id": "user_id",
    "email": "user@example.com",
    "name": "John Doe",
    "profile": {
      "avatar": "avatar-url",
      "bio": "User bio",
      "location": "City, Country",
      "website": "https://example.com"
    },
    "preferences": {
      "learningStyle": "visual",
      "notifications": {
        "email": true,
        "push": false
      },
      "theme": "light"
    },
    "stats": {
      "coursesCompleted": 5,
      "totalLearningTime": 1200,
      "currentStreak": 7
    }
  }
}

Update User Profile

PUT /users/me

Headers: Authorization: Bearer <token>

Request Body:

{
  "name": "Updated Name",
  "profile": {
    "bio": "Updated bio",
    "location": "New City, Country"
  },
  "preferences": {
    "learningStyle": "auditory",
    "notifications": {
      "email": false
    }
  }
}

Upload Avatar

POST /users/me/avatar

Headers:

  • Authorization: Bearer <token>
  • Content-Type: multipart/form-data

Request Body:

avatar: <file>

Delete User Account

DELETE /users/me

Headers: Authorization: Bearer <token>

πŸ“š Course Endpoints

Get All Courses

GET /courses?page=1&limit=10&category=programming&difficulty=beginner

Query Parameters:

  • page (optional): Page number (default: 1)
  • limit (optional): Items per page (default: 10, max: 50)
  • category (optional): Filter by category
  • difficulty (optional): Filter by difficulty (beginner, intermediate, advanced)
  • search (optional): Search in title and description

Response:

{
  "success": true,
  "data": {
    "items": [
      {
        "id": "course_id",
        "title": "Introduction to React",
        "description": "Learn React fundamentals",
        "thumbnail": "thumbnail-url",
        "difficulty": "beginner",
        "category": "programming",
        "duration": 1200,
        "modules": 8,
        "rating": 4.5,
        "enrollments": 1500,
        "instructor": {
          "id": "instructor_id",
          "name": "Jane Smith",
          "avatar": "avatar-url"
        },
        "tags": ["react", "javascript", "frontend"],
        "createdAt": "2023-07-01T00:00:00.000Z"
      }
    ],
    "pagination": {
      "currentPage": 1,
      "totalPages": 5,
      "totalItems": 45,
      "itemsPerPage": 10
    }
  }
}

Get Course by ID

GET /courses/:id

Response:

{
  "success": true,
  "data": {
    "id": "course_id",
    "title": "Introduction to React",
    "description": "Complete course description...",
    "thumbnail": "thumbnail-url",
    "difficulty": "beginner",
    "category": "programming",
    "duration": 1200,
    "modules": [
      {
        "id": "module_id",
        "title": "Getting Started",
        "description": "Module description",
        "duration": 300,
        "lessons": [
          {
            "id": "lesson_id",
            "title": "What is React?",
            "type": "video",
            "duration": 600,
            "content": "lesson-content-url"
          }
        ]
      }
    ],
    "prerequisites": ["javascript-basics"],
    "learningObjectives": [
      "Understand React components",
      "Build interactive UIs"
    ],
    "instructor": {
      "id": "instructor_id",
      "name": "Jane Smith",
      "bio": "Expert in React development",
      "avatar": "avatar-url"
    },
    "reviews": {
      "average": 4.5,
      "count": 250,
      "distribution": {
        "5": 150,
        "4": 75,
        "3": 20,
        "2": 3,
        "1": 2
      }
    }
  }
}

Enroll in Course

POST /courses/:id/enroll

Headers: Authorization: Bearer <token>

Get User's Enrolled Courses

GET /users/me/courses

Headers: Authorization: Bearer <token>

Get Course Progress

GET /courses/:id/progress

Headers: Authorization: Bearer <token>

Response:

{
  "success": true,
  "data": {
    "courseId": "course_id",
    "progress": {
      "percentage": 65,
      "completedModules": 5,
      "totalModules": 8,
      "completedLessons": 15,
      "totalLessons": 24,
      "timeSpent": 3600
    },
    "lastAccessed": "2023-07-25T10:00:00.000Z",
    "currentLesson": {
      "moduleId": "module_6",
      "lessonId": "lesson_16"
    }
  }
}

Update Lesson Progress

POST /courses/:courseId/lessons/:lessonId/progress

Headers: Authorization: Bearer <token>

Request Body:

{
  "completed": true,
  "timeSpent": 300,
  "score": 85
}

🎯 Goal Management Endpoints

Get User Goals

GET /goals?status=active&page=1&limit=10

Headers: Authorization: Bearer <token>

Query Parameters:

  • status (optional): Filter by status (active, completed, paused)
  • type (optional): Filter by goal type
  • page, limit: Pagination

Response:

{
  "success": true,
  "data": {
    "items": [
      {
        "id": "goal_id",
        "title": "Complete React Course",
        "description": "Finish the React fundamentals course",
        "type": "course_completion",
        "target": {
          "type": "completion",
          "value": 100,
          "deadline": "2023-08-31T23:59:59.000Z"
        },
        "progress": {
          "current": 65,
          "percentage": 65
        },
        "status": "active",
        "priority": "high",
        "createdAt": "2023-07-01T00:00:00.000Z"
      }
    ]
  }
}

Create Goal

POST /goals

Headers: Authorization: Bearer <token>

Request Body:

{
  "title": "Learn TypeScript",
  "description": "Master TypeScript fundamentals",
  "type": "skill_development",
  "target": {
    "type": "time",
    "value": 2400,
    "deadline": "2023-12-31T23:59:59.000Z"
  },
  "priority": "medium",
  "relatedCourses": ["typescript-course-id"]
}

Update Goal

PUT /goals/:id

Headers: Authorization: Bearer <token>

Delete Goal

DELETE /goals/:id

Headers: Authorization: Bearer <token>

Update Goal Progress

POST /goals/:id/progress

Headers: Authorization: Bearer <token>

Request Body:

{
  "progress": 75,
  "notes": "Completed another module today"
}

πŸ€– AI Features Endpoints

Get Personalized Recommendations

GET /ai/recommendations

Headers: Authorization: Bearer <token>

Response:

{
  "success": true,
  "data": {
    "courses": [
      {
        "id": "course_id",
        "title": "Advanced React Patterns",
        "reason": "Based on your progress in React fundamentals",
        "confidence": 0.85
      }
    ],
    "goals": [
      {
        "title": "Build a Portfolio Project",
        "description": "Apply your React skills",
        "reason": "You've completed 3 React courses"
      }
    ],
    "nextLessons": [
      {
        "courseId": "current_course",
        "lessonId": "next_lesson",
        "title": "React Hooks Deep Dive",
        "estimatedTime": 45
      }
    ]
  }
}

Generate Learning Path

POST /ai/learning-path

Headers: Authorization: Bearer <token>

Request Body:

{
  "goal": "Become a full-stack developer",
  "currentSkills": ["html", "css", "basic-javascript"],
  "timeCommitment": 10,
  "preferredStyle": "hands-on"
}

Get Content Suggestions

POST /ai/content-suggestions

Headers: Authorization: Bearer <token>

Request Body:

{
  "topic": "React performance optimization",
  "difficulty": "intermediate",
  "format": "video"
}

πŸ“Š Analytics Endpoints

Get User Analytics

GET /analytics/user?period=30d

Headers: Authorization: Bearer <token>

Query Parameters:

  • period: Time period (7d, 30d, 90d, 1y)

Response:

{
  "success": true,
  "data": {
    "learningTime": {
      "total": 7200,
      "thisWeek": 480,
      "average": 102.86
    },
    "progress": {
      "coursesStarted": 8,
      "coursesCompleted": 3,
      "lessonsCompleted": 45
    },
    "goals": {
      "total": 5,
      "completed": 2,
      "onTrack": 2,
      "overdue": 1
    },
    "streaks": {
      "current": 7,
      "longest": 15
    },
    "timeline": [
      {
        "date": "2023-07-25",
        "minutes": 120,
        "lessonsCompleted": 3
      }
    ]
  }
}

Get Course Analytics

GET /analytics/courses/:id

Headers: Authorization: Bearer <token>

πŸ” Search Endpoints

Global Search

GET /search?q=react&type=courses&page=1&limit=10

Query Parameters:

  • q: Search query
  • type: Content type (courses, users, goals, all)
  • filters: Additional filters as JSON string

Response:

{
  "success": true,
  "data": {
    "results": {
      "courses": [
        {
          "id": "course_id",
          "title": "React Fundamentals",
          "type": "course",
          "relevance": 0.95
        }
      ],
      "total": 15
    },
    "suggestions": ["react hooks", "react router"],
    "filters": {
      "categories": ["programming", "web-development"],
      "difficulties": ["beginner", "intermediate"]
    }
  }
}

πŸ“ˆ Error Codes

Code Description
AUTH_REQUIRED Authentication required
AUTH_INVALID Invalid authentication token
AUTH_EXPIRED Authentication token expired
FORBIDDEN Insufficient permissions
NOT_FOUND Resource not found
VALIDATION_ERROR Request validation failed
DUPLICATE_ENTRY Resource already exists
RATE_LIMIT Rate limit exceeded
SERVER_ERROR Internal server error
SERVICE_UNAVAILABLE Service temporarily unavailable

πŸ“ Rate Limiting

  • Anonymous requests: 100 requests per hour
  • Authenticated requests: 1000 requests per hour
  • Upload endpoints: 10 requests per minute

Rate limit headers:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1627284000

πŸ§ͺ Testing the API

Using cURL

# Login
curl -X POST https://api.openln.dev/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"password"}'

# Get courses (with token)
curl -X GET https://api.openln.dev/api/v1/courses \
  -H "Authorization: Bearer YOUR_TOKEN"

Using JavaScript (Fetch)

// Login
const loginResponse = await fetch('/api/v1/auth/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    email: 'user@example.com',
    password: 'password'
  })
});

const { data } = await loginResponse.json();
const token = data.token;

// Use authenticated endpoint
const coursesResponse = await fetch('/api/v1/courses', {
  headers: { 'Authorization': `Bearer ${token}` }
});

πŸ“‹ Postman Collection

A Postman collection with all endpoints is available:


For more information or support, please open an issue or join our discussions.