AI Magicx
Getting Started

Authentication

Authentication

Overview

The AI Magicx API implements Bearer token authentication using secure API keys. All API requests must include a valid API key to authenticate and authorize access to resources.

API Key Management

Creating API Keys

  1. Access the Dashboard

    Code
    https://beta.aimagicx.com/home/[account]/api-keys
  2. Generate New Key

    • Click "Create API Key"
    • Provide a descriptive name (e.g., "Production App", "Development Testing")
    • Select expiration period (optional)
    • Configure permissions scope
    • Copy the generated key immediately
  3. Key Format

    Code
    mgx-sk-[unique-identifier]
    • Prefix: mgx-sk (AI Magicx Secure Key)
    • Identifier: 32-character alphanumeric string

Key Security

⚠️ Critical Security Notice

  • API keys are shown only once during creation
  • Keys cannot be retrieved after initial display
  • Store keys in secure, encrypted storage
  • Never expose keys in client-side code or repositories

Authentication Implementation

Request Format

Include the API key in the Authorization header using Bearer scheme:

Code
Authorization: Bearer mgx-sk-a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6

Implementation Examples

cURL

Code(bash)
curl -X POST https://beta.aimagicx.com/api/v1/chat \ -H "Authorization: Bearer mgx-sk-your-api-key" \ -H "Content-Type: application/json" \ -d '{ "message": "Analyze this text", "model": "4o-mini" }'

Node.js/TypeScript

Code(typescript)
import { config } from 'dotenv'; config(); const AIMAGICX_API_KEY = process.env.AIMAGICX_API_KEY; const API_BASE_URL = 'https://beta.aimagicx.com/api/v1'; async function makeAuthenticatedRequest(endpoint: string, data: any) { const response = await fetch(`${API_BASE_URL}${endpoint}`, { method: 'POST', headers: { 'Authorization': `Bearer ${AIMAGICX_API_KEY}`, 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify(data) }); if (!response.ok) { const error = await response.json(); throw new Error(`API Error: ${error.error.message}`); } return response.json(); }

Python

Code(python)
import os import requests from typing import Dict, Any class AIMAGICXClient: def __init__(self, api_key: str = None): self.api_key = api_key or os.environ.get('AIMAGICX_API_KEY') if not self.api_key: raise ValueError("API key required") self.base_url = 'https://beta.aimagicx.com/api/v1' self.headers = { 'Authorization': f'Bearer {self.api_key}', 'Content-Type': 'application/json', 'Accept': 'application/json' } def request(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]: response = requests.post( f'{self.base_url}{endpoint}', headers=self.headers, json=data ) response.raise_for_status() return response.json()

Go

Code(go)
package main import ( "bytes" "encoding/json" "fmt" "net/http" "os" ) type Client struct { APIKey string BaseURL string } func NewClient() *Client { return &Client{ APIKey: os.Getenv("AIMAGICX_API_KEY"), BaseURL: "https://beta.aimagicx.com/api/v1", } } func (c *Client) Request(endpoint string, payload interface{}) (map[string]interface{}, error) { data, err := json.Marshal(payload) if err != nil { return nil, err } req, err := http.NewRequest("POST", c.BaseURL+endpoint, bytes.NewBuffer(data)) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+c.APIKey) req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") // Execute request... }

Permission Scopes

Available Scopes

ScopeDescriptionAvailable Plans
chat:completionsChat CompletionsAll API plans
models:readRead ModelsAll API plans
tools:readRead ToolsAll API plans
usage:readRead Usage StatisticsAll API plans
account:readRead Account InformationAll API plans
credits:readRead CreditsAll API plans
credits:purchasePurchase CreditsAll API plans
image:generateGenerate ImagesAll API plans
logo:generateGenerate LogosAll API plans

Security Best Practices

1. Environment Variables

Code(bash)
# .env file (never commit to version control) AIMAGICX_API_KEY=mgx-sk-your-api-key

2. Key Rotation Policy

  • Rotate production keys every 90 days
  • Implement zero-downtime rotation
  • Maintain audit logs of key usage
  • Automate rotation reminders

Error Handling

Authentication Errors

Missing Authorization Header

Code(json)
{ "success": false, "error": { "code": "AUTH_MISSING", "message": "Authorization header required", "status": 401 } }

Invalid Key Format

Code(json)
{ "success": false, "error": { "code": "AUTH_INVALID_FORMAT", "message": "Invalid authorization format. Expected: Bearer mgx-sk-...", "status": 401 } }

Expired or Revoked Key

Code(json)
{ "success": false, "error": { "code": "AUTH_KEY_INVALID", "message": "API key is invalid, expired, or revoked", "status": 401 } }

Insufficient Permissions

Code(json)
{ "success": false, "error": { "code": "AUTH_INSUFFICIENT_SCOPE", "message": "Operation requires 'image:generate' scope", "status": 403, "details": { "required_scope": "image:generate", "current_scopes": ["chat:write", "models:read"] } } }

Handling Authentication Failures

Code(javascript)
async function makeSecureRequest(endpoint, data) { try { const response = await fetch(endpoint, { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); if (response.status === 401) { // Authentication failed - check key validity console.error('Authentication failed. Check API key.'); // Implement key refresh logic if applicable } else if (response.status === 403) { // Insufficient permissions console.error('Insufficient permissions for this operation.'); } return response.json(); } catch (error) { console.error('Request failed:', error); throw error; } }

Monitoring & Compliance

Security Headers

All authenticated responses include security metadata:

Code
X-API-Key-ID: key_abc123 X-API-Key-Name: Production App X-API-Key-Scopes: chat:write,models:read X-Request-ID: req_xyz789 X-RateLimit-Remaining: 59

Audit Logging

Enterprise plans include comprehensive audit logs:

  • API key creation/deletion
  • Permission changes
  • Unusual usage patterns
  • Geographic anomalies
  • Failed authentication attempts

Compliance Standards

  • OAuth 2.0: Bearer token implementation
  • OWASP: API Security Top 10 compliance
  • PCI DSS: For payment-related operations
  • SOC 2: Type II certification (in progress)

Next Steps


For security concerns or questions, contact contact@aimagicx.com

Last modified on