Skip to content

Latest commit

Β 

History

History
689 lines (576 loc) Β· 15.7 KB

File metadata and controls

689 lines (576 loc) Β· 15.7 KB

πŸ“‘ API Documentation - ShikshaFlow

Complete API reference for Shiksha Flow backend services.


πŸ” Authentication

All API routes require Firebase Authentication unless explicitly stated. Include the Firebase ID token in the Authorization header:

Authorization: Bearer <firebase_id_token>

πŸ“‹ Table of Contents

  1. Mental Health APIs
  2. Complaint Management APIs
  3. Student Registration API
  4. Response Formats
  5. Error Handling

🧠 Mental Health APIs

1. Generate Personalized Questions

Endpoint: POST /api/mental-health/generate-personalized-questions

Description: Generates 15 contextually relevant mental health assessment questions based on student profile and initial assessment data.

Authentication: Required

Request Body:

{
  firebaseUserData: {
    uid: string;           // Firebase user ID
    name: string;          // Student name
    email: string;         // Student email
    age: number;           // Student age
    department: string;    // Academic department
    role: string;          // User role (student)
  },
  assessmentData: {
    age: number;           // Age (confirmation)
    gender: string;        // Gender identity
    description: string;   // Initial description of mental state
  }
}

Response:

{
  success: boolean;
  questions: [
    {
      id: number;          // Question ID (1-15)
      text: string;        // Question text
      category: string;    // Category (personal, mood, stress, etc.)
    }
  ]
}

Example Request:

const response = await fetch('/api/mental-health/generate-personalized-questions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${idToken}`
  },
  body: JSON.stringify({
    firebaseUserData: {
      uid: "user123",
      name: "John Doe",
      email: "john@example.com",
      age: 20,
      department: "Computer Science",
      role: "student"
    },
    assessmentData: {
      age: 20,
      gender: "male",
      description: "I've been feeling overwhelmed with coursework lately."
    }
  })
});

Error Responses:

  • 400: Missing required fields
  • 401: Unauthorized (invalid token)
  • 500: AI generation failed

2. Analyze Comprehensive Assessment

Endpoint: POST /api/mental-health/analyze-comprehensive

Description: Analyzes student responses and generates dual reports (Mental State + Improvement Plan) with personalized recommendations.

Authentication: Required

Request Body:

{
  firebaseUserData: {
    uid: string;
    name: string;
    email: string;
    age: number;
    department: string;
    role: string;
  },
  assessmentData: {
    age: number;
    gender: string;
    description: string;
  },
  responses: [
    {
      questionId: number;
      questionText: string;
      answer: string;
      category: string;
    }
  ]
}

Response:

{
  success: boolean;
  result: {
    mentalStateReport: {
      currentState: {
        level: string;       // excellent|good|moderate|concerning|critical
        summary: string;     // Overall state description
      },
      stressLevel: {
        level: string;       // low|moderate|high|critical
        score: number;       // 0-100 stress score
        factors: string[];   // Contributing stress factors
      },
      keyFindings: string[]; // Main positive/neutral findings
      strengths: string[];   // Student strengths
      concerns: string[];    // Areas of concern
    },
    improvementReport: {
      overallRecommendation: string;  // Primary recommendation
      immediateActions: [
        {
          action: string;
          priority: string;   // high|medium|low
          timeframe: string;  // e.g., "Within 24 hours"
        }
      ],
      shortTermStrategies: [
        {
          strategy: string;
          priority: string;
          expectedOutcome: string;
        }
      ],
      longTermStrategies: [
        {
          strategy: string;
          priority: string;
          expectedOutcome: string;
        }
      ],
      lifestyleAdvice: {
        sleep: string;
        exercise: string;
        nutrition: string;
        socialConnection: string;
      },
      professionalHelpRecommended: boolean;
      professionalHelpReason: string;  // If recommended
      encouragement: string;           // Motivational message
    },
    assessmentDate: string;  // ISO date
    nextReviewDate: string;  // ISO date (7-14 days later)
  }
}

Example Request:

const response = await fetch('/api/mental-health/analyze-comprehensive', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${idToken}`
  },
  body: JSON.stringify({
    firebaseUserData: { /* ... */ },
    assessmentData: { /* ... */ },
    responses: [
      {
        questionId: 1,
        questionText: "How are you feeling today?",
        answer: "I'm feeling stressed about my upcoming exams.",
        category: "mood"
      }
      // ... 14 more responses
    ]
  })
});

Error Responses:

  • 400: Invalid request (missing fields, < 15 responses)
  • 401: Unauthorized
  • 500: AI analysis failed

πŸ“ Complaint Management APIs

3. AI Complaint Assignment

Endpoint: POST /api/ai/assign-complaint

Description: Automatically analyzes complaint, determines priority, infers complaint type, and assigns to the most suitable authority.

Authentication: Required (Server-side only - called automatically after complaint creation)

Request Body:

{
  complaintId: string;  // Firestore complaint document ID
}

Response:

{
  success: boolean;
  assignedTo: string;        // UID of assigned authority
  assignedToName: string;    // Name of assigned authority
  priority: string;          // low|medium|high|urgent
  complaintType: string;     // Administrative|Infrastructure|Hostel|Academic|Other
  sentiment: string;         // positive|neutral|negative|frustrated|angry
  keyIssues: string[];       // Extracted key issues (2-5)
  urgencyScore: number;      // 0-10 urgency score
  processingTime: number;    // Processing time in milliseconds
}

AI Analysis Process:

  1. Workload Calculation: Counts open complaints per authority
  2. Content Analysis: Analyzes title + description
  3. Classification: Infers complaint type
  4. Priority Determination: Sets urgency level
  5. Sentiment Analysis: Detects emotional tone
  6. Key Issues Extraction: Identifies main problems
  7. Smart Assignment: Matches to best authority based on:
    • Department match
    • Workload balance
    • Role suitability
    • Expertise
  8. Scheduling: Calculates scheduledAt timestamp based on priority

Example (Internal Call):

// Called automatically after complaint creation
await fetch('/api/ai/assign-complaint', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ complaintId: 'complaint123' })
});

Error Responses:

  • 400: Missing complaintId
  • 404: Complaint not found
  • 409: No candidate authority found
  • 500: AI processing error

Firestore Update: After successful processing, the complaint document is updated with:

{
  assignedTo: string;
  assignedToName: string;
  assignedToRole: "admin" | "Faculty" | "staff";
  priority: ComplaintPriority;
  complaintType: string;
  scheduledAt: Timestamp;
  aiRationale: string;
  isAIProcessed: true;
  aiAnalysis: {
    analyzed: true;
    analyzedAt: Timestamp;
    aiProvider: "gemini";
    suggestedPriority: ComplaintPriority;
    urgencyScore: number;
    keyIssues: string[];
    sentiment: Sentiment;
    inferredComplaintType: string;
    recommendedDepartment: string;
    recommendedAction: string;
    autoAssigned: true;
    assignmentReason: string;
    processingTime: number;
    rawResponse: string;
  }
}

πŸ‘€ Student Registration API

4. Register Student

Endpoint: POST /api/register-student

Description: Registers a new student in the system with role-based access.

Authentication: Required (Admin only)

Request Body:

{
  email: string;         // Student email
  password: string;      // Initial password
  name: string;          // Full name
  studentId: string;     // Student ID number
  department: string;    // Academic department
  age: number;           // Student age
  instituteId: string;   // Institution ID
}

Response:

{
  success: boolean;
  uid: string;           // Firebase user UID
  message: string;       // Success message
}

Example Request:

const response = await fetch('/api/register-student', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${adminToken}`
  },
  body: JSON.stringify({
    email: "student@university.edu",
    password: "SecurePass123",
    name: "Jane Smith",
    studentId: "STU2026001",
    department: "Computer Science",
    age: 19,
    instituteId: "INST001"
  })
});

Error Responses:

  • 400: Missing required fields or invalid data
  • 401: Unauthorized (not admin)
  • 409: Email already exists
  • 500: Registration failed

Firestore Document Created:

// Collection: users
// Document ID: <uid>
{
  uid: string;
  email: string;
  name: string;
  studentId: string;
  department: string;
  age: number;
  role: "student";
  instituteId: string;
  createdAt: Timestamp;
  updatedAt: Timestamp;
}

πŸ“Š Response Formats

Success Response Structure

{
  success: true,
  data?: any,           // Response data (varies by endpoint)
  message?: string      // Optional success message
}

Error Response Structure

{
  success: false,
  error: string,        // Error message
  code?: string,        // Error code (optional)
  details?: any         // Additional error details (optional)
}

⚠️ Error Handling

HTTP Status Codes

Code Meaning Common Causes
200 Success Request completed successfully
400 Bad Request Missing fields, invalid data format
401 Unauthorized Invalid/missing auth token
403 Forbidden Insufficient permissions
404 Not Found Resource doesn't exist
409 Conflict Resource already exists, no candidates
500 Server Error AI processing failed, database error

Error Response Examples

400 - Bad Request

{
  "success": false,
  "error": "Missing required fields: assessmentData.age"
}

401 - Unauthorized

{
  "success": false,
  "error": "Unauthorized: Invalid authentication token"
}

500 - Server Error

{
  "success": false,
  "error": "AI analysis failed",
  "details": "Gemini API returned invalid response"
}

πŸ”’ Security

Authentication Flow

  1. Client: Obtains Firebase ID token
const idToken = await user.getIdToken();
  1. Client: Includes token in request headers
headers: {
  'Authorization': `Bearer ${idToken}`
}
  1. Server: Verifies token via Firebase Admin SDK
const decodedToken = await admin.auth().verifyIdToken(idToken);
const uid = decodedToken.uid;

Firestore Security Rules

Rules enforce:

  • Students can only read their own data
  • Students cannot set complaint priority
  • Admins have full access
  • Role-based document access

Example rule:

match /complaints/{complaintId} {
  allow read: if request.auth != null && 
    (isAdmin() || resource.data.createdBy == request.auth.uid);
  
  allow create: if request.auth != null && 
    request.resource.data.studentType is string &&
    request.resource.data.priority == 'medium' &&
    request.resource.data.createdBy == request.auth.uid;
}

πŸš€ Rate Limiting

Gemini API Limits

  • Requests per minute: 60
  • Tokens per request: ~10,000 (questions), ~20,000 (analysis)

Best Practices

  • Implement client-side debouncing
  • Cache AI responses when possible
  • Handle rate limit errors gracefully
  • Use exponential backoff for retries

πŸ“ˆ Performance Optimization

Response Times

Endpoint Average Target
Generate Questions 3-4s <5s
Analyze Responses 5-8s <10s
Assign Complaint 2-3s <5s
Register Student 1-2s <3s

Optimization Tips

  1. Batch Firebase reads when possible
  2. Use Firestore indexes for complex queries
  3. Cache frequently accessed data
  4. Minimize AI prompt length
  5. Use concurrent API calls where appropriate

πŸ§ͺ Testing

Example Test with cURL

Generate Questions

curl -X POST http://localhost:3000/api/mental-health/generate-personalized-questions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ID_TOKEN" \
  -d '{
    "firebaseUserData": {
      "uid": "test123",
      "name": "Test User",
      "email": "test@example.com",
      "age": 20,
      "department": "CS",
      "role": "student"
    },
    "assessmentData": {
      "age": 20,
      "gender": "male",
      "description": "Test description"
    }
  }'

Testing with Postman

  1. Set Environment Variables:

    • BASE_URL: http://localhost:3000 or production URL
    • ID_TOKEN: Firebase ID token
  2. Create Collection: Import API endpoints

  3. Add Pre-request Script:

// Automatically refresh Firebase token
pm.sendRequest({
  url: 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=YOUR_API_KEY',
  method: 'POST',
  header: { 'Content-Type': 'application/json' },
  body: {
    mode: 'raw',
    raw: JSON.stringify({
      email: 'test@example.com',
      password: 'password',
      returnSecureToken: true
    })
  }
}, (err, res) => {
  pm.environment.set('ID_TOKEN', res.json().idToken);
});

πŸ“š Integration Examples

React/Next.js Client

// hooks/useMentalHealth.ts
import { useAuth } from './useAuth';

export function useMentalHealth() {
  const { user } = useAuth();

  const generateQuestions = async (assessmentData: AssessmentData) => {
    const idToken = await user?.getIdToken();
    
    const response = await fetch('/api/mental-health/generate-personalized-questions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${idToken}`
      },
      body: JSON.stringify({
        firebaseUserData: {
          uid: user?.uid,
          // ... user data
        },
        assessmentData
      })
    });

    if (!response.ok) {
      throw new Error('Failed to generate questions');
    }

    return response.json();
  };

  const analyzeResponses = async (data: AnalysisData) => {
    const idToken = await user?.getIdToken();
    
    const response = await fetch('/api/mental-health/analyze-comprehensive', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${idToken}`
      },
      body: JSON.stringify(data)
    });

    return response.json();
  };

  return { generateQuestions, analyzeResponses };
}

πŸ”„ Webhooks & Events

Future Implementation

Planned webhook support for:

  • Complaint status changes
  • Assignment notifications
  • Mental health report completion
  • Priority escalations

πŸ“ž Support

For API issues:


πŸ“ Changelog

v1.0.0 (January 2026)

  • Initial API release
  • Mental health assessment APIs
  • AI complaint assignment
  • Student registration

Last Updated: January 9, 2026
API Version: 1.0.0
Documentation: docs/