π LunarBit API Gateway
Enterprise-grade API Gateway and AI Proxy System for Lunarbit Studios services.
Version: 2.0.0
Base URL: https://api.lunarbit.dev/
Status: Production
Last Updated: February 7, 2026
Compliance: LunarCore Spec v1 β
This major update brings enterprise-grade features:
- π€ Multi-provider AI Gateway with intelligent routing
- π Advanced API key management with granular permissions
- ποΈ Clean architecture with full LunarCore compliance
- π Structured logging and comprehensive error handling
- π Enhanced security and deployment options
Overviewβ
The LunarBit API Gateway provides production-grade access to project metadata, version management, AI capabilities, and automated update checking for all LunarBit projects. Built with clean architecture principles and full LunarCore compliance, this RESTful API enables developers to integrate sophisticated version management and AI-powered features into their applications.
Key Featuresβ
- AI Gateway & Proxy - Multi-provider AI support with intelligent routing and automatic failover
- Version Management - Hierarchical project β channel β version β build architecture
- Auto-Updates - Safe update system with breaking change detection and compatibility checking
- Build Verification - Automatic health checks and checksum validation
- Advanced Authentication - Granular API key permissions with usage tracking
- Enterprise Security - Rate limiting, CORS protection, and OWASP-compliant headers
- GitHub Integration - Automatic synchronization with GitHub releases
LunarCore Complianceβ
This API fully implements the LunarCore Specification v1.0.0:
- β LC-VER: Semantic versioning with VERSION constant exposed
- β LC-LOG: Structured JSON logging with sensitive data redaction
- β LC-CFG: Environment-based configuration with sensible defaults
- β LC-ERR: Consistent error hierarchy with LC_ERR_* error codes
- β LC-SEC: Security-first defaults (HTTPS, API keys, rate limiting)
- β LC-NAM: Consistent naming conventions (camelCase, PascalCase, etc.)
Architectureβ
Clean Architecture Overviewβ
The API follows clean architecture principles with clear separation of concerns:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Lunarbit API Gateway β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β βββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β Routes ββ β Middleware ββ β Controllers β β
β βββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β β β
β ββββββββ΄ββββββββββββββββββββββββββββββββββββββ΄βββββββββ β
β β Services Layer β β
β β ProjectService β AIService β AuthService β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β β β
β ββββββββ΄βββββββββ ββββββ΄βββββββββ ββββββ΄βββββββββ β
β β GitHub API β β AI Providersβ β Storage β β
β βββββββββββββββββ βββββββββββββββ βββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Layer Structure:
- API Layer: HTTP routes, controllers, middleware, input validation
- Core Layer: Business logic services, external provider integrations, data access
- Infrastructure Layer: Database connections, caching, structured logging, metrics
- Shared Layer: Custom error classes, application constants, TypeScript types, utilities
AI Provider Architectureβ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Model Router (β
Implemented) β
β β’ Priority-based routing β
β β’ Round-robin load balancing β
β β’ Least-loaded selection β
β β’ Fastest provider selection β
β β’ Automatic failover β
ββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
βββββββββββ΄ββββββββββ¬βββββββββββ¬βββββββββββββ
β β β β
ββββββββ΄ββββββββ βββββββββ΄βββββββ ββ΄βββββββββ ββ΄ββββββββ
β LM Studio β β OpenAI β βAnthropicβ β Custom β
β (β
Done) β β (β
Done) β β(Design) β β(Ready) β
ββββββββββββββββ ββββββββββββββββ βββββββββββ ββββββββββ
Getting Startedβ
Authenticationβ
To use the API, you'll need an API key. Request one by contacting us at api@lunarbit.dev or through our Discord server.
Include your API key in the Authorization header:
Authorization: Bearer your_api_key_here
Quick Exampleβ
# Check API status
curl https://api.lunarbit.dev/health
# List available projects (requires auth)
curl -H "Authorization: Bearer YOUR_KEY" \
https://api.lunarbit.dev/projects
# Check AI provider status (no auth required)
curl https://api.lunarbit.dev/ai/status
# Chat with AI (requires auth)
curl -X POST https://api.lunarbit.dev/ai/chat \
-H "Authorization: Bearer YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"messages":[{"role":"user","content":"Explain semantic versioning"}]}'
AI Capabilitiesβ
Supported Providersβ
| Provider | Status | Features |
|---|---|---|
| LM Studio | β Production | Local models, streaming, no costs |
| OpenAI | β Production | GPT-3.5/4, accurate tokens, streaming |
| Anthropic | π Designed | Claude models, ready to implement |
| Azure OpenAI | π Designed | Enterprise OpenAI access |
| Custom | β Ready | Implement AIProvider interface |
AI Endpointsβ
AI Statusβ
Check available AI providers and models.
Endpoint: GET /ai/status
Authentication: None required
Response:
{
"enabled": true,
"providers": [
{
"name": "lmstudio",
"available": true,
"models": ["llama-3.1-8b-instruct"]
},
{
"name": "openai",
"available": true,
"models": ["gpt-4", "gpt-3.5-turbo"]
}
]
}
Chat Completionβ
Send messages and get AI responses with streaming support.
Endpoint: POST /ai/chat
Authentication: Required
Request Body:
{
"messages": [
{"role": "user", "content": "Explain semantic versioning"}
],
"temperature": 0.7,
"max_tokens": 500,
"stream": false,
"model": "gpt-4"
}
Parameters:
messages(required): Array of message objects withroleandcontenttemperature(optional, 0-2, default 0.7): Response randomnessmax_tokens(optional, default 2000): Maximum response lengthstream(optional, boolean): Enable streaming responsesmodel(optional): Specific model to use
Response:
{
"response": "Semantic versioning (SemVer) is a versioning scheme...",
"model": "gpt-4",
"tokens_used": 156,
"processing_time_ms": 1247
}
Analyze Changelogβ
AI-powered changelog analysis and summarization.
Endpoint: POST /ai/analyze-changelog
Authentication: Required
Request Body:
{
"version": "1.2.0",
"changelog": "- Fixed memory leak\n- Added dark mode\n- Breaking: Removed Node 14 support"
}
Response:
{
"version": "1.2.0",
"analysis": "This update fixes a memory leak, adds dark mode, and drops Node.js 14 (requires Node 16+).",
"breaking": true,
"severity": "major"
}
Model Routing Strategiesβ
The AI gateway supports multiple routing strategies:
- Priority: Use providers in order (fallback on failure)
- Round-Robin: Distribute requests evenly across providers
- Least-Loaded: Route to provider with fewest active requests
- Fastest: Route to provider with best average latency
API Key Managementβ
The API features an advanced key management system with granular permissions and usage tracking.
Permission Systemβ
API keys can have granular permissions:
| Permission | Access |
|---|---|
canReadProjects | GET /projects, GET /projects/:id |
canReadVersions | GET /projects/:id/channels/:channel/latest |
canCheckUpdates | POST /update/check |
canUseAI | POST /ai/chat, POST /ai/analyze-changelog |
canCreateKeys | POST /admin/keys (admin only) |
canRevokeKeys | DELETE /admin/keys/:name (admin only) |
Creating API Keysβ
Endpoint: POST /admin/keys
Authentication: Admin key required
Request Body:
{
"name": "My App Key",
"description": "API key for my application",
"permissions": {
"canReadProjects": true,
"canReadVersions": true,
"canCheckUpdates": true,
"canUseAI": true
},
"rateLimit": 1000,
"expiresIn": "90d",
"allowedProjects": ["trackly"],
"tags": ["mobile-app", "production"]
}
Response:
{
"message": "API key created successfully",
"key": "lbapi_a1b2c3d4e5f6...",
"name": "My App Key",
"permissions": {...},
"createdAt": "2026-02-07T10:00:00Z",
"expiresAt": "2026-05-08T10:00:00Z",
"warning": "Save this key now - it will not be shown again!"
}
Key Featuresβ
- Automatic Expiration: Set
expiresInwhen creating keys (e.g., "30d", "90d") - Rate Limiting: Custom limits per key
- Usage Tracking: Monitor requests, tokens, errors
- Project Restrictions: Limit access to specific projects
- Instant Revocation: Immediately disable compromised keys
- Tagging: Organize keys with custom tags
- Key Prefix: All keys use
lbapi_prefix for easy identification
Managing Keysβ
List API Keysβ
Endpoint: GET /admin/keys
Authentication: Admin key required
Returns all API keys with masked values for security.
Revoke API Keyβ
Endpoint: DELETE /admin/keys/:keyName
Authentication: Admin key required
Immediately revokes a specific API key.
Key Statisticsβ
Endpoint: GET /admin/keys/stats
Authentication: Admin key required
Get usage statistics for all API keys.
Authenticationβ
All API endpoints require authentication via Bearer token in the Authorization header:
Authorization: Bearer your_api_key_here
Rate Limitsβ
To ensure fair usage and API availability, we enforce multiple types of rate limits:
| Type | Limit | Window |
|---|---|---|
| Per API Key | 1,000 requests | 15 minutes |
| Per IP Address | 1,000 requests | 15 minutes |
| AI Endpoints | 100 requests | 1 hour |
| Unauthenticated | 60 requests | 1 hour |
Custom Limits: API keys can have custom rate limits configured when created.
Rate limit status is included in response headers:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 847
X-RateLimit-Reset: 1640995200
If you exceed the rate limit, you'll receive a 429 Too Many Requests response. Implement exponential backoff and respect the rate limits.
Error Handlingβ
All errors follow a consistent format:
{
"error": {
"code": "PROJECT_NOT_FOUND",
"message": "Project 'nonexistent' not found",
"details": {
"project": "nonexistent",
"available_projects": ["trackly", "csviewer"]
},
"documentation_url": "https://docs.lunarbit.dev/api-errors#PROJECT_NOT_FOUND",
"request_id": "req_abc123xyz"
}
}
Common Error Codesβ
| Code | Status | Description |
|---|---|---|
INVALID_REQUEST | 400 | Malformed request body or parameters |
UNAUTHORIZED | 401 | Missing or invalid authentication |
FORBIDDEN | 403 | Insufficient permissions for operation |
NOT_FOUND | 404 | Resource does not exist |
RATE_LIMIT_EXCEEDED | 429 | Too many requests |
INTERNAL_ERROR | 500 | Server-side error occurred |
Endpointsβ
Health Checkβ
Check API availability and response time.
Endpoint: GET /health
Authentication: None required
Response:
{
"status": "healthy",
"timestamp": "2026-02-07T12:00:00Z",
"version": "2.0.0"
}
Projectsβ
List All Projectsβ
Get all available LunarBit projects.
Endpoint: GET /projects
Authentication: Required
Response:
{
"projects": [
{
"id": "trackly",
"name": "Trackly",
"description": "Business asset management system",
"repository": "LunarBit-dev/Trackly",
"channels": ["stable", "beta"],
"created_at": "2025-01-15T10:00:00Z",
"updated_at": "2026-02-07T08:30:00Z"
}
],
"total": 1,
"page": 1,
"per_page": 20
}
Get Project Detailsβ
Retrieve detailed information about a specific project.
Endpoint: GET /projects/{projectId}
Authentication: Required
Path Parameters:
| Parameter | Type | Description |
|---|---|---|
projectId | string | Unique project identifier |
Response:
{
"id": "trackly",
"name": "Trackly",
"description": "Business asset management system with license tracking",
"repository": "LunarBit-dev/Trackly",
"homepage": "https://trackly.lunarbit.dev",
"channels": [
{
"id": "stable",
"name": "Stable",
"description": "Production-ready releases",
"auto_update": true
},
{
"id": "beta",
"name": "Beta",
"description": "Preview releases for testing",
"auto_update": false
}
],
"latest_version": "1.2.5",
"total_downloads": 12847,
"created_at": "2025-01-15T10:00:00Z",
"updated_at": "2026-02-07T08:30:00Z"
}
Versionsβ
List Project Versionsβ
Get all versions for a project in a specific channel.
Endpoint: GET /projects/{projectId}/channels/{channelId}/versions
Authentication: Required
Path Parameters:
| Parameter | Type | Description |
|---|---|---|
projectId | string | Unique project identifier |
channelId | string | Release channel (stable, beta, dev) |
Query Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
page | integer | 1 | Page number |
per_page | integer | 20 | Results per page (max 100) |
sort | string | desc | Sort order (asc or desc) |
Response:
{
"versions": [
{
"id": "1.2.5",
"name": "v1.2.5",
"description": "Bug fixes and performance improvements",
"release_notes": "## Changes\n- Fixed dashboard loading issue\n- Improved query performance",
"breaking_changes": false,
"published_at": "2026-02-05T14:30:00Z",
"downloads": 3421,
"build_count": 2
}
],
"total": 15,
"page": 1,
"per_page": 20
}
Get Version Detailsβ
Retrieve detailed information about a specific version.
Endpoint: GET /projects/{projectId}/channels/{channelId}/versions/{versionId}
Authentication: Required
Response:
{
"id": "1.2.5",
"name": "v1.2.5",
"description": "Bug fixes and performance improvements",
"release_notes": "## Changes\n- Fixed dashboard loading issue\n- Improved query performance\n- Updated dependencies",
"breaking_changes": false,
"published_at": "2026-02-05T14:30:00Z",
"downloads": 3421,
"builds": [
{
"id": "windows-x64",
"platform": "windows",
"architecture": "x64",
"file_size": 125829120,
"download_url": "https://cdn.lunarbit.dev/trackly/1.2.5/trackly-1.2.5-win-x64.exe",
"checksum": {
"sha256": "abc123...",
"md5": "def456..."
}
}
]
}
Buildsβ
Get Build Informationβ
Retrieve information about a specific build.
Endpoint: GET /projects/{projectId}/channels/{channelId}/versions/{versionId}/builds/{buildId}
Authentication: Required
Response:
{
"id": "windows-x64",
"version": "1.2.5",
"platform": "windows",
"architecture": "x64",
"file_name": "trackly-1.2.5-win-x64.exe",
"file_size": 125829120,
"download_url": "https://cdn.lunarbit.dev/trackly/1.2.5/trackly-1.2.5-win-x64.exe",
"checksum": {
"sha256": "abc123def456...",
"md5": "def456abc123..."
},
"created_at": "2026-02-05T14:30:00Z",
"downloads": 1847,
"status": "verified"
}
Download Buildβ
Download a specific build artifact.
Endpoint: GET /projects/{projectId}/channels/{channelId}/versions/{versionId}/builds/{buildId}/download
Authentication: Required
Response: Redirects to CDN download URL
Updatesβ
Check for Updatesβ
Check if updates are available for a specific version.
Endpoint: GET /projects/{projectId}/channels/{channelId}/update
Authentication: Required
Query Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
current_version | string | Yes | Current installed version |
platform | string | Yes | Target platform (windows, macos, linux) |
architecture | string | Yes | Target architecture (x64, arm64) |
Response (Update Available):
{
"update_available": true,
"current_version": "1.2.3",
"latest_version": "1.2.5",
"breaking_changes": false,
"release_notes": "## Changes\n- Fixed dashboard loading\n- Performance improvements",
"download_url": "https://cdn.lunarbit.dev/trackly/1.2.5/trackly-1.2.5-win-x64.exe",
"file_size": 125829120,
"checksum": {
"sha256": "abc123...",
"md5": "def456..."
},
"published_at": "2026-02-05T14:30:00Z"
}
Response (No Updates):
{
"update_available": false,
"current_version": "1.2.5",
"latest_version": "1.2.5",
"message": "You are running the latest version"
}
Launcher Update Checkβ
Advanced update checking for launcher applications with multiple project support.
Endpoint: POST /update/check
Authentication: Required
Request Body:
{
"client": {
"launcher_version": "2.1.0",
"os": "windows",
"os_version": "10.0.19045",
"architecture": "x64"
},
"installed": [
{
"project_id": "trackly",
"version": "1.0.0",
"channel": "stable"
},
{
"project_id": "csviewer",
"version": "2.3.1",
"channel": "beta"
}
]
}
Response:
{
"updates_available": true,
"launcher_update": {
"available": false,
"current": "2.1.0",
"latest": "2.1.0"
},
"project_updates": [
{
"project_id": "trackly",
"update_available": true,
"current_version": "1.0.0",
"latest_version": "1.2.5",
"breaking_changes": true,
"download_url": "https://cdn.lunarbit.dev/trackly/1.2.5/trackly-1.2.5-win-x64.exe"
},
{
"project_id": "csviewer",
"update_available": false,
"current_version": "2.3.1",
"latest_version": "2.3.1"
}
]
}
Usage Examplesβ
cURLβ
The API is designed to work seamlessly with cURL and any HTTP client. Below are common usage patterns:
# Check API health
curl https://api.lunarbit.dev/health
# List projects (requires authentication)
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.lunarbit.dev/projects
# Check for updates
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.lunarbit.dev/projects/trackly/channels/stable/update?current_version=1.2.3&platform=windows&architecture=x64"
# Chat with AI
curl -X POST https://api.lunarbit.dev/ai/chat \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "Explain semantic versioning"}],
"temperature": 0.7,
"max_tokens": 500
}'
# Create API key (admin only)
curl -X POST https://api.lunarbit.dev/admin/keys \
-H "Authorization: Bearer ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "My App Key",
"permissions": {
"canReadProjects": true,
"canUseAI": true
},
"expiresIn": "90d"
}'
Official TypeScript/JavaScript and Python client libraries are planned for future releases. For now, use standard HTTP clients or cURL to interact with the API.
Best Practicesβ
API Key Securityβ
- Store API keys securely in environment variables
- Never commit API keys to version control
- Rotate keys regularly for production applications
- Use separate keys for development and production
Request Optimizationβ
- Cache responses when appropriate (versions don't change frequently)
- Respect rate limits with exponential backoff
- Use conditional requests with ETag headers
- Batch requests when possible
Error Handlingβ
Always handle errors gracefully. Example with bash/curl:
# Function to handle rate limiting with exponential backoff
call_api_with_retry() {
local url="$1"
local max_retries=3
local retry_count=0
local wait_time=1
while [ $retry_count -lt $max_retries ]; do
response=$(curl -s -w "\n%{http_code}" -H "Authorization: Bearer $API_KEY" "$url")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | head -n-1)
if [ "$http_code" -eq 429 ]; then
echo "Rate limited. Waiting ${wait_time}s before retry..."
sleep $wait_time
wait_time=$((wait_time * 2))
retry_count=$((retry_count + 1))
elif [ "$http_code" -eq 401 ]; then
echo "Error: Invalid API key"
exit 1
elif [ "$http_code" -eq 200 ]; then
echo "$body"
return 0
else
echo "Error: HTTP $http_code"
echo "$body"
exit 1
fi
done
echo "Max retries exceeded"
exit 1
}
# Usage
call_api_with_retry "https://api.lunarbit.dev/projects"
Response Formatβ
All successful responses return JSON with appropriate HTTP status codes:
200 OK- Successful GET request201 Created- Successful POST request204 No Content- Successful DELETE request400 Bad Request- Invalid request parameters401 Unauthorized- Missing or invalid API key403 Forbidden- Insufficient permissions404 Not Found- Resource doesn't exist429 Too Many Requests- Rate limit exceeded500 Internal Server Error- Server error
Securityβ
Security Featuresβ
The API implements comprehensive security measures:
- β API Key Authentication - Granular permission-based access control
- β Rate Limiting - IP and key-based limits to prevent abuse
- β CORS Protection - Configurable origin restrictions
- β Security Headers - OWASP-recommended headers automatically applied
- β Input Sanitization - Request validation and sanitization
- β Request ID Tracking - Full request/response audit trail
- π API Key Encryption - Enhanced key storage (planned)
- π Audit Logging - Comprehensive usage logging (planned)
Security Headersβ
All responses include these security headers:
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000; includeSubDomains
Content-Security-Policy: default-src 'self'
Security Best Practicesβ
- Never commit API keys - Always use environment variables
- Rotate keys regularly - Set expiration dates on production keys
- Use HTTPS in production - Enable SSL/TLS certificates
- Monitor usage - Check
/admin/keys/statsregularly - Revoke compromised keys - Immediate revocation available
- Limit permissions - Grant minimum required access per key
- Enable audit logging - Track all API usage for security review
- Rate limit appropriately - Configure limits based on usage patterns
Deploymentβ
Environment Variablesβ
Required:
NODE_ENV=production
PORT=3000
API_KEY_ADMIN=your_admin_key_here
Optional:
# GitHub Integration
GITHUB_TOKEN=ghp_your_token
# AI Providers
LMSTUDIO_ENABLED=true
LMSTUDIO_BASE_URL=http://localhost:1234
OPENAI_API_KEY=sk-...
OPENAI_ENABLED=true
# Caching
CACHE_TTL=300000
# Logging
LOG_LEVEL=info
LOG_FORMAT=json
Deployment Optionsβ
Option 1: Traditional Server (Debian/Ubuntu)β
The API includes an automated deployment script for Debian/Ubuntu systems:
# Transfer files to server
rsync -avz --exclude 'node_modules' ./api/ user@server:/home/user/api/
# Run deployment script
ssh user@server
cd ~/api
chmod +x deploy-debian.sh
./deploy-debian.sh
The script automatically:
- Installs Node.js 20.x
- Installs dependencies
- Builds TypeScript
- Configures systemd service
- Starts the API
Option 2: Cloudflare Workersβ
# Set secrets
wrangler secret put GITHUB_TOKEN
wrangler secret put API_KEY_READ
wrangler secret put API_KEY_ADMIN
# Deploy
npm run deploy
Option 3: Dockerβ
# Build image
docker build -t lunarbit-api .
# Run container
docker run -d \
-p 3000:3000 \
-e API_KEY_ADMIN=your_admin_key \
--name lunarbit-api \
lunarbit-api
Service Management (systemd)β
# Start service
sudo systemctl start lunarbit-api
# Stop service
sudo systemctl stop lunarbit-api
# Restart service
sudo systemctl restart lunarbit-api
# View logs
sudo journalctl -u lunarbit-api -f
# Check status
sudo systemctl status lunarbit-api
Changelogβ
Version 2.0.0 (Current - February 2026)β
Major Features:
- β LunarCore Compliance - Full implementation of LunarCore Specification v1.0.0
- β Clean Architecture - Comprehensive restructuring with layer separation
- β AI Gateway & Proxy - Multi-provider support (LM Studio, OpenAI, Anthropic)
- β Advanced Model Router - 4 routing strategies with automatic failover
- β Granular API Key Management - Permission-based access control with usage tracking
- β Structured Logging - JSON output with sensitive data redaction
- β Enhanced Error Handling - 15+ custom error classes with detailed context
- β Launcher Update System - Advanced multi-project update checking
- β Security Enhancements - OWASP-compliant headers, rate limiting, CORS
- β Build Verification - Automatic health checks and checksum validation
- β GitHub Integration - Automatic synchronization with GitHub releases
AI Capabilities:
- Chat completion with streaming support
- Changelog analysis and summarization
- Multiple provider support with intelligent routing
- Token tracking and optimization
Breaking Changes from v1:
- Authentication header format changed (
Bearerinstead ofApiKey) - Base URL includes
/api/v2path - Error response format restructured with detailed codes
- API keys from v1 are not compatible with v2
Version 1.0.0 (June 2025)β
- Initial public release
- Basic version management and update checking
- GitHub integration for project data
- Simple API key authentication
Migration from v1.0.0β
If you're using API v1, migrate to v2 with these changes:
Base URL
- https://api.lunarbit.dev/api/v1
+ https://api.lunarbit.dev/api/v2
Authentication Header
- Authorization: ApiKey your_key
+ Authorization: Bearer your_key
Error Response Format
v2 provides more detailed error information:
// v2 error format
{
"error": {
"code": "PROJECT_NOT_FOUND",
"message": "Project 'xyz' not found",
"documentation_url": "https://docs.lunarbit.dev/api-errors#PROJECT_NOT_FOUND"
}
}
Note: v1 API keys are not compatible with v2. Request new API keys for v2 access.
Developmentβ
Project Structureβ
api/
βββ src/
β βββ api/v2/ # API routes and controllers
β βββ core/ # Business logic
β β βββ providers/ai/ # β
AI provider implementations
β β βββ services/ # Business services
β β βββ repositories/ # Data access
β βββ infrastructure/ # Infrastructure concerns
β β βββ logging/ # β
Structured logging
β βββ shared/ # Shared utilities
β β βββ errors/ # β
Custom error classes
β β βββ constants/ # β
Application constants
β βββ keymanager.ts # API key management
β βββ lmstudio.ts # LM Studio integration
β βββ security.ts # Security middleware
β βββ types.ts # TypeScript types
β βββ utils.ts # Utility functions
βββ data/
β βββ api-keys.json # API key storage
βββ server.ts # Main server file
βββ openapi.yaml # OpenAPI specification
βββ README.md # Documentation
Available Scriptsβ
# Development
npm run dev # Start with hot reload
npm run dev:watch # Start with file watching
# Production
npm run build # Compile TypeScript
npm start # Start production server
# Deployment
npm run deploy # Deploy to Cloudflare Workers
# Code Quality
npm run lint # Run ESLint
npm run format # Format code with Prettier
npm test # Run tests
Adding a Custom AI Providerβ
The API supports custom AI providers through a standardized interface:
// Implement the AIProvider interface
import { AIProvider, CompletionRequest, CompletionResponse } from './src/core/providers/ai/BaseProvider';
export class CustomProvider implements AIProvider {
async chatCompletion(request: CompletionRequest): Promise<CompletionResponse> {
// Your implementation
}
async *streamCompletion(request: CompletionRequest): AsyncIterable<string> {
// Streaming implementation
}
async isHealthy(): Promise<boolean> {
// Health check
}
async getModels(): Promise<string[]> {
// List available models
}
}
// Register with ModelRouter
const customProvider = new CustomProvider(config);
modelRouter.registerProvider('custom', customProvider);
Implementation Statusβ
β Completed (Phase 1):
- Architecture audit and clean architecture setup
- AI provider system with routing strategies
- Error handling system (15+ custom errors)
- Structured logging infrastructure
- Application constants (100+ centralized)
π§ In Progress (Phase 2):
- Service layer implementation
- Repository layer abstraction
- Controller refactoring
- Enhanced input validation
π Planned (Phase 3):
- Multi-tenancy support
- Enhanced security features
- Metrics collection
- Database integration
- Caching layer
- CI/CD pipelines
Support and Resourcesβ
Documentationβ
- API Documentation: docs.lunarbit.dev
- OpenAPI Specification: Available at
openapi.yamlin the API repository - Interactive API Docs: Available at
/docsendpoint (when deployed) - GitHub Repository: github.com/LunarBit-dev/api
Get Helpβ
Need assistance with the API? Multiple support channels available:
- Email Support: api@lunarbit.dev
- Discord Community: discord.gg/lunarbit
- GitHub Issues: Report bugs or request features
- GitHub Discussions: Community Q&A
- Status Page: status.lunarbit.dev - Monitor API availability
Additional Resourcesβ
- LunarCore Specification: github.com/LunarBit-dev/LunarCore-spec
- Example Scripts: cURL examples and integration patterns in the API repository
- Client Libraries: TypeScript and Python SDKs planned for future release
Terms and Policiesβ
- API usage is subject to our Terms of Service
- Review our Privacy Policy for data handling
- Rate limits may be adjusted to ensure service quality
- API availability target: 99.9% uptime
Licenseβ
The LunarBit API is proprietary software.
Questions? Contact us at api@lunarbit.dev or join our Discord community.