Skip to main content

Error Response Format

All error responses from the Babou API follow a consistent JSON structure:
{
  "error": "Human-readable error message",
  "code": "ERROR_CODE",
  "hint": "Optional guidance on how to fix the error"
}
error
string
A human-readable description of what went wrong
code
string
A machine-readable error code for programmatic handling
hint
string
Optional additional guidance on resolving the error

HTTP Status Codes

The Babou API uses standard HTTP status codes:
Status CodeMeaning
200Success - Request completed successfully
400Bad Request - Invalid parameters or request format
401Unauthorized - Invalid or missing API key
404Not Found - Resource doesn’t exist or you don’t have access
409Conflict - Resource state conflict (e.g., already processing)
413Payload Too Large - File exceeds size limits
429Too Many Requests - Rate limit exceeded
500Internal Server Error - Something went wrong on our end

Common Error Codes

Authentication Errors

HTTP Status: 401Cause: Invalid or missing API keyExample:
{
  "error": "Unauthorized - Invalid API key",
  "code": "UNAUTHORIZED"
}
Solution:
  • Verify your API key is correct
  • Ensure you’re including the Authorization header
  • Check that your API key hasn’t expired
  • Get a new API key from the dashboard
HTTP Status: 401Cause: API key doesn’t match the expected format (sk-bab-*)Example:
{
  "error": "Invalid API key format",
  "code": "INVALID_API_KEY_FORMAT"
}
Solution:
  • Ensure your API key starts with sk-bab-
  • Check for typos or truncation
  • Don’t add extra characters or whitespace
HTTP Status: 401Cause: The API key has passed its expiration dateExample:
{
  "error": "API key has expired",
  "code": "API_KEY_EXPIRED"
}
Solution:
  • Generate a new API key from your dashboard
  • Update your application with the new key
  • Set up key rotation to prevent future expirations

Validation Errors

HTTP Status: 400Cause: Request parameters don’t meet validation requirementsExample:
{
  "error": "Validation failed",
  "code": "VALIDATION_ERROR",
  "hint": "Name must be between 1 and 30 characters"
}
Common Validation Rules:
  • Project name: 1-30 characters
  • Project description: max 1000 characters
  • Chapter name: 1-30 characters
  • Chapter duration: positive integer
  • Prompt content: 1-5000 characters
Solution:
  • Check the hint field for specific guidance
  • Review the API documentation for parameter requirements
  • Validate input on the client side before sending

Resource Errors

HTTP Status: 404Cause: The requested resource doesn’t exist or you don’t have accessExample:
{
  "error": "Project not found",
  "code": "NOT_FOUND"
}
Solution:
  • Verify the ID is correct
  • Check that the resource belongs to your account
  • Ensure the resource hasn’t been deleted
  • Use List endpoints to find valid IDs
HTTP Status: 409Cause: Resource state conflict - operation can’t proceed due to current stateCommon Scenarios:
  • Another prompt is already being processed for a chapter
  • Export is already in progress for a project
Example:
{
  "error": "A prompt is already being processed for this chapter",
  "code": "CONFLICT",
  "hint": "Wait for the current prompt to complete or set force: true to override"
}
Solution:
  • Wait for the current operation to complete
  • Check operation status before retrying
  • Use force: true parameter if applicable (use cautiously)

File Upload Errors

HTTP Status: 413Cause: Uploaded file exceeds the 100MB size limitExample:
{
  "error": "File size exceeds maximum allowed size of 100MB",
  "code": "FILE_TOO_LARGE"
}
Solution:
  • Compress the file before uploading
  • Split large videos into smaller segments
  • Check file size before upload:
    const stats = fs.statSync(filePath);
    if (stats.size > 100 * 1024 * 1024) {
      throw new Error('File too large');
    }
    
HTTP Status: 500Cause: Failed to upload file to cloud storageExample:
{
  "error": "Failed to upload file to storage",
  "code": "UPLOAD_FAILED"
}
Solution:
  • Retry the upload
  • Check your network connection
  • Verify the file isn’t corrupted
  • Contact support if the issue persists

Rate Limiting

HTTP Status: 429Cause: Too many requests in a short time periodExample:
{
  "error": "Rate limit exceeded",
  "code": "RATE_LIMIT_EXCEEDED",
  "hint": "Retry after 60 seconds"
}
Solution:
  • Implement exponential backoff
  • Space out your requests
  • Cache responses when possible
  • Contact support for higher rate limits
Retry Strategy:
async function fetchWithRetry(url: string, options: RequestInit, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    const response = await fetch(url, options);

    if (response.status !== 429) {
      return response;
    }

    // Exponential backoff
    const delay = Math.pow(2, i) * 1000;
    await new Promise(r => setTimeout(r, delay));
  }

  throw new Error('Max retries exceeded');
}

Server Errors

HTTP Status: 500Cause: An unexpected error occurred on the serverExample:
{
  "error": "An internal error occurred",
  "code": "INTERNAL_ERROR"
}
Solution:
  • Retry the request after a short delay
  • Check the status page for known issues
  • Contact support if the problem persists
  • Include the request ID if available for faster debugging

Error Handling Best Practices

1. Always Check Response Status

async function makeApiCall(url: string, options: RequestInit) {
  const response = await fetch(url, options);

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`API Error (${response.status}): ${error.error} [${error.code}]`);
  }

  return await response.json();
}

2. Implement Retry Logic

async function retryWithBackoff<T>(
  fn: () => Promise<T>,
  maxRetries = 3,
  baseDelay = 1000
): Promise<T> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error: any) {
      const isLastAttempt = attempt === maxRetries - 1;

      // Don't retry on client errors (4xx except 429)
      if (error.message.includes('(4') && !error.message.includes('(429')) {
        throw error;
      }

      if (isLastAttempt) {
        throw error;
      }

      const delay = baseDelay * Math.pow(2, attempt);
      console.log(`Retry ${attempt + 1}/${maxRetries} after ${delay}ms...`);
      await new Promise(r => setTimeout(r, delay));
    }
  }

  throw new Error('Max retries exceeded');
}

3. Handle Specific Error Codes

async function submitPromptSafe(projectId: string, chapterId: string, content: string) {
  try {
    return await submitPrompt(projectId, chapterId, content);
  } catch (error: any) {
    if (error.message.includes('[CONFLICT]')) {
      // Wait and retry for conflicts
      console.log('Waiting for current operation to complete...');
      await new Promise(r => setTimeout(r, 10000));
      return await submitPrompt(projectId, chapterId, content);
    }

    if (error.message.includes('[UNAUTHORIZED]')) {
      // Don't retry auth errors
      throw new Error('Invalid API key - please check your credentials');
    }

    if (error.message.includes('[VALIDATION_ERROR]')) {
      // Don't retry validation errors
      throw new Error(`Invalid input: ${error.message}`);
    }

    // Retry other errors
    return await retryWithBackoff(() => submitPrompt(projectId, chapterId, content));
  }
}

4. Log Errors for Debugging

import logging

logger = logging.getLogger(__name__)

def api_call_with_logging(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            logger.error(f'API call failed: {func.__name__}', exc_info=True)
            logger.error(f'Args: {args}, Kwargs: {kwargs}')
            raise
    return wrapper

@api_call_with_logging
def create_project(name, description=None):
    # ... API call logic
    pass

Need Help?

If you’re experiencing errors that aren’t covered here: