Skip to main content

Error Response Format

All errors follow a consistent JSON structure:
{
  "error": "Human-readable error message",
  "statusCode": 400,
  "details": {
    // Optional additional context
  }
}

HTTP Status Codes

Imperial uses standard HTTP status codes to indicate success or failure.

Success Codes

CodeNameDescription
200OKRequest succeeded
201CreatedResource created successfully (uploads)

Client Error Codes (4xx)

The request was malformed or contains invalid parameters.Common Causes:
  • Missing required fields
  • Invalid file format
  • Malformed JSON
  • Invalid query parameters
Example:
{
  "error": "Validation failed",
  "statusCode": 400,
  "details": {
    "file": "File is required"
  }
}
Solutions:
  • Check request body format
  • Verify all required fields are present
  • Ensure file is properly attached
  • Validate parameter types
Missing or invalid authentication credentials.Common Causes:
  • Missing Authorization header
  • Invalid API key or upload key
  • Expired token
  • Wrong key format
Example:
{
  "error": "Invalid or missing API key",
  "statusCode": 401
}
Solutions:
  • Include Authorization: Bearer YOUR_KEY header
  • Verify key starts with imperial_live_ or imperial_upload_
  • Generate new key if compromised
  • Check key hasn’t been revoked
Authenticated but lacking required permissions.Common Causes:
  • Upload key used for non-upload endpoints (Free/Starter)
  • Trying to access another user’s resources
  • Tier doesn’t support requested feature
Example:
{
  "error": "API access requires Pro or Business tier",
  "statusCode": 403
}
Solutions:
  • Upgrade to Pro/Business for full API access
  • Use correct authentication type for endpoint
  • Verify you own the resource you’re accessing
The requested resource doesn’t exist.Common Causes:
  • Invalid image/upload ID
  • File was deleted
  • Typo in endpoint URL
Example:
{
  "error": "Image not found",
  "statusCode": 404
}
Solutions:
  • Verify resource ID is correct
  • Check if file was deleted
  • Ensure you own the resource
  • Verify endpoint URL is correct
File size or total request size exceeds limits.Common Causes:
  • Storage limit exceeded
  • File larger than available space
  • Batch upload too large
Example:
{
  "error": "Storage limit exceeded. You've used 4.8 GB of 5 GB.",
  "statusCode": 413
}
Solutions:
  • Delete old uploads to free space
  • Enable auto-compression
  • Upgrade to higher tier
  • Split large batch uploads
File type is not supported.Common Causes:
  • Uploading non-image/video files
  • Unsupported video codec
  • Corrupted file
Example:
{
  "error": "Only images and videos are allowed",
  "statusCode": 415
}
Solutions:
  • Use supported formats: JPEG, PNG, WebP, GIF, MP4, WebM, MOV, AVI
  • Verify file isn’t corrupted
  • Check MIME type is correct
Rate limit exceeded.Common Causes:
  • Too many requests per minute
  • Operations limit reached for month
  • Aggressive retry logic
Example:
{
  "error": "Rate limit exceeded. Try again in 42 seconds.",
  "statusCode": 429,
  "details": {
    "retryAfter": 42
  }
}
Solutions:
  • Respect Retry-After header
  • Implement exponential backoff
  • Reduce request frequency
  • Upgrade tier for higher rate limits

Server Error Codes (5xx)

An unexpected error occurred on the server.Common Causes:
  • Database connectivity issues
  • R2 storage unavailable
  • Unhandled exception
Example:
{
  "error": "An internal error occurred. Please try again.",
  "statusCode": 500
}
Solutions:
  • Retry the request after a delay
  • Check status page for incidents
  • Contact support if persistent
  • Implement retry logic with backoff
Service is temporarily unavailable.Common Causes:
  • Planned maintenance
  • Database migration
  • CDN issues
Example:
{
  "error": "Service temporarily unavailable",
  "statusCode": 503,
  "details": {
    "retryAfter": 300
  }
}
Solutions:
  • Wait and retry after specified time
  • Check status page for updates
  • Implement circuit breaker pattern

Common Error Scenarios

Authentication Errors

# ❌ Missing Authorization header
curl https://api.imperial.gay/images

# Error Response:
{
  "error": "Authorization header is required",
  "statusCode": 401
}

Upload Errors

# Upload when storage full
curl -X POST https://api.imperial.gay/images/upload \
  -H "Authorization: Bearer YOUR_KEY" \
  -F "[email protected]"

# Error Response:
{
  "error": "Storage limit exceeded. You've used 5.0 GB of 5 GB.",
  "statusCode": 413
}

Permission Errors

# Using upload key for listing (Free/Starter)
curl https://api.imperial.gay/images \
  -H "Authorization: Bearer imperial_upload_xxxxx"

# Error Response:
{
  "error": "API access requires Pro or Business tier",
  "statusCode": 403
}

Rate Limiting

Rate Limit Headers

Every response includes rate limit information:
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 299
X-RateLimit-Reset: 1704643200
HeaderDescription
X-RateLimit-LimitMax requests per window
X-RateLimit-RemainingRequests left in window
X-RateLimit-ResetUnix timestamp when limit resets

Handling Rate Limits

async function uploadWithRetry(file, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch('https://api.imperial.gay/images/upload', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${API_KEY}`
        },
        body: formData
      });
      
      if (response.status === 429) {
        const retryAfter = response.headers.get('Retry-After') || 60;
        console.log(`Rate limited. Retrying in ${retryAfter}s...`);
        await sleep(retryAfter * 1000);
        continue;
      }
      
      return await response.json();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(Math.pow(2, i) * 1000); // Exponential backoff
    }
  }
}

Best Practices

Error Handling

1

Check Status Code First

Use HTTP status code to determine error category (4xx vs 5xx)
2

Parse Error Message

Display error field to users for actionable feedback
3

Log Error Details

Store details object for debugging and support requests
4

Implement Retry Logic

Retry 5xx errors with exponential backoff. Don’t retry 4xx errors.

Retry Strategy

When to Retry:
  • ✅ 500 Internal Server Error
  • ✅ 503 Service Unavailable
  • ✅ 429 Rate Limited (with backoff)
  • ❌ 400-404 Client Errors (fix request instead)

Logging

Log these fields for troubleshooting:
{
  "timestamp": "2026-01-08T10:30:00Z",
  "endpoint": "POST /images/upload",
  "statusCode": 413,
  "error": "Storage limit exceeded",
  "requestId": "req_abc123",
  "userId": "user_xyz",
  "tier": "starter"
}

Testing Errors

Development Tips

# Test invalid API key
curl https://api.imperial.gay/images \
  -H "Authorization: Bearer invalid_key"

# Expected: 401 Unauthorized

Get Help