Comprehensive code examples for the Lilith API in multiple programming languages.
Overview#
This document provides complete, working code examples for all major API operations. Examples are provided in:
- cURL - Command-line HTTP requests
- JavaScript/TypeScript - Node.js and browser
- Python - Using requests library
- Go - Using net/http
Setup#
Environment Variables#
bash
# Set these in your environment
export LILITH_API_KEY="your_api_key"
export LILITH_API_URL="https://api.lilith.app"
Base Configuration#
JavaScript/TypeScript:
typescript
const API_URL = process.env.LILITH_API_URL || 'https://api.lilith.app';
let authToken: string;
async function apiRequest(
endpoint: string,
options: RequestInit = {}
): Promise<any> {
const response = await fetch(`${API_URL}${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authToken}`,
...options.headers,
},
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || `HTTP ${response.status}`);
}
return response.json();
}
Python:
python
import os
import requests
API_URL = os.environ.get('LILITH_API_URL', 'https://api.lilith.app')
auth_token = None
def api_request(endpoint, method='GET', data=None):
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {auth_token}'
}
response = requests.request(
method,
f'{API_URL}{endpoint}',
headers=headers,
json=data
)
response.raise_for_status()
return response.json()
Go:
go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
var (
apiURL = getEnv("LILITH_API_URL", "https://api.lilith.app")
authToken string
)
func getEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
func apiRequest(endpoint, method string, body interface{}) (map[string]interface{}, error) {
var reqBody io.Reader
if body != nil {
jsonBody, _ := json.Marshal(body)
reqBody = bytes.NewBuffer(jsonBody)
}
req, _ := http.NewRequest(method, apiURL+endpoint, reqBody)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+authToken)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
return result, nil
}
Authentication#
Login#
cURL:
bash
curl -X POST "${LILITH_API_URL}/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "secure_password"
}'
JavaScript:
javascript
async function login(email, password) {
const response = await fetch(`${API_URL}/v1/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await response.json();
authToken = data.access_token;
return {
accessToken: data.access_token,
refreshToken: data.refresh_token,
expiresIn: data.expires_in,
user: data.user,
};
}
// Usage
const auth = await login('user@example.com', 'secure_password');
console.log('Logged in as:', auth.user.email);
Python:
python
def login(email, password):
global auth_token
response = requests.post(
f'{API_URL}/v1/auth/login',
json={'email': email, 'password': password}
)
response.raise_for_status()
data = response.json()
auth_token = data['access_token']
return {
'access_token': data['access_token'],
'refresh_token': data['refresh_token'],
'expires_in': data['expires_in'],
'user': data['user']
}
# Usage
auth = login('user@example.com', 'secure_password')
print(f"Logged in as: {auth['user']['email']}")
Go:
go
func login(email, password string) (map[string]interface{}, error) {
body := map[string]string{
"email": email,
"password": password,
}
jsonBody, _ := json.Marshal(body)
resp, err := http.Post(
apiURL+"/v1/auth/login",
"application/json",
bytes.NewBuffer(jsonBody),
)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
authToken = result["access_token"].(string)
return result, nil
}
Refresh Token#
cURL:
bash
curl -X POST "${LILITH_API_URL}/v1/auth/refresh" \
-H "Content-Type: application/json" \
-d '{
"refresh_token": "your_refresh_token"
}'
JavaScript:
javascript
async function refreshToken(refreshToken) {
const response = await fetch(`${API_URL}/v1/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: refreshToken }),
});
const data = await response.json();
authToken = data.access_token;
return data;
}
Python:
python
def refresh_token(refresh_token):
global auth_token
response = requests.post(
f'{API_URL}/v1/auth/refresh',
json={'refresh_token': refresh_token}
)
response.raise_for_status()
data = response.json()
auth_token = data['access_token']
return data
Chat Completions#
Basic Chat#
cURL:
bash
curl -X POST "${LILITH_API_URL}/v1/chat/completions" \
-H "Authorization: Bearer ${TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "system", "content": "You are a wise meditation teacher."},
{"role": "user", "content": "How do I start meditating?"}
],
"persona": "zen_master",
"max_tokens": 500,
"temperature": 0.7
}'
JavaScript:
javascript
async function chat(messages, options = {}) {
return apiRequest('/v1/chat/completions', {
method: 'POST',
body: JSON.stringify({
messages,
persona: options.persona || 'default',
max_tokens: options.maxTokens || 500,
temperature: options.temperature || 0.7,
...options,
}),
});
}
// Usage
const response = await chat(
[
{ role: 'system', content: 'You are a wise meditation teacher.' },
{ role: 'user', content: 'How do I start meditating?' },
],
{
persona: 'zen_master',
maxTokens: 500,
}
);
console.log('Response:', response.content);
console.log('Tokens used:', response.usage.total_tokens);
Python:
python
def chat(messages, persona='default', max_tokens=500, temperature=0.7):
return api_request('/v1/chat/completions', 'POST', {
'messages': messages,
'persona': persona,
'max_tokens': max_tokens,
'temperature': temperature
})
# Usage
response = chat([
{'role': 'system', 'content': 'You are a wise meditation teacher.'},
{'role': 'user', 'content': 'How do I start meditating?'}
], persona='zen_master')
print(f"Response: {response['content']}")
print(f"Tokens used: {response['usage']['total_tokens']}")
Go:
go
func chat(messages []map[string]string, persona string) (map[string]interface{}, error) {
body := map[string]interface{}{
"messages": messages,
"persona": persona,
"max_tokens": 500,
"temperature": 0.7,
}
return apiRequest("/v1/chat/completions", "POST", body)
}
// Usage
messages := []map[string]string{
{"role": "system", "content": "You are a wise meditation teacher."},
{"role": "user", "content": "How do I start meditating?"},
}
response, _ := chat(messages, "zen_master")
fmt.Printf("Response: %v\n", response["content"])
Streaming Chat#
JavaScript:
javascript
async function streamChat(messages, onChunk) {
const response = await fetch(`${API_URL}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authToken}`,
},
body: JSON.stringify({
messages,
stream: true,
}),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') return;
try {
const chunk = JSON.parse(data);
onChunk(chunk);
} catch (e) {
// Skip invalid JSON
}
}
}
}
}
// Usage
let fullResponse = '';
await streamChat(
[{ role: 'user', content: 'Tell me a short zen story' }],
(chunk) => {
const content = chunk.choices?.[0]?.delta?.content || '';
fullResponse += content;
process.stdout.write(content);
}
);
Python:
python
import json
def stream_chat(messages, on_chunk):
response = requests.post(
f'{API_URL}/v1/chat/completions',
headers={
'Content-Type': 'application/json',
'Authorization': f'Bearer {auth_token}'
},
json={'messages': messages, 'stream': True},
stream=True
)
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
data = line[6:]
if data == '[DONE]':
break
try:
chunk = json.loads(data)
on_chunk(chunk)
except json.JSONDecodeError:
pass
# Usage
full_response = []
def handle_chunk(chunk):
content = chunk.get('choices', [{}])[0].get('delta', {}).get('content', '')
full_response.append(content)
print(content, end='', flush=True)
stream_chat([
{'role': 'user', 'content': 'Tell me a short zen story'}
], handle_chunk)
print('\n\nFull response:', ''.join(full_response))
Content API#
List Courses#
cURL:
bash
curl -X GET "${LILITH_API_URL}/v1/content/courses?page=1&limit=20&status=published" \
-H "Authorization: Bearer ${TOKEN}"
JavaScript:
javascript
async function listCourses(options = {}) {
const params = new URLSearchParams({
page: options.page || 1,
limit: options.limit || 20,
sortBy: options.sortBy || 'created_at',
sortOrder: options.sortOrder || 'desc',
...(options.status && { status: options.status }),
...(options.tradition && { tradition: options.tradition }),
});
return apiRequest(`/v1/content/courses?${params}`);
}
// Usage
const courses = await listCourses({
page: 1,
limit: 10,
status: 'published',
tradition: 'zen',
});
console.log(`Found ${courses.total} courses`);
courses.items.forEach((course) => {
console.log(`- ${course.title} (${course.lesson_count} lessons)`);
});
Python:
python
def list_courses(page=1, limit=20, status=None, tradition=None):
params = {
'page': page,
'limit': limit,
'sortBy': 'created_at',
'sortOrder': 'desc'
}
if status:
params['status'] = status
if tradition:
params['tradition'] = tradition
response = requests.get(
f'{API_URL}/v1/content/courses',
headers={'Authorization': f'Bearer {auth_token}'},
params=params
)
response.raise_for_status()
return response.json()
# Usage
courses = list_courses(page=1, limit=10, status='published')
print(f"Found {courses['total']} courses")
for course in courses['items']:
print(f"- {course['title']} ({course['lesson_count']} lessons)")
Get Course Details#
cURL:
bash
curl -X GET "${LILITH_API_URL}/v1/content/courses/course_abc123" \
-H "Authorization: Bearer ${TOKEN}"
JavaScript:
javascript
async function getCourse(courseId) {
return apiRequest(`/v1/content/courses/${courseId}`);
}
// Usage
const course = await getCourse('course_abc123');
console.log(`Course: ${course.title}`);
console.log(`Description: ${course.description}`);
console.log(`Lessons: ${course.lessons.length}`);
Python:
python
def get_course(course_id):
return api_request(f'/v1/content/courses/{course_id}')
# Usage
course = get_course('course_abc123')
print(f"Course: {course['title']}")
print(f"Description: {course['description']}")
print(f"Lessons: {len(course['lessons'])}")
List Meditations#
cURL:
bash
curl -X GET "${LILITH_API_URL}/v1/content/meditations?duration_min=5&duration_max=15" \
-H "Authorization: Bearer ${TOKEN}"
JavaScript:
javascript
async function listMeditations(options = {}) {
const params = new URLSearchParams({
page: options.page || 1,
limit: options.limit || 20,
...(options.durationMin && { duration_min: options.durationMin }),
...(options.durationMax && { duration_max: options.durationMax }),
...(options.difficulty && { difficulty: options.difficulty }),
...(options.tradition && { tradition: options.tradition }),
});
return apiRequest(`/v1/content/meditations?${params}`);
}
// Usage - Find short meditations for beginners
const meditations = await listMeditations({
durationMin: 5,
durationMax: 15,
difficulty: 'beginner',
});
meditations.items.forEach((m) => {
console.log(`${m.title} - ${Math.round(m.duration_seconds / 60)} min`);
});
Python:
python
def list_meditations(duration_min=None, duration_max=None, difficulty=None):
params = {'page': 1, 'limit': 20}
if duration_min:
params['duration_min'] = duration_min
if duration_max:
params['duration_max'] = duration_max
if difficulty:
params['difficulty'] = difficulty
response = requests.get(
f'{API_URL}/v1/content/meditations',
headers={'Authorization': f'Bearer {auth_token}'},
params=params
)
response.raise_for_status()
return response.json()
# Usage - Find short meditations for beginners
meditations = list_meditations(duration_min=5, duration_max=15, difficulty='beginner')
for m in meditations['items']:
print(f"{m['title']} - {m['duration_seconds'] // 60} min")
Search API#
Full-Text Search#
cURL:
bash
curl -X GET "${LILITH_API_URL}/v1/search?q=mindfulness&type=meditation&from=0&size=20" \
-H "Authorization: Bearer ${TOKEN}"
JavaScript:
javascript
async function search(query, options = {}) {
const params = new URLSearchParams({
q: query,
from: options.from || 0,
size: options.size || 20,
...(options.type && { type: options.type }),
...(options.tradition && { tradition: options.tradition }),
});
return apiRequest(`/v1/search?${params}`);
}
// Usage
const results = await search('mindfulness', {
type: 'meditation',
size: 10,
});
console.log(`Found ${results.total} results`);
results.items.forEach((item) => {
console.log(`[${item.type}] ${item.title} (score: ${item.score.toFixed(2)})`);
});
Python:
python
def search(query, content_type=None, from_offset=0, size=20):
params = {
'q': query,
'from': from_offset,
'size': size
}
if content_type:
params['type'] = content_type
response = requests.get(
f'{API_URL}/v1/search',
headers={'Authorization': f'Bearer {auth_token}'},
params=params
)
response.raise_for_status()
return response.json()
# Usage
results = search('mindfulness', content_type='meditation', size=10)
print(f"Found {results['total']} results")
for item in results['items']:
print(f"[{item['type']}] {item['title']} (score: {item['score']:.2f})")
Media API#
Upload File#
cURL:
bash
curl -X POST "${LILITH_API_URL}/v1/media/upload" \
-H "Authorization: Bearer ${TOKEN}" \
-F "file=@meditation.mp3" \
-F "type=audio" \
-F "title=Morning Meditation"
JavaScript:
javascript
async function uploadMedia(file, metadata) {
const formData = new FormData();
formData.append('file', file);
formData.append('type', metadata.type);
formData.append('title', metadata.title);
if (metadata.description) {
formData.append('description', metadata.description);
}
const response = await fetch(`${API_URL}/v1/media/upload`, {
method: 'POST',
headers: {
Authorization: `Bearer ${authToken}`,
},
body: formData,
});
return response.json();
}
// Usage (Node.js with file system)
const fs = require('fs');
const FormData = require('form-data');
const form = new FormData();
form.append('file', fs.createReadStream('meditation.mp3'));
form.append('type', 'audio');
form.append('title', 'Morning Meditation');
const uploaded = await uploadMedia(form, {
type: 'audio',
title: 'Morning Meditation',
});
console.log('Uploaded:', uploaded.id);
console.log('URL:', uploaded.url);
Python:
python
def upload_media(file_path, media_type, title, description=None):
with open(file_path, 'rb') as f:
files = {'file': f}
data = {
'type': media_type,
'title': title
}
if description:
data['description'] = description
response = requests.post(
f'{API_URL}/v1/media/upload',
headers={'Authorization': f'Bearer {auth_token}'},
files=files,
data=data
)
response.raise_for_status()
return response.json()
# Usage
uploaded = upload_media('meditation.mp3', 'audio', 'Morning Meditation')
print(f"Uploaded: {uploaded['id']}")
print(f"URL: {uploaded['url']}")
Get Signed URL#
cURL:
bash
curl -X GET "${LILITH_API_URL}/v1/media/asset_abc123/signed-url" \
-H "Authorization: Bearer ${TOKEN}"
JavaScript:
javascript
async function getSignedUrl(assetId, expiresIn = 3600) {
return apiRequest(`/v1/media/${assetId}/signed-url?expires_in=${expiresIn}`);
}
// Usage
const { url, expires_at } = await getSignedUrl('asset_abc123', 3600);
console.log('Signed URL:', url);
console.log('Expires:', new Date(expires_at));
Python:
python
def get_signed_url(asset_id, expires_in=3600):
response = requests.get(
f'{API_URL}/v1/media/{asset_id}/signed-url',
headers={'Authorization': f'Bearer {auth_token}'},
params={'expires_in': expires_in}
)
response.raise_for_status()
return response.json()
# Usage
signed = get_signed_url('asset_abc123', 3600)
print(f"Signed URL: {signed['url']}")
print(f"Expires: {signed['expires_at']}")
Notifications API#
List Notifications#
cURL:
bash
curl -X GET "${LILITH_API_URL}/v1/notifications?limit=20&status=unread" \
-H "Authorization: Bearer ${TOKEN}"
JavaScript:
javascript
async function listNotifications(options = {}) {
const params = new URLSearchParams({
limit: options.limit || 50,
offset: options.offset || 0,
...(options.status && { status: options.status }),
});
return apiRequest(`/v1/notifications?${params}`);
}
// Usage
const notifications = await listNotifications({ status: 'unread' });
console.log(`You have ${notifications.total} unread notifications`);
notifications.items.forEach((n) => {
console.log(`[${n.type}] ${n.title}`);
});
Python:
python
def list_notifications(limit=50, offset=0, status=None):
params = {'limit': limit, 'offset': offset}
if status:
params['status'] = status
response = requests.get(
f'{API_URL}/v1/notifications',
headers={'Authorization': f'Bearer {auth_token}'},
params=params
)
response.raise_for_status()
return response.json()
# Usage
notifications = list_notifications(status='unread')
print(f"You have {notifications['total']} unread notifications")
for n in notifications['items']:
print(f"[{n['type']}] {n['title']}")
Mark as Read#
cURL:
bash
curl -X PATCH "${LILITH_API_URL}/v1/notifications/notif_abc123/read" \
-H "Authorization: Bearer ${TOKEN}"
JavaScript:
javascript
async function markAsRead(notificationId) {
return apiRequest(`/v1/notifications/${notificationId}/read`, {
method: 'PATCH',
});
}
// Mark all as read
async function markAllAsRead(notificationIds) {
return Promise.all(notificationIds.map((id) => markAsRead(id)));
}
Python:
python
def mark_as_read(notification_id):
response = requests.patch(
f'{API_URL}/v1/notifications/{notification_id}/read',
headers={'Authorization': f'Bearer {auth_token}'}
)
response.raise_for_status()
return response.json()
# Mark all as read
def mark_all_as_read(notification_ids):
return [mark_as_read(nid) for nid in notification_ids]
Webhooks API#
Register Webhook#
cURL:
bash
curl -X POST "${LILITH_API_URL}/v1/webhooks" \
-H "Authorization: Bearer ${TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "Content Updates",
"url": "https://example.com/webhooks/lilith",
"events": ["content.created", "content.updated", "content.deleted"]
}'
JavaScript:
javascript
async function createWebhook(name, url, events, options = {}) {
return apiRequest('/v1/webhooks', {
method: 'POST',
body: JSON.stringify({
name,
url,
events,
filters: options.filters,
retryConfig: options.retryConfig,
}),
});
}
// Usage
const webhook = await createWebhook(
'Content Updates',
'https://example.com/webhooks/lilith',
['content.created', 'content.updated'],
{
filters: {
contentTypes: ['meditation', 'course'],
},
}
);
console.log('Webhook ID:', webhook.id);
console.log('Secret:', webhook.secret); // Store securely!
Python:
python
def create_webhook(name, url, events, filters=None):
data = {
'name': name,
'url': url,
'events': events
}
if filters:
data['filters'] = filters
return api_request('/v1/webhooks', 'POST', data)
# Usage
webhook = create_webhook(
'Content Updates',
'https://example.com/webhooks/lilith',
['content.created', 'content.updated'],
filters={'contentTypes': ['meditation', 'course']}
)
print(f"Webhook ID: {webhook['id']}")
print(f"Secret: {webhook['secret']}") # Store securely!
Verify Webhook Signature#
JavaScript:
javascript
const crypto = require('crypto');
function verifyWebhook(payload, signature, timestamp, secret) {
const signedPayload = `${timestamp}.${payload}`;
const expectedSig = crypto
.createHmac('sha256', secret)
.update(signedPayload)
.digest('hex');
const providedSig = signature.replace('sha256=', '');
return crypto.timingSafeEqual(
Buffer.from(expectedSig),
Buffer.from(providedSig)
);
}
// Express middleware
app.post(
'/webhooks/lilith',
express.raw({ type: 'application/json' }),
(req, res) => {
const signature = req.headers['x-webhook-signature'];
const timestamp = req.headers['x-webhook-timestamp'];
const payload = req.body.toString();
if (!verifyWebhook(payload, signature, timestamp, WEBHOOK_SECRET)) {
return res.status(401).json({ error: 'Invalid signature' });
}
const event = JSON.parse(payload);
switch (event.type) {
case 'content.created':
handleContentCreated(event.data);
break;
case 'content.updated':
handleContentUpdated(event.data);
break;
}
res.status(200).json({ received: true });
}
);
Python:
python
import hmac
import hashlib
def verify_webhook(payload, signature, timestamp, secret):
signed_payload = f"{timestamp}.{payload}"
expected_sig = hmac.new(
secret.encode(),
signed_payload.encode(),
hashlib.sha256
).hexdigest()
provided_sig = signature.replace('sha256=', '')
return hmac.compare_digest(expected_sig, provided_sig)
# Flask example
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhooks/lilith', methods=['POST'])
def handle_webhook():
signature = request.headers.get('X-Webhook-Signature')
timestamp = request.headers.get('X-Webhook-Timestamp')
payload = request.get_data(as_text=True)
if not verify_webhook(payload, signature, timestamp, WEBHOOK_SECRET):
return jsonify({'error': 'Invalid signature'}), 401
event = request.get_json()
if event['type'] == 'content.created':
handle_content_created(event['data'])
elif event['type'] == 'content.updated':
handle_content_updated(event['data'])
return jsonify({'received': True}), 200
Error Handling#
Comprehensive Error Handler#
JavaScript:
javascript
class LilithAPIError extends Error {
constructor(response, body) {
super(body.error?.message || body.message || 'API Error');
this.status = response.status;
this.code = body.error?.code || 'unknown_error';
this.details = body.error?.details || {};
this.requestId = body.error?.request_id;
}
}
async function apiRequestWithErrorHandling(endpoint, options = {}) {
const response = await fetch(`${API_URL}${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authToken}`,
...options.headers,
},
});
const body = await response.json();
if (!response.ok) {
throw new LilithAPIError(response, body);
}
return body;
}
// Usage with error handling
try {
const result = await apiRequestWithErrorHandling(
'/v1/content/courses/invalid'
);
} catch (error) {
if (error instanceof LilithAPIError) {
console.error(`API Error [${error.code}]: ${error.message}`);
console.error(`Status: ${error.status}`);
console.error(`Request ID: ${error.requestId}`);
switch (error.status) {
case 401:
// Refresh token and retry
await refreshToken(savedRefreshToken);
break;
case 429:
// Handle rate limiting
const retryAfter = error.details.retry_after || 60;
console.log(`Rate limited. Retry after ${retryAfter}s`);
break;
case 404:
console.log('Resource not found');
break;
}
}
}
Python:
python
class LilithAPIError(Exception):
def __init__(self, response, body):
self.status = response.status_code
self.code = body.get('error', {}).get('code', 'unknown_error')
self.message = body.get('error', {}).get('message', 'API Error')
self.details = body.get('error', {}).get('details', {})
self.request_id = body.get('error', {}).get('request_id')
super().__init__(self.message)
def api_request_with_error_handling(endpoint, method='GET', data=None):
response = requests.request(
method,
f'{API_URL}{endpoint}',
headers={
'Content-Type': 'application/json',
'Authorization': f'Bearer {auth_token}'
},
json=data
)
body = response.json()
if not response.ok:
raise LilithAPIError(response, body)
return body
# Usage with error handling
try:
result = api_request_with_error_handling('/v1/content/courses/invalid')
except LilithAPIError as e:
print(f"API Error [{e.code}]: {e.message}")
print(f"Status: {e.status}")
print(f"Request ID: {e.request_id}")
if e.status == 401:
# Refresh token and retry
refresh_token(saved_refresh_token)
elif e.status == 429:
# Handle rate limiting
retry_after = e.details.get('retry_after', 60)
print(f"Rate limited. Retry after {retry_after}s")
elif e.status == 404:
print("Resource not found")
Complete Client Examples#
TypeScript SDK Wrapper#
typescript
// lilith-client.ts
export class LilithClient {
private baseUrl: string;
private accessToken: string | null = null;
private refreshToken: string | null = null;
constructor(baseUrl = 'https://api.lilith.app') {
this.baseUrl = baseUrl;
}
async login(email: string, password: string) {
const response = await this.request(
'/v1/auth/login',
{
method: 'POST',
body: JSON.stringify({ email, password }),
},
false
);
this.accessToken = response.access_token;
this.refreshToken = response.refresh_token;
return response;
}
async chat(messages: Array<{ role: string; content: string }>, options = {}) {
return this.request('/v1/chat/completions', {
method: 'POST',
body: JSON.stringify({ messages, ...options }),
});
}
async listCourses(options = {}) {
const params = new URLSearchParams(options as Record<string, string>);
return this.request(`/v1/content/courses?${params}`);
}
async search(query: string, options = {}) {
const params = new URLSearchParams({ q: query, ...options } as Record<
string,
string
>);
return this.request(`/v1/search?${params}`);
}
private async request(
endpoint: string,
options: RequestInit = {},
auth = true
) {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(options.headers as Record<string, string>),
};
if (auth && this.accessToken) {
headers['Authorization'] = `Bearer ${this.accessToken}`;
}
const response = await fetch(`${this.baseUrl}${endpoint}`, {
...options,
headers,
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
}
return response.json();
}
}
// Usage
const client = new LilithClient();
await client.login('user@example.com', 'password');
const response = await client.chat([{ role: 'user', content: 'Hello!' }]);
Python SDK Wrapper#
python
# lilith_client.py
import requests
from typing import Optional, List, Dict, Any
class LilithClient:
def __init__(self, base_url: str = 'https://api.lilith.app'):
self.base_url = base_url
self.access_token: Optional[str] = None
self.refresh_token: Optional[str] = None
def login(self, email: str, password: str) -> Dict[str, Any]:
response = self._request('/v1/auth/login', 'POST', {
'email': email,
'password': password
}, auth=False)
self.access_token = response['access_token']
self.refresh_token = response['refresh_token']
return response
def chat(self, messages: List[Dict[str, str]], **options) -> Dict[str, Any]:
return self._request('/v1/chat/completions', 'POST', {
'messages': messages,
**options
})
def list_courses(self, **options) -> Dict[str, Any]:
return self._request('/v1/content/courses', params=options)
def search(self, query: str, **options) -> Dict[str, Any]:
return self._request('/v1/search', params={'q': query, **options})
def _request(
self,
endpoint: str,
method: str = 'GET',
data: Optional[Dict] = None,
params: Optional[Dict] = None,
auth: bool = True
) -> Dict[str, Any]:
headers = {'Content-Type': 'application/json'}
if auth and self.access_token:
headers['Authorization'] = f'Bearer {self.access_token}'
response = requests.request(
method,
f'{self.base_url}{endpoint}',
headers=headers,
json=data,
params=params
)
response.raise_for_status()
return response.json()
# Usage
client = LilithClient()
client.login('user@example.com', 'password')
response = client.chat([
{'role': 'user', 'content': 'Hello!'}
])
Related Documentation#
- Getting Started - Quick start guide
- Authentication - Auth reference
- Rate Limits - Rate limiting details
- Error Codes - Error reference
- Webhooks - Webhook integration