Skip to main content
Our APIs use conventional HTTP response codes to indicate the success or failure of API requests. Error responses include detailed information to help you diagnose and resolve issues.

Error Response Format

All API errors follow a consistent JSON format:
{
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "details": {
      "field": "additional_context",
      "retry_after": 60
    }
  }
}
error.code
string
Machine-readable error code for programmatic handling
error.message
string
Human-readable description of the error
error.details
object
Additional context and metadata about the error (optional)

HTTP Status Codes

200
OK
Request succeeded
201
Created
Resource successfully created
204
No Content
Request succeeded, no content to return
400
Bad Request
Invalid request parameters or malformed request
401
Unauthorized
Missing or invalid API key
403
Forbidden
Valid credentials but insufficient permissions
404
Not Found
Requested resource does not exist
409
Conflict
Request conflicts with current state
413
Payload Too Large
Request body or file exceeds size limits
422
Unprocessable Entity
Valid request format but unable to process
429
Too Many Requests
Rate limit exceeded
500
Internal Server Error
Unexpected server error
502
Bad Gateway
Gateway or proxy error
503
Service Unavailable
Service temporarily unavailable
504
Gateway Timeout
Gateway timeout

Common Error Codes

Authentication Errors

HTTP Status: 401
Cause: Missing or invalid API key
Solutions:
  • Verify your API key is correct and hasn’t been revoked
  • Check that the Authorization header is properly formatted: Bearer YOUR_API_KEY
  • Ensure you’re using the correct environment (dev/staging/prod)
# Correct format
headers = {"Authorization": "Bearer YOUR_API_KEY"}

# Common mistakes
headers = {"Authorization": "YOUR_API_KEY"}  # Missing "Bearer"
headers = {"Authorization": "Bearer: YOUR_API_KEY"}  # Extra colon
HTTP Status: 403
Cause: Valid credentials but insufficient permissions
Solutions:
  • Verify your organization has access to the requested resource
  • Contact your organization admin to check permissions
  • Ensure you’re accessing resources within your organization scope
HTTP Status: 401
Cause: API key has expired or been revoked
Solutions:
  • Generate a new API key in the Newton Console
  • Update your application with the new key
  • Implement key rotation in your system

Request Errors

HTTP Status: 400
Cause: Malformed request or missing required parameters
Solutions:
  • Check that all required parameters are included
  • Verify parameter types and formats
  • Ensure JSON is properly formatted for POST requests
{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "Missing required parameter: lens_id",
    "details": {
      "missing_fields": ["lens_id"]
    }
  }
}
HTTP Status: 400
Cause: Specified lens_id does not exist or is not available
Solutions:
  • Get available lens IDs from /lens/metadata endpoint
  • Verify the lens ID format is correct
  • Check that the lens belongs to your organization
HTTP Status: 400
Cause: Unsupported file format uploaded
Solutions:
  • Check supported formats: JPEG, PNG, MP4, CSV, TSV, JSON
  • Verify file extension matches content type
  • Convert file to supported format if needed
HTTP Status: 413
Cause: File exceeds 1GB size limit
Solutions:
  • Compress or resize the file
  • Split large files into smaller chunks
  • Use video compression for large video files

Session Errors

HTTP Status: 404
Cause: Session ID does not exist or has been destroyed
Solutions:
  • Verify the session ID is correct
  • Check if session was destroyed or timed out
  • Create a new session if needed
HTTP Status: 429
Cause: Maximum concurrent sessions reached
Solutions:
  • Destroy unused sessions with /lens/sessions/destroy
  • Implement session pooling in your application
  • Contact support to discuss higher limits
HTTP Status: 408
Cause: Session idle for more than 30 minutes
Solutions:
  • Send periodic keep-alive messages
  • Recreate session if needed
  • Implement automatic session refresh

Rate Limiting

HTTP Status: 429
Cause: Too many requests in a short time period
Response includes retry information:
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Please retry after 60 seconds.",
    "details": {
      "retry_after": 60,
      "limit": 100,
      "window": 60,
      "current_usage": 100
    }
  }
}
Solutions:
  • Implement exponential backoff
  • Respect the retry_after value
  • Reduce request frequency
  • Implement request queuing

Retry Strategies

Exponential Backoff

Implement exponential backoff for transient errors:
import time
import random
import requests

def make_request_with_retry(url, headers, max_retries=3):
    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 == 429:
                # Rate limited - respect retry_after
                error_data = response.json()
                retry_after = error_data.get('error', {}).get('details', {}).get('retry_after', 60)
                print(f"Rate limited. Waiting {retry_after} seconds...")
                time.sleep(retry_after)
                continue
            
            elif response.status_code in [500, 502, 503, 504]:
                # Server error - exponential backoff
                wait_time = (2 ** attempt) + random.uniform(0, 1)
                print(f"Server error. Retrying in {wait_time:.2f} seconds...")
                time.sleep(wait_time)
                continue
            
            else:
                # Client error - don't retry
                print(f"Client error: {response.status_code}")
                response.raise_for_status()
                
        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                raise e
            
            wait_time = (2 ** attempt) + random.uniform(0, 1)
            print(f"Request failed. Retrying in {wait_time:.2f} seconds...")
            time.sleep(wait_time)
    
    raise Exception(f"Max retries ({max_retries}) exceeded")

# Usage
try:
    data = make_request_with_retry(
        "https://api.u1.archetypeai.app/v0.5/lens/info",
        {"Authorization": "Bearer YOUR_API_KEY"}
    )
    print(data)
except Exception as e:
    print(f"Request failed after retries: {e}")

Circuit Breaker Pattern

For production systems, implement a circuit breaker:
import time
from enum import Enum

class CircuitState(Enum):
    CLOSED = "closed"      # Normal operation
    OPEN = "open"          # Failing, reject requests
    HALF_OPEN = "half_open"  # Testing if service recovered

class CircuitBreaker:
    def __init__(self, failure_threshold=5, recovery_timeout=60):
        self.failure_threshold = failure_threshold
        self.recovery_timeout = recovery_timeout
        self.failure_count = 0
        self.last_failure_time = None
        self.state = CircuitState.CLOSED
    
    def call(self, func, *args, **kwargs):
        if self.state == CircuitState.OPEN:
            if self._should_attempt_reset():
                self.state = CircuitState.HALF_OPEN
            else:
                raise Exception("Circuit breaker is OPEN")
        
        try:
            result = func(*args, **kwargs)
            self._on_success()
            return result
        except Exception as e:
            self._on_failure()
            raise e
    
    def _should_attempt_reset(self):
        return (time.time() - self.last_failure_time) >= self.recovery_timeout
    
    def _on_success(self):
        self.failure_count = 0
        self.state = CircuitState.CLOSED
    
    def _on_failure(self):
        self.failure_count += 1
        self.last_failure_time = time.time()
        
        if self.failure_count >= self.failure_threshold:
            self.state = CircuitState.OPEN

# Usage
circuit_breaker = CircuitBreaker()

def api_call():
    response = requests.get(
        "https://api.u1.archetypeai.app/v0.5/lens/info",
        headers={"Authorization": "Bearer YOUR_API_KEY"}
    )
    response.raise_for_status()
    return response.json()

try:
    data = circuit_breaker.call(api_call)
    print(data)
except Exception as e:
    print(f"Circuit breaker prevented call: {e}")

Error Monitoring

Logging Best Practices

import logging
import json

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def log_api_error(response, request_details):
    """Log API errors for monitoring and debugging"""
    try:
        error_data = response.json()
        logger.error(
            "API Error",
            extra={
                "status_code": response.status_code,
                "error_code": error_data.get('error', {}).get('code'),
                "error_message": error_data.get('error', {}).get('message'),
                "request_url": request_details.get('url'),
                "request_method": request_details.get('method'),
                "response_body": error_data
            }
        )
    except Exception:
        logger.error(
            "API Error (unparseable response)",
            extra={
                "status_code": response.status_code,
                "response_text": response.text,
                "request_url": request_details.get('url'),
                "request_method": request_details.get('method')
            }
        )

# Usage in your API calls
response = requests.get(url, headers=headers)
if not response.ok:
    log_api_error(response, {"url": url, "method": "GET"})
    response.raise_for_status()
If you are experiencing issues while following this guide: When contacting support, please include:
  • Error codes and messages
  • Request/response examples
  • Timestamps of errors
  • Your organization ID
  • Steps to reproduce the issue