# Getting Started

Welcome to the Lilith API! This guide will help you get up and running with our
AI-powered wisdom platform in just a few minutes.

## Prerequisites

Before you begin, ensure you have:

- A Lilith developer account
  ([sign up here](https://dashboard.lilith.app/signup))
- Basic understanding of REST APIs and JSON
- An HTTP client (cURL, Postman, or your preferred programming language)

### System Requirements

- **API Version**: v1 (current)
- **Transport**: HTTPS only (TLS 1.2+)
- **Format**: JSON request/response bodies
- **Authentication**: JWT Bearer tokens
- **Rate Limits**: 1000 requests/hour (upgradeable)

## API Keys

### 1. Create Your API Key

1. Log in to the [Lilith Developer Dashboard](https://dashboard.lilith.app)
2. Navigate to **API Keys** in the sidebar
3. Click **Generate New Key**
4. Choose your key permissions:
   - **Read**: Access chat, lectures, and content
   - **Write**: Submit content for ingestion
   - **Admin**: Access test endpoints (staff only)
5. Copy and securely store your API key

### 2. Key Management Best Practices

- **Never commit API keys to version control**
- Store keys in environment variables or secure config files
- Rotate keys regularly (recommended: every 90 days)
- Use different keys for development, staging, and production
- Monitor key usage in the dashboard

```bash
# Environment variable example
export LILITH_API_KEY="your_api_key_here"
```

## Authentication

The Lilith API uses JWT (JSON Web Token) authentication. Include your token in
the `Authorization` header of every API request.

### Authentication Flow

```curl
# 1. Authenticate and get JWT token
curl -X POST "https://api.lilith.app/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "your-email@example.com",
    "password": "your-secure-password"
  }'
```

```javascript
// JavaScript/Node.js example
const response = await fetch('https://api.lilith.app/v1/auth/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    email: 'your-email@example.com',
    password: 'your-secure-password',
  }),
});

const auth = await response.json();
const token = auth.token;
```

```kotlin
// Kotlin example
val client = OkHttpClient()
val json = """
{
  "email": "your-email@example.com",
  "password": "your-secure-password"
}
""".trimIndent()

val body = json.toRequestBody("application/json".toMediaType())
val request = Request.Builder()
    .url("https://api.lilith.app/v1/auth/login")
    .post(body)
    .build()

val response = client.newCall(request).execute()
val authData = response.body?.string()
```

```swift
// Swift example
let url = URL(string: "https://api.lilith.app/v1/auth/login")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let loginData: [String: Any] = [
    "email": "your-email@example.com",
    "password": "your-secure-password"
]

request.httpBody = try JSONSerialization.data(withJSONObject: loginData)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    // Handle authentication response
}
task.resume()
```

### Using Your JWT Token

Once authenticated, include the JWT token in all subsequent requests:

```bash
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

## First API Call

Let's make your first API call to check system health and verify your setup:

### Health Check

```curl
curl -X GET "https://api.lilith.app/v1/health" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

```javascript
const healthResponse = await fetch('https://api.lilith.app/v1/health', {
  headers: {
    Authorization: `Bearer ${token}`,
  },
});

const health = await healthResponse.json();
console.log('API Status:', health.status);
```

```kotlin
val request = Request.Builder()
    .url("https://api.lilith.app/v1/health")
    .addHeader("Authorization", "Bearer $token")
    .build()

val response = client.newCall(request).execute()
println("API Status: ${response.body?.string()}")
```

```swift
var request = URLRequest(url: URL(string: "https://api.lilith.app/v1/health")!)
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let data = data {
        print("API Status: \(String(data: data, encoding: .utf8) ?? "")")
    }
}
task.resume()
```

**Expected Response:**

```json
{
  "status": "ok",
  "uptime_s": 86400,
  "version": "1.0.0",
  "services": {
    "chat": "healthy",
    "tts": "healthy",
    "ingestion": "healthy"
  }
}
```

### Your First Chat Interaction

Now let's create a simple chat interaction with an AI wisdom persona:

```curl
curl -X POST "https://api.lilith.app/v1/chat" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "persona": "zen_master",
    "input": {
      "text": "What is the essence of mindfulness?"
    },
    "mode": "text",
    "options": {
      "cite": true,
      "depth": "practical",
      "stream": false
    }
  }'
```

```javascript
const chatResponse = await fetch('https://api.lilith.app/v1/chat', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    persona: 'zen_master',
    input: {
      text: 'What is the essence of mindfulness?',
    },
    mode: 'text',
    options: {
      cite: true,
      depth: 'practical',
      stream: false,
    },
  }),
});

const chat = await chatResponse.json();
console.log('AI Response:', chat.text);
```

```kotlin
val chatJson = """
{
  "persona": "zen_master",
  "input": {
    "text": "What is the essence of mindfulness?"
  },
  "mode": "text",
  "options": {
    "cite": true,
    "depth": "practical",
    "stream": false
  }
}
""".trimIndent()

val chatBody = chatJson.toRequestBody("application/json".toMediaType())
val chatRequest = Request.Builder()
    .url("https://api.lilith.app/v1/chat")
    .addHeader("Authorization", "Bearer $token")
    .post(chatBody)
    .build()

val chatResponse = client.newCall(chatRequest).execute()
println("AI Response: ${chatResponse.body?.string()}")
```

```swift
let chatData: [String: Any] = [
    "persona": "zen_master",
    "input": [
        "text": "What is the essence of mindfulness?"
    ],
    "mode": "text",
    "options": [
        "cite": true,
        "depth": "practical",
        "stream": false
    ]
]

var chatRequest = URLRequest(url: URL(string: "https://api.lilith.app/v1/chat")!)
chatRequest.httpMethod = "POST"
chatRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
chatRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
chatRequest.httpBody = try JSONSerialization.data(withJSONObject: chatData)

let chatTask = URLSession.shared.dataTask(with: chatRequest) { data, response, error in
    if let data = data {
        let chatResult = try? JSONSerialization.jsonObject(with: data)
        print("AI Response: \(chatResult)")
    }
}
chatTask.resume()
```

**Expected Response:**

```json
{
  "message_id": "msg_abc123",
  "conversation_id": "conv_def456",
  "text": "The essence of mindfulness lies in bringing your full attention to the present moment, without judgment. It's about observing your thoughts, feelings, and sensations as they arise, acknowledging them with kindness, and gently returning your focus to the here and now.",
  "citations": [
    {
      "source_uri": "buddhist_teachings.pdf",
      "span": { "start": 0, "end": 85 },
      "confidence": 0.95,
      "license": "CC-BY-SA-4.0"
    }
  ],
  "audio_url": null
}
```

## Error Handling

The Lilith API uses standard HTTP status codes and provides detailed error
information:

### Common Error Responses

#### 400 Bad Request

```json
{
  "code": "VALIDATION_ERROR",
  "message": "Required field 'persona' is missing from the request",
  "details": {
    "field": "persona",
    "provided": null,
    "expected": "string (zen_master, philosopher, stoic, mystic, teacher)"
  },
  "trace_id": "550e8400-e29b-41d4-a716-446655440000"
}
```

#### 401 Unauthorized

```json
{
  "code": "INVALID_TOKEN",
  "message": "JWT token is expired or invalid",
  "trace_id": "550e8400-e29b-41d4-a716-446655440001"
}
```

#### 429 Rate Limited

```json
{
  "code": "RATE_LIMIT_EXCEEDED",
  "message": "API rate limit exceeded. Please retry after 60 seconds.",
  "details": {
    "limit": 1000,
    "remaining": 0,
    "reset_time": "2023-12-01T13:00:00Z"
  },
  "trace_id": "550e8400-e29b-41d4-a716-446655440002"
}
```

### Error Handling Best Practices

```javascript
async function makeAPICall(endpoint, data) {
  try {
    const response = await fetch(`https://api.lilith.app${endpoint}`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      const error = await response.json();

      switch (response.status) {
        case 400:
          console.error('Validation Error:', error.message);
          break;
        case 401:
          console.error('Authentication Error:', error.message);
          // Refresh token or redirect to login
          break;
        case 429:
          console.error('Rate Limit Exceeded:', error.message);
          // Wait and retry after the specified time
          break;
        case 500:
          console.error(
            'Server Error:',
            error.message,
            'Trace ID:',
            error.trace_id
          );
          // Log trace_id for support
          break;
        default:
          console.error('API Error:', error.message);
      }

      throw new Error(`API Error: ${error.message}`);
    }

    return await response.json();
  } catch (error) {
    console.error('Request failed:', error);
    throw error;
  }
}
```

## Rate Limits

The Lilith API implements rate limiting to ensure fair usage and system
stability:

### Rate Limit Details

| Plan           | Requests/Hour | Concurrent | Streaming |
| -------------- | ------------- | ---------- | --------- |
| **Free**       | 1,000         | 5          | 2         |
| **Pro**        | 10,000        | 20         | 10        |
| **Enterprise** | 100,000+      | 100+       | 50+       |

### Rate Limit Headers

Every API response includes rate limit information:

```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1701432000
Retry-After: 3600
```

### Handling Rate Limits

```javascript
function handleRateLimit(response) {
  const remaining = parseInt(response.headers.get('X-RateLimit-Remaining'));
  const reset = parseInt(response.headers.get('X-RateLimit-Reset'));

  if (remaining < 10) {
    const resetTime = new Date(reset * 1000);
    console.warn(
      `Rate limit warning: ${remaining} requests remaining until ${resetTime}`
    );
  }

  if (response.status === 429) {
    const retryAfter = parseInt(response.headers.get('Retry-After'));
    console.log(`Rate limited. Retry after ${retryAfter} seconds`);

    // Implement exponential backoff
    setTimeout(() => {
      // Retry the request
    }, retryAfter * 1000);
  }
}
```

## Environment Setup

### Development Environment

```bash
# Set environment variables
export LILITH_API_BASE_URL="https://staging-api.lilith.app"
export LILITH_API_TOKEN="your_staging_token"
export LILITH_DEBUG="true"
```

### Production Environment

```bash
# Production settings
export LILITH_API_BASE_URL="https://api.lilith.app"
export LILITH_API_TOKEN="your_production_token"
export LILITH_DEBUG="false"
```

### Configuration File Example

```json
{
  "development": {
    "baseURL": "https://staging-api.lilith.app",
    "timeout": 30000,
    "debug": true,
    "retryAttempts": 3
  },
  "production": {
    "baseURL": "https://api.lilith.app",
    "timeout": 10000,
    "debug": false,
    "retryAttempts": 5
  }
}
```

## Next Steps

Congratulations! You've successfully made your first API calls. Here's what to
explore next:

### 🚀 Core Features

- **[Chat Integration](./chat-integration.md)** - Build conversational AI
  experiences
- **[Audio Streaming](./audio-streaming.md)** - Add voice synthesis and
  streaming
- **[WebSocket API](./websocket-integration.md)** - Real-time bidirectional
  communication

### 📚 Advanced Topics

- **[Authentication Guide](./authentication.md)** - Detailed authentication
  patterns
- **[Offline Support](./offline-support.md)** - Building offline-capable
  applications
- **[Error Handling](../reference/error-codes.md)** - Comprehensive error
  reference

### 🛠️ SDKs and Tools

- **[TypeScript SDK](../sdk-guides/typescript-integration.md)** - Official
  TypeScript/JavaScript SDK
- **[Android SDK](../sdk-guides/android-kotlin-integration.md)** - Native
  Android integration
- **[iOS SDK](../sdk-guides/ios-swift-integration.md)** - Native iOS integration

### 📖 Examples and Tutorials

- **[Authentication Flow](../examples/authentication-flow.md)** - Complete auth
  implementation
- **[Chat Conversation](../examples/chat-conversation.md)** - Building chat
  interfaces
- **[Audio Streaming](../examples/audio-streaming.md)** - Voice-enabled
  applications

### 🔧 Development Tools

- **[Postman Collection](https://www.postman.com/lilith-api/workspace/lilith-api)** -
  Ready-to-use API collection
- **[OpenAPI Specification](../api-specs/enhanced-openapi.yaml)** - Complete API
  schema
- **[Mock Server](https://mock-api.lilith.app)** - Test without affecting
  production

### 💬 Support and Community

- **[Community Forum](https://community.lilith.app)** - Connect with other
  developers
- **[GitHub Issues](https://github.com/lilith/platform/issues)** - Report bugs
  and request features
- **[Discord Server](https://discord.gg/lilith-dev)** - Real-time chat with the
  community
- **[Email Support](mailto:api-support@lilith.app)** - Direct support from our
  team

### 📊 Monitoring and Analytics

- **[Developer Dashboard](https://dashboard.lilith.app)** - Monitor usage and
  manage keys
- **[Status Page](https://status.lilith.app)** - Real-time system status
- **[API Metrics](https://dashboard.lilith.app/metrics)** - Performance
  analytics

---

## Quick Reference

### Base URLs

- **Production**: `https://api.lilith.app`
- **Staging**: `https://staging-api.lilith.app`
- **Mock Server**: `https://mock-api.lilith.app`

### Essential Endpoints

| Endpoint             | Method | Description              |
| -------------------- | ------ | ------------------------ |
| `/v1/health`         | GET    | System health check      |
| `/v1/auth/login`     | POST   | User authentication      |
| `/v1/chat`           | POST   | Chat with AI personas    |
| `/v1/lectures`       | POST   | Generate wisdom lectures |
| `/v1/tts/synthesize` | POST   | Text-to-speech synthesis |

### HTTP Headers

```http
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json
Accept: application/json
User-Agent: YourApp/1.0.0
```

### Response Formats

- **Success**: HTTP 200/201 with JSON response
- **Client Error**: HTTP 4xx with error details
- **Server Error**: HTTP 5xx with trace ID
- **Streaming**: `text/event-stream` for real-time data

Ready to build something amazing? Let's get started! 🚀
