API Reference v2.0

Complete REST API documentation for ChaozCode. All endpoints use JSON for request and response bodies. Authentication is required for all endpoints except health checks.

Base URL: https://api.chaozcode.com/v2

📑 Quick Navigation

Authentication

All API requests require authentication using a Bearer token. Include your API key in the Authorization header:

Authorization: Bearer YOUR_API_KEY

Getting Your API Key

  1. Log in to your dashboard at chaozcode.com/app/dashboard
  2. Navigate to Settings → API Keys
  3. Click "Generate New Key"
  4. Copy and securely store your key

API Key Types

TypeScopeUse Case
developmentFull access, rate limitedLocal development & testing
productionFull access, higher limitsProduction applications
readonlyGET requests onlyAnalytics, reporting
restrictedSpecific endpoints onlyThird-party integrations

Example Request

curl -X GET "https://api.chaozcode.com/v2/user/me" \
  -H "Authorization: Bearer cc_live_abc123..." \
  -H "Content-Type: application/json"

Rate Limits

API requests are rate limited based on your plan. Limits are applied per API key.

PlanRequests/MinRequests/DayBurst Limit
Free1010020
Pro6010,000100
Team300100,000500
Enterprise1,000+UnlimitedCustom

Rate Limit Headers

Every response includes rate limit information:

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1706652000
X-RateLimit-RetryAfter: 30

Handling Rate Limits

When rate limited, you'll receive a 429 Too Many Requests response. Implement exponential backoff:

async function apiCallWithRetry(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.status === 429) {
        const delay = Math.pow(2, i) * 1000;
        await new Promise(r => setTimeout(r, delay));
      } else throw error;
    }
  }
}

Error Handling

All errors return a consistent JSON structure:

{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "The request body is missing required field 'prompt'",
    "details": {
      "field": "prompt",
      "reason": "required"
    },
    "requestId": "req_abc123"
  }
}

Error Codes

HTTPCodeDescription
400INVALID_REQUESTMalformed request or missing parameters
401UNAUTHORIZEDInvalid or missing API key
403FORBIDDENAPI key lacks required permissions
404NOT_FOUNDResource doesn't exist
409CONFLICTResource already exists
422VALIDATION_ERRORRequest validation failed
429RATE_LIMITEDToo many requests
500INTERNAL_ERRORServer error (retry safe)
503SERVICE_UNAVAILABLETemporary outage

AI Query Endpoints

Core endpoints for AI-powered queries and completions.

POST /query

Send a prompt to the AI and receive a completion. Supports multiple models and customization options.

ParameterTypeRequiredDescription
promptstringYesThe input prompt (max 100,000 chars)
modelstringNoModel ID: gpt-4, claude-3-sonnet, gemini-pro
systemPromptstringNoSystem instructions for the AI
temperaturenumberNoCreativity (0.0-2.0, default: 0.7)
maxTokensintegerNoMaximum response tokens (default: 4096)
topPnumberNoNucleus sampling (0.0-1.0)
stoparrayNoStop sequences
streambooleanNoEnable streaming response
contextobjectNoAdditional context from Memory Spine
Request Example
curl -X POST "https://api.chaozcode.com/v2/query" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Explain the difference between REST and GraphQL",
    "model": "gpt-4",
    "temperature": 0.7,
    "maxTokens": 1000
  }'
200 Success Response
{
  "id": "query_abc123",
  "text": "REST and GraphQL are both API architectures...",
  "model": "gpt-4",
  "usage": {
    "promptTokens": 15,
    "completionTokens": 487,
    "totalTokens": 502
  },
  "finishReason": "stop",
  "createdAt": "2026-01-30T12:00:00Z"
}
POST /query/stream

Stream AI responses using Server-Sent Events (SSE). Same parameters as /query.

Stream Response Format
data: {"type":"start","id":"query_abc123"}

data: {"type":"delta","content":"REST "}

data: {"type":"delta","content":"and "}

data: {"type":"delta","content":"GraphQL..."}

data: {"type":"done","usage":{"totalTokens":502}}
POST /query/chat

Multi-turn chat completion with message history.

ParameterTypeRequiredDescription
messagesarrayYesArray of message objects with role and content
modelstringNoModel ID (default: gpt-4)
conversationIdstringNoResume existing conversation
Request Example
{
  "messages": [
    {"role": "system", "content": "You are a helpful coding assistant."},
    {"role": "user", "content": "How do I create a React hook?"},
    {"role": "assistant", "content": "Here's how to create a custom React hook..."},
    {"role": "user", "content": "Can you show an example with useState?"}
  ],
  "model": "gpt-4"
}
GET /models

List all available AI models with their capabilities and pricing.

200 Response
{
  "models": [
    {
      "id": "gpt-4",
      "name": "GPT-4",
      "provider": "openai",
      "contextWindow": 128000,
      "inputPrice": 0.03,
      "outputPrice": 0.06,
      "capabilities": ["chat", "code", "analysis"]
    },
    {
      "id": "claude-3-sonnet",
      "name": "Claude 3 Sonnet",
      "provider": "anthropic",
      "contextWindow": 200000,
      "inputPrice": 0.003,
      "outputPrice": 0.015,
      "capabilities": ["chat", "code", "vision"]
    }
  ]
}

Memory Endpoints

Memory Spine API for persistent context and knowledge management. See Memory Spine API for the complete 62-tool MCP reference.

POST /memory/store

Store a new memory with content, tags, and metadata.

ParameterTypeRequiredDescription
idstringYesUnique memory identifier
contentstringYesMemory content (text, JSON, markdown)
tagsarrayNoCategorization tags
importancestringNolow, medium, high, critical
metadataobjectNoAdditional key-value pairs
201 Success
{
  "ok": true,
  "id": "project-auth-v2",
  "vectorId": "vec_abc123",
  "createdAt": "2026-01-30T12:00:00Z"
}
POST /memory/search

Semantic search for relevant memories.

ParameterTypeRequiredDescription
querystringYesNatural language search query
limitintegerNoMax results (default: 10, max: 100)
tagsarrayNoFilter by tags
minScorenumberNoMinimum similarity (0.0-1.0)
200 Success
{
  "results": [
    {
      "id": "auth-implementation",
      "content": "Implemented OAuth2 with PKCE...",
      "score": 0.92,
      "tags": ["auth", "security"],
      "createdAt": "2026-01-29T10:00:00Z"
    }
  ],
  "total": 1,
  "took": 23
}
GET /memory/{id}

Retrieve a specific memory by ID.

PUT /memory/{id}

Update an existing memory. Creates a new version.

DELETE /memory/{id}

Soft delete a memory. Recoverable within 30 days.

GET /memory/stats

Get Memory Spine statistics.

200 Response
{
  "vectorCount": 5234,
  "storageBytes": 52428800,
  "version": "0.4.0",
  "avgResponseMs": 8,
  "status": "healthy"
}
POST /memory/context

Build an optimized context window for LLM queries.

ParameterTypeRequiredDescription
querystringYesTask or question
maxTokensintegerNoMax context size (default: 4000)

Codebase Endpoints

Code analysis and generation endpoints.

POST /codebase/analyze

Analyze codebase structure, dependencies, and patterns.

ParameterTypeRequiredDescription
filesarrayYesArray of {path, content} objects
languagestringNoPrimary language (auto-detected)
depthstringNobasic, standard, deep (default: standard)
200 Success
{
  "summary": {
    "totalFiles": 45,
    "totalLines": 8234,
    "languages": {"typescript": 80, "css": 15, "json": 5}
  },
  "structure": {
    "components": 12,
    "hooks": 5,
    "utils": 8,
    "tests": 20
  },
  "dependencies": [...],
  "suggestions": [...]
}
POST /codebase/generate

Generate code based on context and task description.

ParameterTypeRequiredDescription
taskstringYesWhat to generate
contextarrayNoRelevant code files for context
languagestringNoTarget language
styleobjectNoCode style preferences
POST /codebase/review

AI code review with suggestions and issue detection.

ParameterTypeRequiredDescription
codestringYesCode to review
languagestringNoProgramming language
focusarrayNoFocus areas: security, performance, style, bugs
POST /codebase/fix

Get AI-powered fix suggestions for code issues.

ParameterTypeRequiredDescription
codestringYesCode with issues
errorstringNoError message or description
contextstringNoAdditional context

Agent Endpoints

AI agent orchestration and task management.

POST /agents/spawn

Spawn a specialized AI agent for a task.

ParameterTypeRequiredDescription
typestringYesAgent type: explore, task, code-review, general-purpose
promptstringYesTask description
modelstringNoOverride default model
timeoutintegerNoTimeout in seconds (default: 300)
202 Accepted
{
  "agentId": "agent_abc123",
  "type": "explore",
  "status": "running",
  "createdAt": "2026-01-30T12:00:00Z"
}
GET /agents/{agentId}

Get agent status and results.

200 Response
{
  "agentId": "agent_abc123",
  "type": "explore",
  "status": "completed",
  "result": {
    "summary": "Found 5 authentication-related files...",
    "files": [...],
    "confidence": 0.92
  },
  "usage": {"tokens": 1523, "cost": 0.045},
  "duration": 3.2
}
GET /agents/types

List available agent types and their capabilities.

DELETE /agents/{agentId}

Cancel a running agent.

Project Endpoints

Manage projects and their configurations.

GET /projects

List all projects for the authenticated user.

POST /projects

Create a new project.

ParameterTypeRequiredDescription
namestringYesProject name
descriptionstringNoProject description
settingsobjectNoProject configuration
GET /projects/{projectId}

Get project details.

PATCH /projects/{projectId}

Update project settings.

DELETE /projects/{projectId}

Delete a project and all associated data.

User Endpoints

User account and settings management.

GET /user/me

Get current user profile.

200 Response
{
  "id": "user_abc123",
  "email": "developer@example.com",
  "name": "Jane Developer",
  "plan": "pro",
  "usage": {
    "apiCalls": 4523,
    "limit": 10000,
    "resetAt": "2026-02-01T00:00:00Z"
  },
  "createdAt": "2025-06-15T10:00:00Z"
}
PATCH /user/me

Update user profile.

GET /user/usage

Get detailed usage statistics.

GET /user/api-keys

List all API keys (masked).

POST /user/api-keys

Generate a new API key.

DELETE /user/api-keys/{keyId}

Revoke an API key.

Webhook Endpoints

Configure webhooks to receive real-time event notifications.

GET /webhooks

List configured webhooks.

POST /webhooks

Create a new webhook.

ParameterTypeRequiredDescription
urlstringYesWebhook endpoint URL (HTTPS)
eventsarrayYesEvents to subscribe to
secretstringNoSigning secret (auto-generated if omitted)

Available Events

  • memory.stored - New memory created
  • memory.updated - Memory modified
  • memory.deleted - Memory removed
  • agent.started - Agent began processing
  • agent.completed - Agent finished
  • agent.failed - Agent encountered error
  • project.updated - Project settings changed
  • usage.threshold - Usage threshold reached
DELETE /webhooks/{webhookId}

Delete a webhook.

POST /webhooks/{webhookId}/test

Send a test event to verify webhook configuration.

Webhook Payload Format

{
  "id": "evt_abc123",
  "type": "memory.stored",
  "createdAt": "2026-01-30T12:00:00Z",
  "data": {
    "memoryId": "project-update",
    "tags": ["project", "update"],
    "importance": "high"
  }
}

Verifying Webhook Signatures

All webhooks include a signature header for verification:

X-ChaozCode-Signature: sha256=abc123...

// Verify in Node.js
const crypto = require('crypto');
const signature = crypto
  .createHmac('sha256', webhookSecret)
  .update(rawBody)
  .digest('hex');

if (signature === receivedSignature) {
  // Valid webhook
}