SDK Documentation
Official client libraries — handles auth, errors, and types automatically.
Installation
Initialize
import { BetterSpace } from '@betterspace/sdk';
const bs = new BetterSpace('bs_live_your_api_key');Module Reference
bs.usersRegister and manage usersbs.users.register(externalId, email, options?)Register a user. Auto-creates BetterSpace profile if email doesn't exist.
const user = await bs.users.register('emp-001', 'priya@company.com', {
name: 'Priya Sharma',
phone: '+919876543210',
gender: 'female'
});
// → { status: "created_new", external_id: "emp-001", betterspace_user_id: "uuid" }bs.users.list(params?)List all registered users for your tenant.
const { users } = await bs.users.list({ page: 1, limit: 20 });bs.users.get(externalId)Get a specific user by their external ID.
const user = await bs.users.get('emp-001');bs.assessmentsMental health screenings with AI insightsbs.assessments.types()List available assessment types (PHQ-9, GAD-7, PSS-10, WHO-5, DASS-21).
const types = await bs.assessments.types();
// → [{ id: "phq9", name: "PHQ-9", questions: 9 }, ...]bs.assessments.submit(userId, type, answers)Submit answers and get scored results with severity classification.
const result = await bs.assessments.submit('emp-001', 'phq9', [1,2,1,3,0,1,2,1,0]);
// → { score: 11, severity: "moderate", max_score: 27 }bs.assessments.insights(type, score, severity)Get AI-generated personalized recommendations based on score.
const insights = await bs.assessments.insights('phq9', 11, 'moderate');bs.chatAI wellness companion (Rooh)bs.chat.message(userId, message, sessionId?)Send a message and get an AI wellness response.
const chat = await bs.chat.message('emp-001', 'I feel stressed about work');
console.log(chat.response); // "I hear you. Work stress can feel overwhelming..."bs.crisisReal-time crisis text analysisbs.crisis.analyze(text, userId?)Analyze text for suicide ideation, self-harm, or severe distress.
const result = await bs.crisis.analyze('I feel like there is no way out');
if (result.is_crisis) {
console.log(result.category); // "crisis_distress"
console.log(result.severity); // "high"
}bs.therapistsSearch and book therapistsbs.therapists.search(filters?)Search verified therapists with optional filters.
const { therapists } = await bs.therapists.search({
specialization: 'Anxiety',
language: 'Hindi',
max_price: 2000
});bs.therapists.availability(therapistId, date)Get available time slots for a specific date.
const slots = await bs.therapists.availability('uuid', '2026-06-15');bs.bookingsTherapy session managementbs.bookings.create(userId, therapistId, date, startTime, options?)Create a therapy session booking.
const booking = await bs.bookings.create('emp-001', 'therapist-uuid', '2026-06-15', '10:00');
// → { booking_id: "uuid", booking_number: "BS-XXX", status: "pending" }bs.moodMood logging and trendsbs.mood.log(userId, moodValue, options?)Log a mood entry (1-5 scale).
await bs.mood.log('emp-001', 4, { activities: ['work', 'exercise'], note: 'Good day' });
// → { logged: true, mood_id: "uuid" }bs.mood.trends(userId, period?)Get mood history and average.
const trends = await bs.mood.trends('emp-001', 'weekly');bs.teamsCorporate wellness analyticsbs.teams.burnoutScore(teamId)Calculate team burnout risk score (0-100).
const score = await bs.teams.burnoutScore('team-uuid');
// → { burnout_risk_score: 45, risk_level: "moderate" }bs.sleepSleep tracking and scoringbs.sleep.log(userId, bedtime, wakeTime, quality?)Log a sleep entry and get a sleep score.
const sleep = await bs.sleep.log('emp-001', '2026-05-27T23:30:00Z', '2026-05-28T07:00:00Z', 4);
// → { logged: true, duration_hours: 7.5, sleep_score: 88 }bs.webhooksReal-time event notificationsbs.webhooks.create(url, events, description?)Register a webhook endpoint.
const wh = await bs.webhooks.create( 'https://your-app.com/webhooks', ['booking.completed', 'crisis.detected', 'mood.logged'] ); console.log(wh.secret); // Store this securely!
Error Handling
All SDK methods throw typed errors with code, status, and message.
import { BetterSpace, BetterSpaceError } from '@betterspace/sdk';
try {
await bs.mood.log('unknown-user', 4);
} catch (err) {
if (err instanceof BetterSpaceError) {
console.log(err.code); // "user_not_found"
console.log(err.status); // 404
console.log(err.message); // "User with external_id 'unknown-user' not found"
}
}| Error Code | Status | When |
|---|---|---|
| missing_api_key | 401 | API key not provided |
| invalid_api_key | 401 | Key invalid or expired |
| module_not_subscribed | 403 | Module not in subscription |
| rate_limit_exceeded | 429 | Too many requests |
| user_not_found | 404 | External user ID not registered |
| invalid_request | 400 | Missing required parameters |
Complete Integration Example
A typical integration flow for an HR platform:
import { BetterSpace, BetterSpaceError } from '@betterspace/sdk';
const bs = new BetterSpace('bs_live_your_key');
// 1. Register employee when they join
async function onEmployeeJoined(employee) {
const user = await bs.users.register(employee.id, employee.email, {
name: employee.name,
phone: employee.phone,
});
console.log('Registered:', user.status); // "created_new" or "linked_existing"
}
// 2. Monthly wellness check
async function runWellnessCheck(employeeId) {
// Get PHQ-9 questions
const { questions } = await bs.assessments.administer(employeeId, 'phq9');
// ... show questions to user, collect answers ...
const answers = [1, 2, 1, 3, 0, 1, 2, 1, 0]; // from user input
// Submit and get results
const result = await bs.assessments.submit(employeeId, 'phq9', answers);
if (result.severity === 'severe' || result.severity === 'moderately_severe') {
// Suggest therapy
const { therapists } = await bs.therapists.search({ specialization: 'Depression' });
return { result, suggestedTherapists: therapists.slice(0, 3) };
}
return { result };
}
// 3. Daily mood tracking
async function logDailyMood(employeeId, mood, activities) {
await bs.mood.log(employeeId, mood, { activities });
}
// 4. Team dashboard
async function getTeamHealth(teamId) {
const [analytics, burnout] = await Promise.all([
bs.teams.analytics(teamId),
bs.teams.burnoutScore(teamId),
]);
return { ...analytics, burnout };
}
// 5. Crisis monitoring
async function checkMessage(employeeId, message) {
const result = await bs.crisis.analyze(message, employeeId);
if (result.is_crisis) {
// Alert HR immediately
notifyHR(employeeId, result.category, result.severity);
}
}