Files
LearnIT/docs/API_DOCUMENTATION.md
2026-05-06 20:16:11 +01:00

16 KiB

API Documentation - AI Study Assistant

📡 COMPLETE API REFERENCE


📋 OVERVIEW

This document provides comprehensive API documentation for the AI Study Assistant backend services, including authentication, content management, learning analytics, and AI-powered tutoring features.


🔐 AUTHENTICATION

Base URL

Production: https://api.teachit.app
Staging: https://api-staging.teachit.app
Development: http://localhost:5001

Authentication Methods

All API endpoints require authentication using Firebase ID tokens.

Request Headers

Authorization: Bearer <firebase_id_token>
Content-Type: application/json
X-Request-ID: <unique_request_id>

Token Validation

// Example token validation
const idToken = req.headers.authorization?.split('Bearer ')[1];
const decodedToken = await admin.auth().verifyIdToken(idToken);
const uid = decodedToken.uid;

👤 USER MANAGEMENT

Sign Up

POST /auth/signup

Request Body:

{
  "email": "student@school.com",
  "password": "securePassword123",
  "role": "student",
  "schoolId": "school123",
  "profile": {
    "name": "John Doe",
    "grade": 10,
    "section": "A"
  }
}

Response:

{
  "success": true,
  "user": {
    "uid": "user123",
    "email": "student@school.com",
    "role": "student",
    "profile": {
      "name": "John Doe",
      "grade": 10,
      "section": "A"
    },
    "createdAt": "2026-05-06T20:00:00Z"
  },
  "token": "firebase_id_token"
}

Sign In

POST /auth/signin

Request Body:

{
  "email": "student@school.com",
  "password": "securePassword123"
}

Response:

{
  "success": true,
  "user": {
    "uid": "user123",
    "email": "student@school.com",
    "role": "student",
    "profile": {
      "name": "John Doe",
      "grade": 10,
      "section": "A"
    }
  },
  "token": "firebase_id_token"
}

Get User Profile

GET /auth/profile

Response:

{
  "success": true,
  "user": {
    "uid": "user123",
    "email": "student@school.com",
    "role": "student",
    "schoolId": "school123",
    "profile": {
      "name": "John Doe",
      "grade": 10,
      "section": "A",
      "avatar": "https://storage.googleapis.com/avatars/user123.jpg"
    },
    "preferences": {
      "language": "en",
      "theme": "light",
      "notifications": true
    }
  }
}

🤖 AI TUTORING

Ask Tutor

POST /tutor/ask

Request Body:

{
  "query": "What is a derivative?",
  "mode": "EXPLANATION",
  "context": {
    "subject": "Mathematics",
    "currentTopic": "Calculus"
  },
  "studentInfo": {
    "level": 2,
    "grade": 10
  }
}

Response:

{
  "success": true,
  "response": {
    "text": "A derivative is a concept that measures how a function changes as its input changes...",
    "sources": [
      {
        "chunkId": "chunk123",
        "title": "Introduction to Derivatives",
        "relevance": 0.95
      }
    ],
    "metadata": {
      "mode": "EXPLANATION",
      "responseTime": 1.2,
      "tokens": 156,
      "model": "claude-3-5-sonnet-20241022"
    }
  },
  "interactionId": "interaction123"
}

Get Chat History

GET /tutor/history?limit=20&offset=0

Response:

{
  "success": true,
  "interactions": [
    {
      "id": "interaction123",
      "query": "What is a derivative?",
      "response": "A derivative is a concept...",
      "mode": "EXPLANATION",
      "timestamp": "2026-05-06T20:00:00Z",
      "feedback": {
        "rating": 5,
        "comment": "Very helpful!"
      }
    }
  ],
  "total": 45,
  "hasMore": true
}

Submit Feedback

POST /tutor/feedback

Request Body:

{
  "interactionId": "interaction123",
  "rating": 5,
  "comment": "Very helpful explanation",
  "category": "content_quality"
}

Response:

{
  "success": true,
  "feedbackId": "feedback123"
}

📚 CONTENT MANAGEMENT

Upload Content

POST /content/upload

Request (multipart/form-data):

file: [file_content]
fileName: "derivatives_lesson.pdf"
mimeType: "application/pdf"
metadata: {
  "subject": "Mathematics",
  "concept": "Derivatives",
  "difficulty": 0.6,
  "grade": 10,
  "language": "en"
}

Response:

{
  "success": true,
  "contentId": "content123",
  "chunks": [
    {
      "id": "chunk123",
      "text": "A derivative measures the rate of change...",
      "metadata": {
        "concept": "Derivatives",
        "difficulty": 0.6,
        "quality": 0.85
      }
    }
  ],
  "processingTime": 2.3
}

Get Content List

GET /content/list?subject=Mathematics&concept=Derivatives&limit=10

Response:

{
  "success": true,
  "content": [
    {
      "id": "content123",
      "title": "Introduction to Derivatives",
      "subject": "Mathematics",
      "concept": "Derivatives",
      "difficulty": 0.6,
      "grade": 10,
      "chunkCount": 12,
      "uploadedAt": "2026-05-06T20:00:00Z",
      "uploadedBy": "teacher123"
    }
  ],
  "total": 25,
  "hasMore": true
}

Get Content Details

GET /content/{contentId}

Response:

{
  "success": true,
  "content": {
    "id": "content123",
    "title": "Introduction to Derivatives",
    "subject": "Mathematics",
    "concept": "Derivatives",
    "difficulty": 0.6,
    "grade": 10,
    "chunks": [
      {
        "id": "chunk123",
        "text": "A derivative measures the rate of change...",
        "metadata": {
          "concept": "Derivatives",
          "difficulty": 0.6,
          "quality": 0.85,
          "wordCount": 156
        }
      }
    ],
    "uploadedAt": "2026-05-06T20:00:00Z",
    "uploadedBy": "teacher123"
  }
}

📝 QUIZ SYSTEM

Create Quiz

POST /quiz/create

Request Body:

{
  "title": "Derivatives Quiz",
  "subject": "Mathematics",
  "concept": "Derivatives",
  "grade": 10,
  "difficulty": 0.5,
  "questions": [
    {
      "type": "multiple_choice",
      "question": "What is the derivative of f(x) = x²?",
      "options": [
        "2x",
        "x",
        "2",
        "x²"
      ],
      "correctAnswer": 0,
      "explanation": "Using the power rule, the derivative of x² is 2x."
    }
  ],
  "timeLimit": 30,
  "passingScore": 70
}

Response:

{
  "success": true,
  "quizId": "quiz123",
  "questions": [
    {
      "id": "question123",
      "type": "multiple_choice",
      "question": "What is the derivative of f(x) = x²?",
      "options": [
        "2x",
        "x",
        "2",
        "x²"
      ]
    }
  ]
}

Start Quiz

POST /quiz/{quizId}/start

Response:

{
  "success": true,
  "attemptId": "attempt123",
  "quiz": {
    "id": "quiz123",
    "title": "Derivatives Quiz",
    "timeLimit": 30,
    "questionCount": 5
  },
  "questions": [
    {
      "id": "question123",
      "type": "multiple_choice",
      "question": "What is the derivative of f(x) = x²?",
      "options": [
        "2x",
        "x",
        "2",
        "x²"
      ]
    }
  ],
  "startedAt": "2026-05-06T20:00:00Z"
}

Submit Quiz Answer

POST /quiz/{attemptId}/answer

Request Body:

{
  "questionId": "question123",
  "answer": 0,
  "timeSpent": 15
}

Response:

{
  "success": true,
  "correct": true,
  "explanation": "Using the power rule, the derivative of x² is 2x.",
  "points": 10,
  "totalPoints": 50
}

Complete Quiz

POST /quiz/{attemptId}/complete

Response:

{
  "success": true,
  "results": {
    "score": 85,
    "totalQuestions": 5,
    "correctAnswers": 4,
    "timeSpent": 180,
    "passed": true,
    "completedAt": "2026-05-06T20:03:00Z"
  },
  "recommendations": [
    {
      "concept": "Chain Rule",
      "reason": "Related to derivatives",
      "priority": "medium"
    }
  ]
}

📊 LEARNING ANALYTICS

Get Learning State

GET /analytics/learning-state

Response:

{
  "success": true,
  "learningState": {
    "studentId": "student123",
    "adaptiveDifficulty": {
      "currentLevel": 2.3,
      "targetLevel": 3.0,
      "adjustmentFactor": 0.1
    },
    "conceptStates": [
      {
        "concept": "Derivatives",
        "mastery": 0.75,
        "confidence": 0.82,
        "lastInteraction": "2026-05-06T20:00:00Z",
        "interactions": 12,
        "correctAnswers": 9
      }
    ],
    "spacedRepetition": {
      "nextReviewDue": [
        {
          "concept": "Derivatives",
          "dueDate": "2026-05-08T20:00:00Z",
          "priority": "high"
        }
      ]
    },
    "metadata": {
      "totalInteractions": 45,
      "averageSessionTime": 15.2,
      "streak": 7,
      "lastActive": "2026-05-06T20:00:00Z"
    }
  }
}

Update Learning State

POST /analytics/learning-state

Request Body:

{
  "concept": "Derivatives",
  "mastery": 0.8,
  "confidence": 0.85,
  "interaction": {
    "type": "quiz",
    "correct": true,
    "timeSpent": 30
  }
}

Response:

{
  "success": true,
  "updated": true,
  "newMastery": 0.8,
  "recommendations": [
    {
      "action": "advance_difficulty",
      "reason": "High mastery achieved"
    }
  ]
}

Get Progress Report

GET /analytics/progress?period=week&subject=Mathematics

Response:

{
  "success": true,
  "progress": {
    "period": "week",
    "subject": "Mathematics",
    "stats": {
      "totalSessions": 12,
      "totalTime": 180,
      "conceptsStudied": 5,
      "averageScore": 82,
      "improvement": 15
    },
    "dailyProgress": [
      {
        "date": "2026-05-06",
        "sessions": 2,
        "timeSpent": 30,
        "concepts": ["Derivatives"],
        "score": 85
      }
    ],
    "conceptProgress": [
      {
        "concept": "Derivatives",
        "mastery": 0.75,
        "improvement": 0.2,
        "timeSpent": 60
      }
    ]
  }
}

🏫 SCHOOL MANAGEMENT

Get School Info

GET /school/info

Response:

{
  "success": true,
  "school": {
    "id": "school123",
    "name": "Escola Profissional de Vila do Conde",
    "settings": {
      "curriculum": ["Mathematics", "Science", "English"],
      "language": "en",
      "policies": {
        "allowExternalKnowledge": false,
        "fallbackMode": "partial_with_hint",
        "minRetrievalConfidence": 0.6
      }
    },
    "subscription": {
      "plan": "premium",
      "maxStudents": 1000,
      "maxTeachers": 50,
      "expiresAt": "2026-12-31T23:59:59Z"
    }
  }
}

Get Students

GET /school/students?grade=10&section=A

Response:

{
  "success": true,
  "students": [
    {
      "uid": "student123",
      "name": "John Doe",
      "email": "john@school.com",
      "grade": 10,
      "section": "A",
      "progress": {
        "totalSessions": 45,
        "averageScore": 82,
        "lastActive": "2026-05-06T20:00:00Z"
      }
    }
  ],
  "total": 25
}

📈 TEACHER ANALYTICS

Get Class Analytics

GET /analytics/class?grade=10&section=A&period=month

Response:

{
  "success": true,
  "analytics": {
    "period": "month",
    "classSize": 25,
    "activeStudents": 23,
    "totalSessions": 345,
    "averageScore": 78,
    "topConcepts": [
      {
        "concept": "Derivatives",
        "mastery": 0.72,
        "students": 20
      }
    ],
    "strugglingStudents": [
      {
        "studentId": "student456",
        "name": "Jane Smith",
        "averageScore": 65,
        "conceptsNeedingHelp": ["Chain Rule"]
      }
    ],
    "engagementMetrics": {
      "dailyActiveUsers": 18,
      "averageSessionTime": 12.5,
      "questionFrequency": 3.2
    }
  }
}

🔄 WEBHOOKS

Webhook Events

The system supports webhooks for real-time notifications:

Event Types

  • user.created
  • interaction.completed
  • quiz.completed
  • content.uploaded
  • learning.state.updated

Webhook Configuration

POST /webhooks/configure

Request Body:

{
  "url": "https://your-app.com/webhook",
  "events": ["interaction.completed", "quiz.completed"],
  "secret": "webhook_secret"
}

Response:

{
  "success": true,
  "webhookId": "webhook123"
}

⚠️ ERROR HANDLING

Error Response Format

{
  "success": false,
  "error": {
    "code": "AUTHENTICATION_REQUIRED",
    "message": "Authentication token is required",
    "details": {
      "field": "authorization",
      "expected": "Bearer <token>"
    },
    "requestId": "req_123456"
  }
}

Error Codes

Code HTTP Status Description
AUTHENTICATION_REQUIRED 401 Firebase token required
INVALID_TOKEN 401 Invalid or expired token
PERMISSION_DENIED 403 Insufficient permissions
NOT_FOUND 404 Resource not found
VALIDATION_ERROR 400 Request validation failed
RATE_LIMIT_EXCEEDED 429 Too many requests
INTERNAL_ERROR 500 Server error
SERVICE_UNAVAILABLE 503 Service temporarily unavailable

📊 RATE LIMITING

Rate Limits

Endpoint Requests/Minute Burst
/tutor/ask 20 5
/quiz/* 30 10
/content/* 10 3
/analytics/* 50 15
/auth/* 100 20

Rate Limit Headers

X-RateLimit-Limit: 20
X-RateLimit-Remaining: 15
X-RateLimit-Reset: 1623456789

🔍 SEARCH AND FILTERING

Query Parameters

Common parameters across endpoints:

  • limit: Number of items to return (default: 20, max: 100)
  • offset: Number of items to skip (default: 0)
  • sort: Field to sort by
  • order: Sort order (asc/desc, default: desc)
  • filter: Filter criteria (JSON object)
  • search: Search term

Example Filter

GET /content/list?filter={"subject":"Mathematics","difficulty":{"gte":0.5,"lte":0.8}}&sort=uploadedAt&order=desc&limit=10

📱 SDK EXAMPLES

JavaScript/TypeScript

import { TeachItAPI } from '@teachit/api-client';

const api = new TeachItAPI({
  baseURL: 'https://api.teachit.app',
  token: 'firebase_id_token'
});

// Ask tutor
const response = await api.tutor.ask({
  query: 'What is a derivative?',
  mode: 'EXPLANATION'
});

// Get learning state
const learningState = await api.analytics.getLearningState();

Flutter/Dart

import 'package:teachit_api/teachit_api.dart';

final api = TeachItAPI(
  baseURL: 'https://api.teachit.app',
  token: 'firebase_id_token'
);

// Ask tutor
final response = await api.tutor.ask(
  query: 'What is a derivative?',
  mode: 'EXPLANATION',
);

// Get learning state
final learningState = await api.analytics.getLearningState();

Python

from teachit_api import TeachItAPI

api = TeachItAPI(
    base_url='https://api.teachit.app',
    token='firebase_id_token'
)

# Ask tutor
response = api.tutor.ask(
    query='What is a derivative?',
    mode='EXPLANATION'
)

# Get learning state
learning_state = api.analytics.get_learning_state()

🧪 TESTING

Test Environment

Test Data

POST /auth/test/login

Response:

{
  "success": true,
  "token": "test_token",
  "user": {
    "uid": "test_user",
    "role": "student"
  }
}

📋 CHANGE LOG

Version 1.0.0 (2026-05-06)

  • Initial API release
  • Authentication endpoints
  • AI tutoring functionality
  • Quiz system
  • Learning analytics
  • Content management

📞 SUPPORT

API Support

Community


Last Updated: 2026-05-06 Version: 1.0.0 API Team: Backend Development