API Documentation

Everything you need to integrate moder8r into your application

Error Reference

Comprehensive guide to handling errors returned by the moder8r API.

Error Response Format

Errors from the native endpoints (/v1/moderate/text and /v1/moderate) return a JSON object with an error object:

Error Response Structure
{
  "error": {
    "code": "text_too_long",
    "message": "Text exceeds maximum length of 10240 bytes. Current: 12873 bytes",
    "details": {
      "max_bytes": 10240,
      "current_bytes": 12873
    }
  },
  "request_id": "mod_3f2b8c1e-9a4d-4c7e-b1f0-6d2a5e8c9b13"
}
error.code

Machine-readable error identifier. Branch on this, not on the message.

error.message

Human-readable description. Wording may change.

error.details

Optional extra data, e.g. limits for text_too_long, invalid_themes, and quota_exceeded.

request_id

Included on /v1/moderate/text errors after authentication succeeds. 401 responses and legacy /v1/moderate errors don't include it.

Error Codes: POST /v1/moderate/text

Error CodeStatusCategoryDescriptionSolution
missing_api_key
401
Authentication
No Authorization header providedSend Authorization: Bearer m8r_sk_...
invalid_auth_format
401
Authentication
Authorization header doesn't start with "Bearer "Use the format Authorization: Bearer m8r_sk_...
invalid_api_key
401
Authentication
API key is unknown or has been revokedCheck your API key in the dashboard
invalid_json
400
Request
Request body is not valid JSONSend a valid JSON body with Content-Type: application/json
missing_text
400
Request
No 'text' (or 'content') field, or it isn't a stringInclude a 'text' string in the request body
empty_text
400
Request
Text is empty or only whitespaceSend non-empty text, or skip moderation for empty input
text_too_long
400
Request
Text exceeds 10,240 bytes (UTF-8). details.max_bytes and details.current_bytes are included.Split the text into chunks under 10,240 bytes
invalid_threshold
400
Request
threshold is outside the range 0 to 1Use a number between 0 and 1
invalid_themes
400
Request
themes isn't an array of up to 10 non-empty strings of at most 100 characters eachTrim the list to 10 or fewer short themes
invalid_explain
400
Request
explain isn't a booleanSend true or false (not a string)
quota_exceeded
402
Rate Limiting
Monthly request limit reached. details.usage and details.limit are included.Upgrade your plan, or wait for the reset on the 1st of the month (UTC)
rate_limit_exceeded
429
Rate Limiting
Per-minute rate limit for your key exceededWait Retry-After seconds, then retry with backoff
openai_rate_limit
429
Server
The upstream moderation provider is rate limitedRetry with exponential backoff
internal_error
500
Server
Unexpected server errorRetry after a short delay. Contact support with the request_id if it persists.
moderation_failed
502
Server
The upstream moderation provider returned an errorRetry with exponential backoff

Other Endpoints

Legacy POST /v1/moderate

Uses the same error.code / error.message shape without request_id, and different codes: invalid_content, empty_content, and content_too_long (400); quota_exceeded (402, with error.usage and error.upgrade_url); rate_limit_exceeded (429, with error.retry_after); moderation_rate_limit and moderation_api_error (503); and internal_error (500).

Perspective-compatible endpoints

comments:analyze and comments:suggestscore return Google-style errors so existing Perspective clients keep working. Note that error.code is the numeric HTTP status here, and both rate-limit and monthly-quota failures return 429 RESOURCE_EXHAUSTED (told apart by errors[0].reason: rateLimitExceeded or quotaExceeded), not 402.

Perspective error
{
  "error": {
    "code": 429,
    "message": "Monthly quota exceeded.",
    "status": "RESOURCE_EXHAUSTED",
    "errors": [
      {
        "domain": "commentanalyzer.googleapis.com",
        "reason": "quotaExceeded",
        "message": "Monthly quota exceeded."
      }
    ]
  }
}

Statuses: 400 INVALID_ARGUMENT, 401 UNAUTHENTICATED, 429 RESOURCE_EXHAUSTED, 500 INTERNAL, 503 UNAVAILABLE.

HTTP Status Codes

Status CodeMeaningAction
200
SuccessProcess the response data
400
Bad RequestFix request format/content and retry
401
UnauthorizedCheck API key and authentication
402
Payment RequiredUpgrade plan or wait for the monthly reset (1st of the month, UTC)
429
Too Many RequestsWait Retry-After seconds (rate_limit_exceeded) or back off (openai_rate_limit), then retry
500
Server ErrorRetry with exponential backoff
502
Bad Gateway (moderation_failed)Upstream moderation provider failed. Retry with backoff.
503
Service UnavailableLegacy /v1/moderate and Perspective endpoints only. Retry with backoff.

Retry Logic Examples

⚠️ Rate Limiting Best Practices

Always implement exponential backoff for rate-limited requests (429 status). Respect the Retry-After header when provided.

JavaScript Implementation

// JavaScript - retry only what is retryable
const RETRYABLE = new Set([429, 500, 502, 503]);

async function moderateWithRetry(text, maxRetries = 3) {
  for (let attempt = 1; ; attempt++) {
    let response;
    try {
      response = await fetch('https://api.moder8r.app/v1/moderate/text', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${process.env.MODER8R_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text }),
      });
    } catch (networkError) {
      if (attempt >= maxRetries) throw networkError;
      await sleep(2 ** attempt * 1000);
      continue;
    }

    if (response.ok) return response.json();

    const body = await response.json().catch(() => ({}));
    const code = body.error?.code;

    // 400, 401 and 402 won't succeed on retry: fix the request, key, or plan
    if (!RETRYABLE.has(response.status) || attempt >= maxRetries) {
      throw new Error(`${response.status} ${code}: ${body.error?.message} (request_id: ${body.request_id})`);
    }

    // Prefer the server's Retry-After (sent with rate_limit_exceeded)
    const retryAfter = Number(response.headers.get('Retry-After'));
    const delay = retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 1000;
    await sleep(delay);
  }
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

Python Implementation

# Python - Retry logic with backoff
import time
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

def create_session_with_retries():
    """Create a requests session with retry strategy"""
    session = requests.Session()
    
    retry_strategy = Retry(
        total=3,
        backoff_factor=1,
        status_forcelist=[429, 500, 502, 503, 504],
        respect_retry_after_header=True,
        allowed_methods=["POST", "GET"]
    )
    
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    
    return session

def moderate_text_with_retry(content):
    """Moderate text with automatic retries"""
    session = create_session_with_retries()
    
    url = 'https://api.moder8r.app/v1/moderate/text'
    headers = {
        'Authorization': 'Bearer m8r_sk_your_key_here',
        'Content-Type': 'application/json'
    }
    data = {'text': content}
    
    try:
        response = session.post(url, headers=headers, json=data, timeout=30)
        response.raise_for_status()
        return response.json()
        
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 429:
            retry_after = e.response.headers.get('Retry-After', 60)
            print(f"Rate limited. Wait {retry_after} seconds before retrying.")
        raise
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
        raise

Error Handling Guidelines

✅ Best Practices

  • • Always check HTTP status codes first
  • • Parse error response for specific error codes
  • • Implement exponential backoff for retries
  • • Log errors with request_id for debugging
  • • Handle rate limits gracefully
  • • Validate input before making requests
  • • Set reasonable timeouts

❌ Common Mistakes

  • • Ignoring HTTP status codes
  • • Not implementing retry logic
  • • Aggressive retry without backoff
  • • Not handling quota exceeded errors
  • • Missing request validation
  • • Exposing error details to end users
  • • Not monitoring error rates