@campusiq/sdk
v1.0.5
Published
Official JavaScript/TypeScript SDK for CampusIQ - A comprehensive school management system API
Maintainers
Readme
CampusIQ SDK
The official JavaScript/TypeScript SDK for CampusIQ - A comprehensive school management system API.
🚀 Quick Start
Installation
```bash npm install @campusiq/sdk
or
yarn add @campusiq/sdk
or
pnpm add @campusiq/sdk ```
Basic Usage
```javascript import { CampusIQ } from '@campusiq/sdk';
const client = new CampusIQClient({ apiKey: 'your-api-key', schoolId: 'your-school-id', environment: 'production' // or 'sandbox' });
// Get all students const students = await client.students.list(); console.log(students); ```
📚 Table of Contents
- Authentication
- Configuration
- API Resources
- Error Handling
- Pagination
- Filtering & Search
- Webhooks
- TypeScript Support
- Examples
- Contributing
🔐 Authentication
To use the CampusIQ SDK, you need:
- API Key: Get your API key from the CampusIQ dashboard
- School ID: Your unique school identifier
```javascript const client = new CampusIQClient({ apiKey: 'ciq_a1b2c3d4_e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6', schoolId: '64f8a1b2c3d4e5f6a7b8c9d0' }); ```
Getting Your Credentials
- Log in to your CampusIQ Dashboard
- Navigate to Settings → API Keys
- Click Create New API Key
- Copy your API key and School ID
⚙️ Configuration
Basic Configuration
```javascript const client = new CampusIQClient({ apiKey: 'your-api-key', schoolId: 'your-school-id', environment: 'production', // 'production' or 'sandbox' timeout: 30000, // Request timeout in milliseconds retries: 3, // Number of retry attempts baseURL: 'https://api.campusiq.edu' // Custom base URL (optional) }); ```
Environment Variables
You can also use environment variables:
```bash CAMPUSIQ_API_KEY=your-api-key CAMPUSIQ_SCHOOL_ID=your-school-id CAMPUSIQ_ENVIRONMENT=production ```
```javascript const client = new CampusIQClient({ apiKey: process.env.CAMPUSIQ_API_KEY, schoolId: process.env.CAMPUSIQ_SCHOOL_ID, environment: process.env.CAMPUSIQ_ENVIRONMENT }); ```
📖 API Resources
Students
List Students
```javascript // Get all students const students = await client.students.list();
// With pagination const students = await client.students.list({ page: 1, limit: 50 });
// With filters const students = await client.students.list({ grade: '10', status: 'active', search: 'john' }); ```
Get Student
```javascript const student = await client.students.get('student-id'); ```
Create Student
```javascript const newStudent = await client.students.create({ firstName: 'John', lastName: 'Doe', email: '[email protected]', grade: '10', dateOfBirth: '2008-05-15', address: { street: '123 Main St', city: 'Anytown', state: 'CA', zipCode: '12345' }, parentContact: { name: 'Jane Doe', email: '[email protected]', phone: '+1-555-0123' } }); ```
Update Student
```javascript const updatedStudent = await client.students.update('student-id', { grade: '11', email: '[email protected]' }); ```
Delete Student
```javascript await client.students.delete('student-id'); ```
Teachers
List Teachers
```javascript const teachers = await client.teachers.list({ department: 'Mathematics', status: 'active' }); ```
Create Teacher
```javascript const newTeacher = await client.teachers.create({ firstName: 'Sarah', lastName: 'Johnson', email: '[email protected]', department: 'Mathematics', subjects: ['Algebra', 'Geometry'], hireDate: '2020-08-15', qualifications: ['M.Ed Mathematics', 'B.S Mathematics'] }); ```
Courses
List Courses
```javascript const courses = await client.courses.list({ semester: 'Fall 2024', department: 'Science' }); ```
Create Course
```javascript const newCourse = await client.courses.create({ name: 'Advanced Biology', code: 'BIO-401', description: 'Advanced topics in biology', credits: 4, department: 'Science', teacherId: 'teacher-id', schedule: { days: ['Monday', 'Wednesday', 'Friday'], startTime: '09:00', endTime: '10:30', room: 'SCI-101' }, semester: 'Fall 2024' }); ```
Enrollments
List Enrollments
```javascript const enrollments = await client.enrollments.list({ studentId: 'student-id', semester: 'Fall 2024' }); ```
Enroll Student
```javascript const enrollment = await client.enrollments.create({ studentId: 'student-id', courseId: 'course-id', semester: 'Fall 2024', enrollmentDate: '2024-08-15' }); ```
Grades
List Grades
```javascript const grades = await client.grades.list({ studentId: 'student-id', courseId: 'course-id', semester: 'Fall 2024' }); ```
Record Grade
```javascript const grade = await client.grades.create({ studentId: 'student-id', courseId: 'course-id', assignmentName: 'Midterm Exam', score: 85, maxScore: 100, weight: 0.3, category: 'exam', gradedDate: '2024-10-15' }); ```
Attendance
List Attendance
```javascript const attendance = await client.attendance.list({ studentId: 'student-id', date: '2024-10-15' }); ```
Record Attendance
```javascript const attendance = await client.attendance.create({ studentId: 'student-id', courseId: 'course-id', date: '2024-10-15', status: 'present', // 'present', 'absent', 'tardy', 'excused' notes: 'Arrived 5 minutes late' }); ```
🚨 Error Handling
The SDK throws specific error types for different scenarios:
```javascript import { CampusIQError } from '@campusiq/sdk';
try { const student = await client.students.get('invalid-id'); } catch (error) { if (error instanceof CampusIQError) { console.log('Error Code:', error.code); console.log('Error Message:', error.message); console.log('HTTP Status:', error.status); console.log('Request ID:', error.requestId); } } ```
Error Types
ValidationError- Invalid input dataAuthenticationError- Invalid API key or permissionsNotFoundError- Resource not foundRateLimitError- Rate limit exceededServerError- Internal server error
📄 Pagination
All list methods support pagination:
```javascript const students = await client.students.list({ page: 1, limit: 25 });
console.log(students.data); // Array of students console.log(students.pagination); // Pagination info /* { page: 1, limit: 25, total: 150, pages: 6, hasNext: true, hasPrev: false } */ ```
Iterating Through Pages
```javascript let page = 1; let hasMore = true;
while (hasMore) { const result = await client.students.list({ page, limit: 50 });
// Process students result.data.forEach(student => { console.log(student.firstName, student.lastName); });
hasMore = result.pagination.hasNext; page++; } ```
🔍 Filtering & Search
Basic Filtering
```javascript const students = await client.students.list({ grade: '10', status: 'active' }); ```
Search
```javascript const students = await client.students.list({ search: 'john doe' }); ```
Advanced Filtering
```javascript const students = await client.students.list({ grade: ['9', '10', '11'], // Multiple values enrollmentDate: { gte: '2024-01-01', lte: '2024-12-31' }, sort: 'lastName:asc' }); ```
🔔 Webhooks
Setting Up Webhooks
```javascript // Configure webhook endpoint const webhook = await client.webhooks.create({ url: 'https://your-app.com/webhooks/campusiq', events: ['student.created', 'student.updated', 'grade.created'], secret: 'your-webhook-secret' }); ```
Webhook Events
student.created- New student enrolledstudent.updated- Student information updatedstudent.deleted- Student removedteacher.created- New teacher addedcourse.created- New course createdenrollment.created- Student enrolled in coursegrade.created- New grade recordedattendance.created- Attendance recorded
Verifying Webhooks
```javascript import { CampusIQClient } from '@campusiq/sdk';
// In your webhook handler app.post('/webhooks/campusiq', (req, res) => { const signature = req.headers['x-campusiq-signature']; const payload = req.body;
if (CampusIQ.verifyWebhook(payload, signature, 'your-webhook-secret')) { // Process webhook console.log('Event:', payload.event); console.log('Data:', payload.data); res.status(200).send('OK'); } else { res.status(400).send('Invalid signature'); } }); ```
📝 TypeScript Support
The SDK is written in TypeScript and includes full type definitions:
```typescript import { CampusIQClient, Student, Teacher, Course } from '@campusiq/sdk';
const client = new CampusIQ({ apiKey: 'your-api-key', schoolId: 'your-school-id' });
// Fully typed responses const students: Student[] = await client.students.list(); const student: Student = await client.students.get('student-id');
// Type-safe creation const newStudent: Student = await client.students.create({ firstName: 'John', lastName: 'Doe', email: '[email protected]', grade: '10' // TypeScript will enforce valid grade values }); ```
Available Types
```typescript interface Student { id: string; firstName: string; lastName: string; email: string; grade: string; status: 'active' | 'inactive' | 'graduated'; dateOfBirth: string; enrollmentDate: string; address: Address; parentContact: Contact; createdAt: string; updatedAt: string; }
interface Teacher { id: string; firstName: string; lastName: string; email: string; department: string; subjects: string[]; hireDate: string; status: 'active' | 'inactive'; qualifications: string[]; createdAt: string; updatedAt: string; }
// ... and many more ```
💡 Examples
Complete Student Management Example
```javascript import { CampusIQClient } from '@campusiq/sdk';
const client = new CampusIQClient({ apiKey: process.env.CAMPUSIQ_API_KEY, schoolId: process.env.CAMPUSIQ_SCHOOL_ID });
async function manageStudents() { try { // Create a new student const newStudent = await client.students.create({ firstName: 'Alice', lastName: 'Smith', email: '[email protected]', grade: '9', dateOfBirth: '2009-03-20', address: { street: '456 Oak Ave', city: 'Springfield', state: 'IL', zipCode: '62701' }, parentContact: { name: 'Bob Smith', email: '[email protected]', phone: '+1-555-0456' } });
console.log('Created student:', newStudent.id);
// Get all 9th grade students
const ninthGraders = await client.students.list({
grade: '9',
status: 'active'
});
console.log(`Found ${ninthGraders.data.length} 9th grade students`);
// Update student grade
const updatedStudent = await client.students.update(newStudent.id, {
grade: '10'
});
console.log('Updated student grade to:', updatedStudent.grade);} catch (error) { console.error('Error managing students:', error.message); } }
manageStudents(); ```
Bulk Operations Example
```javascript async function bulkEnrollStudents() { const courseId = 'course-123'; const studentIds = ['student-1', 'student-2', 'student-3'];
const enrollments = await Promise.all( studentIds.map(studentId => client.enrollments.create({ studentId, courseId, semester: 'Fall 2024', enrollmentDate: new Date().toISOString().split('T')[0] }) ) );
console.log(Enrolled ${enrollments.length} students in course);
}
```
Grade Calculation Example
```javascript async function calculateGPA(studentId) { const grades = await client.grades.list({ studentId, semester: 'Fall 2024' });
const totalPoints = grades.data.reduce((sum, grade) => { const percentage = (grade.score / grade.maxScore) * 100; const gpa = percentageToGPA(percentage); return sum + (gpa * grade.credits); }, 0);
const totalCredits = grades.data.reduce((sum, grade) => sum + grade.credits, 0); const gpa = totalPoints / totalCredits;
console.log(Student GPA: ${gpa.toFixed(2)});
return gpa;
}
function percentageToGPA(percentage) { if (percentage >= 97) return 4.0; if (percentage >= 93) return 3.7; if (percentage >= 90) return 3.3; if (percentage >= 87) return 3.0; if (percentage >= 83) return 2.7; if (percentage >= 80) return 2.3; if (percentage >= 77) return 2.0; if (percentage >= 73) return 1.7; if (percentage >= 70) return 1.3; if (percentage >= 67) return 1.0; return 0.0; } ```
🔧 Advanced Configuration
Custom HTTP Client
```javascript import axios from 'axios';
const client = new CampusIQClient({ apiKey: 'your-api-key', schoolId: 'your-school-id', httpClient: axios.create({ timeout: 60000, headers: { 'User-Agent': 'MyApp/1.0.0' } }) }); ```
Request Interceptors
```javascript client.interceptors.request.use((config) => { console.log('Making request to:', config.url); return config; });
client.interceptors.response.use( (response) => { console.log('Response received:', response.status); return response; }, (error) => { console.error('Request failed:', error.message); return Promise.reject(error); } ); ```
Rate Limiting
```javascript const client = new CampusIQClient({ apiKey: 'your-api-key', schoolId: 'your-school-id', rateLimit: { requests: 100, per: 'minute' // 'second', 'minute', 'hour' } }); ```
🧪 Testing
Mock Client for Testing
```javascript import { CampusIQClient } from '@campusiq/sdk';
// Create a mock client for testing const mockClient = new CampusIQClient({ apiKey: 'test-key', schoolId: 'test-school', environment: 'test' });
// Mock responses mockClient.students.list = jest.fn().mockResolvedValue({ data: [ { id: '1', firstName: 'John', lastName: 'Doe' } ], pagination: { page: 1, total: 1 } }); ```
Integration Testing
```javascript describe('CampusIQ SDK Integration', () => { let client;
beforeAll(() => { client = new CampusIQClient({ apiKey: process.env.TEST_API_KEY, schoolId: process.env.TEST_SCHOOL_ID, environment: 'sandbox' }); });
test('should create and retrieve student', async () => { const newStudent = await client.students.create({ firstName: 'Test', lastName: 'Student', email: '[email protected]', grade: '9' });
expect(newStudent.id).toBeDefined();
const retrievedStudent = await client.students.get(newStudent.id);
expect(retrievedStudent.firstName).toBe('Test');}); }); ```
📊 Performance Tips
Batch Operations
```javascript // Instead of multiple individual requests const students = []; for (const data of studentData) { const student = await client.students.create(data); // Slow students.push(student); }
// Use batch operations when available const students = await client.students.createBatch(studentData); // Fast ```
Efficient Pagination
```javascript // Use cursors for large datasets let cursor = null; const allStudents = [];
do { const result = await client.students.list({ limit: 100, cursor });
allStudents.push(...result.data); cursor = result.pagination.nextCursor; } while (cursor); ```
Caching
```javascript const NodeCache = require('node-cache'); const cache = new NodeCache({ stdTTL: 300 }); // 5 minutes
async function getCachedStudent(id) {
const cacheKey = student:${id};
let student = cache.get(cacheKey);
if (!student) { student = await client.students.get(id); cache.set(cacheKey, student); }
return student; } ```
🛠️ Troubleshooting
Common Issues
Authentication Errors
```javascript // Check your API key format if (!apiKey.startsWith('ciq_')) { throw new Error('Invalid API key format'); }
// Verify school ID if (!schoolId.match(/^[0-9a-f]{24}$/)) { throw new Error('Invalid school ID format'); } ```
Rate Limiting
```javascript
try {
const result = await client.students.list();
} catch (error) {
if (error.code === 'RATE_LIMIT_EXCEEDED') {
const retryAfter = error.retryAfter; // seconds
console.log(Rate limited. Retry after ${retryAfter} seconds);
// Wait and retry
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
const result = await client.students.list();} } ```
Network Issues
```javascript const client = new CampusIQClient({ apiKey: 'your-api-key', schoolId: 'your-school-id', retries: 3, retryDelay: 1000, // 1 second timeout: 30000 // 30 seconds }); ```
Debug Mode
```javascript const client = new CampusIQClient({ apiKey: 'your-api-key', schoolId: 'your-school-id', debug: true // Enable debug logging }); ```
📞 Support
- Documentation: https://docs.campusiq.edu
- API Reference: https://api.campusiq.edu/docs
- Support Email: [email protected]
- GitHub Issues: https://github.com/campusiq/sdk-js/issues
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
```bash git clone https://github.com/campusiq/sdk-js.git cd sdk-js npm install npm run build npm test ```
Running Tests
```bash
Unit tests
npm test
Integration tests
npm run test:integration
Coverage
npm run test:coverage ```
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔄 Changelog
See CHANGELOG.md for a list of changes and version history.
Made with ❤️ by the CampusIQ Team
For more information, visit https://campusiq.edu
