Skip to main content
The Claro API uses standard HTTP status codes and returns detailed error information in JSON format to help you diagnose and handle errors effectively.

Error Response Format

All error responses follow a consistent structure:
{
  "error": {
    "code": "error_code",
    "message": "Human-readable error message",
    "details": {
      // Optional additional context
    }
  }
}

HTTP Status Codes

The API uses standard HTTP status codes to indicate success or failure:
Status CodeMeaningCommon Causes
200OKRequest succeeded
400Bad RequestInvalid request parameters
401UnauthorizedMissing or invalid API key
403ForbiddenInsufficient permissions
404Not FoundResource doesn’t exist
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer-side error
503Service UnavailableTemporary service disruption

Common Error Codes

Authentication Errors

401 Unauthorized

Error Code: unauthorized The API key is missing or invalid.
{
  "error": {
    "code": "unauthorized",
    "message": "Invalid API key"
  }
}
Solutions:
  • Verify your API key is correct
  • Check that you’re using the Bearer prefix in the Authorization header
  • Ensure the key hasn’t been deleted from your account
  • Get a new API key from claro.baytos.ai

403 Forbidden

Error Code: forbidden Your API key is valid but lacks permission to access the resource.
{
  "error": {
    "code": "forbidden",
    "message": "You don't have access to this workspace"
  }
}
Solutions:
  • Verify you’re a member of the workspace
  • Check that the prompt exists and is accessible to you
  • Ensure your workspace subscription is active

Resource Errors

404 Not Found

Error Code: not_found The requested resource doesn’t exist.
{
  "error": {
    "code": "not_found",
    "message": "Prompt not found: @workspace/nonexistent:v1"
  }
}
Solutions:
  • Verify the package name is spelled correctly
  • Check that the version exists (e.g., :v1, :v2)
  • Ensure you have access to the workspace

Validation Errors

400 Bad Request

Error Code: validation_error The request contains invalid parameters.
{
  "error": {
    "code": "validation_error",
    "message": "Invalid package name format",
    "details": {
      "field": "prompt_id",
      "expected": "@namespace/prompt-name:version"
    }
  }
}
Solutions:
  • Check the request parameters match the expected format
  • Review the API documentation for the endpoint
  • Ensure all required fields are provided

Rate Limiting Errors

429 Too Many Requests

Error Code: rate_limit_exceeded You’ve exceeded the rate limit.
{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Please retry after 60 seconds.",
    "retry_after": 60
  }
}
Solutions:
  • Wait for the duration specified in retry_after
  • Implement exponential backoff retry logic
  • Reduce request frequency
  • Contact support for higher rate limits
See Rate Limits for detailed guidance.

Server Errors

500 Internal Server Error

Error Code: internal_error An unexpected error occurred on the server.
{
  "error": {
    "code": "internal_error",
    "message": "An unexpected error occurred. Please try again later."
  }
}
Solutions:
  • Retry the request after a short delay
  • Check status.baytos.ai for service status
  • Contact support if the issue persists

503 Service Unavailable

Error Code: service_unavailable The service is temporarily unavailable.
{
  "error": {
    "code": "service_unavailable",
    "message": "Service temporarily unavailable. Please try again later."
  }
}
Solutions:
  • Wait a few moments and retry
  • Implement exponential backoff
  • Check service status page

Error Handling Examples

Python SDK

The SDK provides specific exception types for different errors:
from baytos.claro import (
    BaytClient,
    BaytAuthError,
    BaytNotFoundError,
    BaytRateLimitError,
    BaytAPIError
)

client = BaytClient(api_key="your_api_key")

try:
    prompt = client.get_prompt("@workspace/my-prompt:v1")
    print(f"Successfully loaded: {prompt.title}")

except BaytNotFoundError as e:
    print(f"Prompt not found: {e}")
    # Handle missing prompt - maybe use a fallback

except BaytAuthError as e:
    print(f"Authentication failed: {e}")
    # Check API key configuration

except BaytRateLimitError as e:
    print(f"Rate limit exceeded: {e}")
    # Wait and retry, or queue for later

except BaytAPIError as e:
    print(f"API error occurred: {e}")
    # Log error and notify administrators

except Exception as e:
    print(f"Unexpected error: {e}")
    # Handle any other errors

Python with requests

import requests
import time

def get_prompt(package_name, api_key, max_retries=3):
    url = f"https://api.baytos.ai/v1/prompts/{package_name}"
    headers = {"Authorization": f"Bearer {api_key}"}

    for attempt in range(max_retries):
        try:
            response = requests.get(url, headers=headers)

            if response.status_code == 200:
                return response.json()

            elif response.status_code == 401:
                raise Exception("Invalid API key")

            elif response.status_code == 403:
                raise Exception("Access denied")

            elif response.status_code == 404:
                raise Exception(f"Prompt not found: {package_name}")

            elif response.status_code == 429:
                if attempt < max_retries - 1:
                    retry_after = int(response.headers.get('Retry-After', 60))
                    time.sleep(retry_after)
                    continue
                else:
                    raise Exception("Rate limit exceeded")

            elif response.status_code >= 500:
                if attempt < max_retries - 1:
                    time.sleep(2 ** attempt)  # Exponential backoff
                    continue
                else:
                    raise Exception("Server error")

            else:
                response.raise_for_status()

        except requests.exceptions.RequestException as e:
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)
                continue
            raise

    raise Exception("Max retries exceeded")

JavaScript with fetch

async function getPrompt(packageName, apiKey, maxRetries = 3) {
  const url = `https://api.baytos.ai/v1/prompts/${packageName}`;
  const headers = {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  };

  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, { headers });

      if (response.ok) {
        return await response.json();
      }

      const error = await response.json();

      switch (response.status) {
        case 401:
          throw new Error(`Authentication failed: ${error.error.message}`);

        case 403:
          throw new Error(`Access denied: ${error.error.message}`);

        case 404:
          throw new Error(`Prompt not found: ${packageName}`);

        case 429:
          if (attempt < maxRetries - 1) {
            const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
            console.log(`Rate limited. Retrying after ${retryAfter}s...`);
            await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
            continue;
          }
          throw new Error('Rate limit exceeded');

        case 500:
        case 503:
          if (attempt < maxRetries - 1) {
            const delay = Math.pow(2, attempt) * 1000;
            await new Promise(resolve => setTimeout(resolve, delay));
            continue;
          }
          throw new Error(`Server error: ${error.error.message}`);

        default:
          throw new Error(`HTTP ${response.status}: ${error.error.message}`);
      }
    } catch (err) {
      if (attempt === maxRetries - 1) throw err;
    }
  }

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

// Usage
try {
  const prompt = await getPrompt('@workspace/my-prompt:v1', apiKey);
  console.log(prompt);
} catch (error) {
  console.error('Failed to fetch prompt:', error.message);
}

Troubleshooting Guide

Symptoms: 401 Unauthorized responsesChecklist:
  • API key is correctly copied (no extra spaces)
  • Environment variable is set correctly
  • Using Bearer prefix in Authorization header
  • API key hasn’t been deleted
  • Testing with the correct API endpoint
Solution: Create a new API key and update your configuration.
Symptoms: 404 Not Found responsesChecklist:
  • Package name format is correct: @namespace/prompt-name:version
  • The prompt exists in your workspace
  • You have access to the workspace
  • The version number is correct (e.g., :v1 not :1)
Solution: Verify the package name in the Claro dashboard.
Symptoms: Requests sometimes fail with 500 or timeout errorsChecklist:
  • Implement retry logic with exponential backoff
  • Add timeout to requests (30s recommended)
  • Check network connectivity
  • Monitor API status page
Solution: Implement robust retry logic and error handling.
Symptoms: 429 Too Many Requests responsesChecklist:
  • Implement exponential backoff
  • Respect Retry-After header
  • Cache responses when possible
  • Batch requests efficiently
Solution: See Rate Limits guide.

Error Logging Best Practices

Log errors with sufficient context for debugging:
import logging

logger = logging.getLogger(__name__)

try:
    prompt = client.get_prompt(package_name)
except BaytAPIError as e:
    logger.error(
        "Failed to fetch prompt",
        extra={
            "package_name": package_name,
            "error_code": e.code,
            "error_message": str(e),
            "user_id": user_id,
            "request_id": request_id
        }
    )
    raise

Next Steps