Skip to content

Latest commit

 

History

History
764 lines (648 loc) · 15.6 KB

File metadata and controls

764 lines (648 loc) · 15.6 KB

IvyLevel API Documentation

Base URL: https://api.ivylevel.com (production) | http://localhost:8000 (development)
Version: 2.0.0

Table of Contents

  1. Authentication
  2. AI Agents
  3. Coach Management
  4. Admin Management
  5. Payment Processing
  6. Email Services
  7. Document Management
  8. WebSocket API
  9. Error Handling

Authentication

All API requests require authentication except for login and registration endpoints.

Register User

POST /api/auth/register
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "SecurePassword123!",
  "name": "John Doe",
  "role": "student"  // "student" or "coach"
}

Response:
{
  "user_id": "123e4567-e89b-12d3-a456-426614174000",
  "email": "user@example.com",
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
  "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
  "token_type": "bearer"
}

Login

POST /api/auth/login
Content-Type: application/json

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

Response:
{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
  "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
  "token_type": "bearer",
  "user": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "email": "user@example.com",
    "role": "student"
  }
}

Refresh Token

POST /api/auth/refresh
Authorization: Bearer <refresh_token>

Response:
{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
  "token_type": "bearer"
}

AI Agents

All AI agent endpoints require authentication.

Profile Assessment

Analyze a student's profile with behavioral intelligence.

POST /api/agents/assess/profile
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "assessment_type": "comprehensive",
  "include_behavioral": true
}

Response:
{
  "status": "success",
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "assessment": {
    "behavioral_traits": [
      {
        "trait": "analytical",
        "confidence": 0.85,
        "evidence": ["Strong problem-solving in essays", "Mathematical aptitude"]
      },
      {
        "trait": "creative",
        "confidence": 0.72,
        "evidence": ["Artistic extracurriculars", "Creative writing samples"]
      }
    ],
    "learning_style": "visual-kinesthetic",
    "communication_preferences": {
      "preferred_medium": "email",
      "response_time": "within 24 hours",
      "tone": "professional yet friendly"
    },
    "strengths": [
      "Strong analytical skills",
      "Leadership experience",
      "Consistent academic performance"
    ],
    "areas_for_improvement": [
      "Test scores below target range",
      "Limited STEM extracurriculars",
      "Essay writing needs refinement"
    ],
    "chetty_score": 78.5,
    "confidence": 0.89,
    "recommendations": [
      "Focus on SAT/ACT preparation",
      "Join STEM-related clubs or competitions",
      "Work with writing tutor for essays"
    ]
  }
}

Game Plan Generation

Generate a personalized action plan for a student.

POST /api/agents/generate/gameplan
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "timeline_months": 12,
  "focus_areas": ["test_prep", "extracurriculars", "essays"]
}

Response:
{
  "status": "success",
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "game_plan": {
    "plan_type": "comprehensive",
    "timeline_months": 12,
    "goals": [
      {
        "id": "goal_1",
        "title": "Improve SAT Score",
        "target": "1500+",
        "deadline": "2025-05-01"
      },
      {
        "id": "goal_2",
        "title": "Complete College Essays",
        "target": "10 polished essays",
        "deadline": "2025-11-01"
      }
    ],
    "milestones": [
      {
        "month": 1,
        "tasks": [
          {
            "title": "Take diagnostic SAT",
            "priority": "high",
            "estimated_hours": 4
          },
          {
            "title": "Research summer programs",
            "priority": "medium",
            "estimated_hours": 10
          }
        ]
      }
    ],
    "chetty_optimizations": {
      "mobility_score_impact": "+12%",
      "recommended_colleges": ["MIT", "Stanford", "UC Berkeley"],
      "financial_optimization": "Apply for need-based aid"
    },
    "narrative_arc": "From passionate problem-solver to innovative engineer ready to tackle global challenges"
  }
}

Opportunity Finder

Find relevant opportunities for a student.

POST /api/agents/find/opportunities
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "opportunity_type": "scholarship",
  "filters": {
    "min_amount": 5000,
    "deadline_after": "2025-01-01",
    "field": "STEM"
  }
}

Response:
{
  "status": "success",
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "opportunities": [
    {
      "id": "opp_1",
      "name": "National STEM Scholarship",
      "type": "scholarship",
      "amount": "$10,000",
      "deadline": "2025-03-15",
      "match_score": 0.92,
      "requirements": [
        "3.5+ GPA",
        "STEM major",
        "US citizen"
      ],
      "application_url": "https://example.com/apply",
      "roi_analysis": {
        "effort_hours": 20,
        "success_probability": 0.65,
        "expected_value": "$6,500"
      }
    }
  ],
  "count": 15
}

Crisis Detection

Detect potential crisis situations for a student.

POST /api/agents/detect/crisis
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "content": "Recent email or communication text",
  "check_history": true
}

Response:
{
  "status": "success",
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "crisis_analysis": {
    "crisis_detected": false,
    "severity_score": 0.2,
    "indicators": [],
    "recommendations": ["Continue regular check-ins"],
    "confidence": 0.94
  }
}

College Readiness Assessment

Assess a student's readiness for college.

POST /api/agents/assess/readiness
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "target_colleges": ["MIT", "Stanford", "Harvard"]
}

Response:
{
  "status": "success",
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "readiness_assessment": {
    "overall_readiness": 0.78,
    "college_specific": {
      "MIT": {
        "match_score": 0.72,
        "strengths": ["Strong STEM background"],
        "gaps": ["Research experience needed"]
      },
      "Stanford": {
        "match_score": 0.81,
        "strengths": ["Leadership qualities"],
        "gaps": ["Community service hours"]
      }
    },
    "action_items": [
      {
        "priority": "high",
        "action": "Gain research experience",
        "timeline": "Next 3 months"
      }
    ],
    "confidence": 0.87
  }
}

Behavioral Intervention

Get intervention recommendations for a student.

POST /api/agents/intervention/recommend
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "crisis_type": "academic_stress",
  "urgency": "medium"
}

Response:
{
  "status": "success",
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "intervention": {
    "strategies": [
      {
        "type": "immediate",
        "action": "Schedule stress management session",
        "resources": ["Breathing exercises", "Time management tools"]
      },
      {
        "type": "ongoing",
        "action": "Weekly check-ins",
        "duration": "4 weeks"
      }
    ],
    "communication_templates": [
      {
        "medium": "email",
        "subject": "Checking in - Here to Support You",
        "body": "Hi [Name], I noticed you might be feeling overwhelmed..."
      }
    ],
    "expected_outcomes": {
      "timeline": "2-4 weeks",
      "success_indicators": ["Improved assignment completion", "Reduced stress levels"]
    }
  }
}

Coach Management

Get Assigned Students

GET /api/coach/students
Authorization: Bearer <access_token>

Response:
{
  "students": [
    {
      "id": "123e4567-e89b-12d3-a456-426614174000",
      "name": "John Doe",
      "email": "john.doe@example.com",
      "grade": 11,
      "last_session": "2025-01-10",
      "readiness_score": 0.78,
      "alerts": []
    }
  ],
  "total": 15
}

Create Coaching Session

POST /api/coach/session
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "student_id": "123e4567-e89b-12d3-a456-426614174000",
  "session_type": "regular",
  "duration_minutes": 60,
  "notes": "Discussed college essay topics",
  "action_items": ["Complete first draft", "Research 3 more colleges"]
}

Response:
{
  "session_id": "sess_123",
  "status": "created",
  "next_session_recommended": "2025-01-24"
}

Admin Management

Get Platform Analytics

GET /api/admin/analytics
Authorization: Bearer <admin_access_token>

Response:
{
  "overview": {
    "total_users": 53,
    "active_students": 23,
    "active_coaches": 30,
    "revenue_mtd": "$45,230",
    "sessions_completed": 142,
    "avg_readiness_score": 0.72
  },
  "trends": {
    "user_growth": [
      {"month": "Nov", "students": 18, "coaches": 25},
      {"month": "Dec", "students": 23, "coaches": 30}
    ],
    "revenue_trend": [
      {"month": "Nov", "amount": 42150},
      {"month": "Dec", "amount": 45230}
    ]
  }
}

Manage Users

GET /api/admin/users?role=student&status=active
Authorization: Bearer <admin_access_token>

Response:
{
  "users": [
    {
      "id": "user_123",
      "email": "student@example.com",
      "name": "John Doe",
      "role": "student",
      "status": "active",
      "created_at": "2024-01-15T10:00:00Z",
      "last_login": "2025-01-20T14:30:00Z"
    }
  ],
  "total": 23,
  "page": 1,
  "per_page": 20
}

Bulk Import Users

POST /api/admin/users/import
Authorization: Bearer <admin_access_token>
Content-Type: multipart/form-data

file: users.csv

Response:
{
  "status": "success",
  "imported": 15,
  "failed": 2,
  "errors": [
    {"row": 5, "error": "Email already exists"},
    {"row": 12, "error": "Invalid phone format"}
  ]
}

System Health Check

GET /api/admin/system/health
Authorization: Bearer <admin_access_token>

Response:
{
  "status": "healthy",
  "services": {
    "database": "healthy",
    "redis": "healthy",
    "email": "healthy",
    "ai_agents": "healthy"
  },
  "metrics": {
    "cpu_usage": "45%",
    "memory_usage": "62%",
    "disk_usage": "28%",
    "response_time_ms": 120
  }
}

Update Platform Settings

PUT /api/admin/settings
Authorization: Bearer <admin_access_token>
Content-Type: application/json

{
  "category": "email",
  "settings": {
    "smtp_host": "smtp.sendgrid.net",
    "smtp_port": 587,
    "from_email": "noreply@ivylevel.com"
  }
}

Response:
{
  "status": "updated",
  "category": "email",
  "settings": {
    "smtp_host": "smtp.sendgrid.net",
    "smtp_port": 587,
    "from_email": "noreply@ivylevel.com",
    "updated_at": "2025-01-20T15:45:00Z"
  }
}

Payment Processing

Create Checkout Session

POST /api/payment/create-checkout
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "price_id": "price_1234567890",
  "success_url": "https://app.ivylevel.com/payment/success",
  "cancel_url": "https://app.ivylevel.com/payment/cancel"
}

Response:
{
  "checkout_url": "https://checkout.stripe.com/pay/cs_1234567890",
  "session_id": "cs_1234567890"
}

Get Subscriptions

GET /api/payment/subscriptions
Authorization: Bearer <access_token>

Response:
{
  "subscriptions": [
    {
      "id": "sub_1234567890",
      "status": "active",
      "plan": "Premium Monthly",
      "current_period_end": "2025-02-15",
      "cancel_at_period_end": false
    }
  ]
}

WebSocket API

Connect to real-time updates via WebSocket.

Connection

const ws = new WebSocket('wss://api.ivylevel.com/ws/client-123');

ws.onopen = () => {
  // Authenticate
  ws.send(JSON.stringify({
    type: 'auth',
    token: 'your-access-token'
  }));
  
  // Subscribe to topics
  ws.send(JSON.stringify({
    type: 'subscribe',
    topic: 'student:123e4567-e89b-12d3-a456-426614174000'
  }));
};

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  console.log('Received:', message);
};

Message Types

Subscribe to Topic

{
  "type": "subscribe",
  "topic": "crisis_alerts"
}

Receive Event

{
  "type": "event",
  "event_type": "crisis.detected",
  "data": {
    "student_id": "123e4567-e89b-12d3-a456-426614174000",
    "severity": "high",
    "timestamp": "2025-01-15T10:30:00Z"
  }
}

Error Handling

All errors follow a consistent format:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input provided",
    "details": {
      "field": "email",
      "error": "Invalid email format"
    }
  },
  "status_code": 400
}

Common Error Codes

Code Status Description
UNAUTHORIZED 401 Missing or invalid authentication
FORBIDDEN 403 Insufficient permissions
NOT_FOUND 404 Resource not found
VALIDATION_ERROR 400 Invalid input data
RATE_LIMITED 429 Too many requests
INTERNAL_ERROR 500 Server error

Rate Limiting

API requests are rate limited:

  • Authenticated requests: 1000 per hour
  • AI Agent requests: 100 per hour
  • Unauthenticated requests: 60 per hour

Rate limit headers:

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

SDKs and Code Examples

Python Example

import requests

class IvyLevelAPI:
    def __init__(self, api_key):
        self.base_url = "https://api.ivylevel.com"
        self.headers = {"Authorization": f"Bearer {api_key}"}
    
    def assess_profile(self, student_id):
        response = requests.post(
            f"{self.base_url}/api/agents/assess/profile",
            json={"student_id": student_id},
            headers=self.headers
        )
        return response.json()

# Usage
api = IvyLevelAPI("your-access-token")
assessment = api.assess_profile("123e4567-e89b-12d3-a456-426614174000")
print(assessment)

JavaScript/TypeScript Example

class IvyLevelAPI {
  private baseUrl = 'https://api.ivylevel.com';
  private headers: Headers;

  constructor(private apiKey: string) {
    this.headers = new Headers({
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    });
  }

  async assessProfile(studentId: string) {
    const response = await fetch(
      `${this.baseUrl}/api/agents/assess/profile`,
      {
        method: 'POST',
        headers: this.headers,
        body: JSON.stringify({ student_id: studentId })
      }
    );
    return response.json();
  }
}

// Usage
const api = new IvyLevelAPI('your-access-token');
const assessment = await api.assessProfile('123e4567-e89b-12d3-a456-426614174000');
console.log(assessment);

API Versioning

The API uses URL versioning. The current version is v2. Version 1 endpoints are deprecated but still supported.

https://api.ivylevel.com/v2/agents/assess/profile  (current)
https://api.ivylevel.com/v1/agents/assess/profile  (deprecated)

Support

For API support: