LogoRuxa.ai
Ruxa AI API Integration Best Practices
2025/12/24
3 min read

Ruxa AI API Integration Best Practices

Best practices for integrating Ruxa AI API - error handling, task polling, callback configuration, and cost optimization.

API Authentication

Secure API Key Storage

// ❌ Don't hardcode
const apiKey = "sk-xxxxx";
 
// ✅ Use environment variables
const apiKey = process.env.RUXA_API_KEY;

Request Header Format

const headers = {
  'Authorization': `Bearer ${apiKey}`,
  'Content-Type': 'application/json'
};

Task Status Handling

Ruxa AI uses an asynchronous task model. After creating a task, you need to query its status to get results.

Task States

State Description
generating Task is being processed
completed Task finished, results available
fail Task failed

Polling Implementation

async function pollTaskStatus(taskId, apiKey, maxAttempts = 60) {
  const pollInterval = 5000; // 5 seconds
  
  for (let i = 0; i < maxAttempts; i++) {
    const response = await fetch(
      `https://api.ruxa.ai/api/v1/tasks/query/${taskId}`,
      {
        headers: { 'Authorization': `Bearer ${apiKey}` }
      }
    );
    
    const data = await response.json();
    
    if (data.data.state === 'completed') {
      return data.data;
    }
    
    if (data.data.state === 'fail') {
      throw new Error(data.data.failMsg || 'Task failed');
    }
    
    // Continue waiting
    await new Promise(r => setTimeout(r, pollInterval));
  }
  
  throw new Error('Polling timeout');
}

For production, use callbacks instead of polling:

const response = await fetch('https://api.ruxa.ai/api/v1/tasks/create', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    model: 'google/nano-banana',
    callBackUrl: 'https://your-app.com/api/webhook',
    input: {
      prompt: 'Your prompt here',
      output_format: 'png'
    }
  })
});

Handling Callbacks

// Next.js API Route example
export async function POST(request) {
  const data = await request.json();
  
  // Check task status
  if (data.state === 'completed') {
    // Process results
    const resultUrls = data.resultUrls;
    // Save or process images/videos
  } else if (data.state === 'fail') {
    // Handle failure
    console.error('Task failed:', data.failMsg);
  }
  
  return Response.json({ received: true });
}

Error Handling

Response Status Codes

Code Description Action
200 Success Process normally
401 Unauthorized Check API key
402 Insufficient credits Top up account
422 Validation error Check request parameters
429 Rate limited Implement backoff retry
500 Server error Retry request

Retry Logic

async function callAPIWithRetry(payload, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch('https://api.ruxa.ai/api/v1/tasks/create', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${process.env.RUXA_API_KEY}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      });
      
      const data = await response.json();
      
      if (data.code === 200) {
        return data;
      }
      
      // Don't retry client errors
      if (response.status >= 400 && response.status < 500) {
        throw new Error(`Client error: ${data.message}`);
      }
      
    } catch (error) {
      if (attempt === maxRetries) throw error;
      
      // Exponential backoff
      await new Promise(r => setTimeout(r, Math.pow(2, attempt) * 1000));
    }
  }
}

Cost Optimization

Choose the Right Model

Use Case Recommended Model
Quick prototyping google/nano-banana
High-quality images google/nano-banana-pro
Standard video sora-2
HD video sora-2-hd

Optimize Prompts

  • Concise, clear prompts often work better
  • Avoid overly long or redundant descriptions
  • Test different prompts to find the best results

Security Recommendations

  1. Never expose API keys in client-side code
  2. Use server-side proxy for API calls
  3. Rotate API keys regularly
  4. Monitor for unusual usage patterns

Learn More

Author

avatar for Ruxa AI
Ruxa AI

Categories

Newsletter

Join the community

Subscribe to our newsletter for the latest news and updates