Skip to main content

Welcome to Common API

The Common API provides essential utility services for managing your kie.ai account and handling generated content. These APIs help you monitor credit usage and access generated files efficiently.

Authentication

All API requests require authentication using Bearer tokens. Please obtain your API key from the API Key Management Page.
Please keep your API key secure and never share it publicly. If you suspect your key has been compromised, reset it immediately.

API Base URL

https://api.kie.ai

Authentication Header

Authorization: Bearer YOUR_API_KEY

Quick Start Guide

Step 1: Check Your Credit Balance

Monitor your account credits to ensure sufficient balance for continued service:
curl -X GET "https://api.kie.ai/api/v1/chat/credit" \
  -H "Authorization: Bearer YOUR_API_KEY"
Response:
{
  "code": 200,
  "msg": "success",
  "data": 100
}

Step 2: Get Download URL for Generated Files

Convert generated file URLs to temporary downloadable links:
curl -X POST "https://api.kie.ai/api/v1/common/download-url" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://tempfile.1f6cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxbd98"
  }'
Response:
{
  "code": 200,
  "msg": "success",
  "data": "https://tempfile.1f6cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxbd98"
}
Download URLs are valid for 20 minutes only. Make sure to download or cache the content within this timeframe.

API Overview

Get Account Credits

GET /api/v1/chat/credit

Purpose: Monitor your account credit balanceFeatures:
  • Real-time credit balance retrieval
  • No parameters required
  • Instant response
  • Essential for usage monitoring
Use Cases:
  • Check credits before starting generation tasks
  • Monitor credit consumption patterns
  • Plan credit replenishment
  • Implement credit threshold alerts

Get Download URL

POST /api/v1/common/download-url

Purpose: Generate temporary download links for generated filesFeatures:
  • Supports all kie.ai generated file types (images, videos, audio, etc.)
  • 20-minute validity period
  • Secure authenticated access
  • Only works with kie.ai generated URLs
Use Cases:
  • Download generated content to local storage
  • Share temporary links with team members
  • Integrate with external systems
  • Build custom download workflows

Practical Examples

Credit Monitoring System

Implement an automated credit monitoring system:
class KieAIClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.kie.ai';
  }
  
  async getCredits() {
    const response = await fetch(`${this.baseUrl}/api/v1/chat/credit`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`
      }
    });
    
    if (!response.ok) {
      throw new Error(`Failed to get credits: ${response.statusText}`);
    }
    
    const result = await response.json();
    return result.data;
  }
  
  async getDownloadUrl(fileUrl) {
    const response = await fetch(`${this.baseUrl}/api/v1/common/download-url`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ url: fileUrl })
    });
    
    if (!response.ok) {
      throw new Error(`Failed to get download URL: ${response.statusText}`);
    }
    
    const result = await response.json();
    return result.data;
  }
  
  async downloadFile(fileUrl, outputPath) {
    // Get download URL
    const downloadUrl = await this.getDownloadUrl(fileUrl);
    
    // Download file
    const response = await fetch(downloadUrl);
    const buffer = await response.arrayBuffer();
    
    // Save to file (Node.js)
    const fs = require('fs');
    fs.writeFileSync(outputPath, Buffer.from(buffer));
    
    console.log(`File downloaded to: ${outputPath}`);
  }
  
  async checkCreditsAndWarn(threshold = 10) {
    const credits = await this.getCredits();
    
    if (credits < threshold) {
      console.warn(`⚠️  Low credits warning: ${credits} credits remaining`);
      return false;
    }
    
    console.log(`✓ Credits available: ${credits}`);
    return true;
  }
}

// Usage example
const client = new KieAIClient('YOUR_API_KEY');

// Monitor credits before operation
async function runWithCreditCheck() {
  const hasEnoughCredits = await client.checkCreditsAndWarn(20);
  
  if (!hasEnoughCredits) {
    console.error('Insufficient credits. Please recharge your account.');
    return;
  }
  
  // Proceed with operations
  console.log('Credits verified. Proceeding with operations...');
}

// Download generated files
async function downloadGeneratedFiles(fileUrls) {
  for (let i = 0; i < fileUrls.length; i++) {
    try {
      await client.downloadFile(
        fileUrls[i],
        `./downloads/file-${i + 1}.mp4`
      );
      console.log(`✓ Downloaded file ${i + 1}/${fileUrls.length}`);
    } catch (error) {
      console.error(`✗ Failed to download file ${i + 1}:`, error.message);
    }
  }
}

// Periodic credit monitoring
async function monitorCredits(intervalMinutes = 60) {
  setInterval(async () => {
    try {
      const credits = await client.getCredits();
      console.log(`[${new Date().toISOString()}] Current credits: ${credits}`);
      
      if (credits < 50) {
        // Send alert (email, webhook, etc.)
        console.warn('ALERT: Credits below 50!');
      }
    } catch (error) {
      console.error('Credit check failed:', error.message);
    }
  }, intervalMinutes * 60 * 1000);
}

Error Handling

Common errors and handling methods:
// Check if API key is correct
if (response.status === 401) {
  console.error('Invalid API key, please check Authorization header');
  // Retrieve or update API key
}
// Only kie.ai generated URLs are supported
if (response.status === 422) {
  const error = await response.json();
  console.error('Invalid URL:', error.msg);
  // Ensure you're using a kie.ai generated file URL
  // External URLs are not supported
}
// Credits depleted, need to recharge
if (response.status === 402) {
  console.error('Insufficient credits. Please recharge your account.');
  // Redirect to credit purchase page
  // Or send notification to admin
}
// Implement retry mechanism
async function apiCallWithRetry(apiFunction, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await apiFunction();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      
      // Exponential backoff
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

Best Practices

  • Monitor regularly: Check credits before starting large batch operations
  • Set up alerts: Implement automated alerts when credits fall below threshold
  • Budget planning: Track credit consumption patterns for better planning
  • Graceful degradation: Handle insufficient credit scenarios appropriately
  • Time-sensitive: Download URLs expire after 20 minutes
  • Cache appropriately: Save files immediately after getting download URLs
  • Batch downloads: Process multiple files efficiently within time limit
  • Error handling: Implement retry logic for failed downloads
  • Parallel processing: Download multiple files concurrently (respect rate limits)
  • Connection pooling: Reuse HTTP connections for multiple requests
  • Timeout settings: Set appropriate timeouts for download operations
  • Progress tracking: Implement progress indicators for long-running operations
  • API key protection: Never expose API keys in client-side code
  • HTTPS only: Always use HTTPS for API requests
  • Key rotation: Regularly rotate API keys for security
  • Access logging: Keep logs of API usage for auditing

Important Notes

Download URL Expiration: Temporary download URLs are valid for 20 minutes only. Make sure to:
  • Download files immediately after getting the URL
  • Implement error handling for expired URLs
  • Cache downloaded content for future use
Credit Balance: Service access will be restricted when credits are depleted. Always:
  • Monitor credit balance regularly
  • Set up low-credit alerts
  • Plan credit replenishment in advance
  • Implement graceful degradation when credits are low
Supported URLs: The download URL endpoint only supports files generated by kie.ai services. External file URLs will result in a 422 validation error.

Status Codes

200
Success
Request processed successfully
401
Unauthorized
Authentication credentials are missing or invalid
402
Insufficient Credits
Account does not have enough credits to perform the operation
404
Not Found
The requested resource or endpoint does not exist
422
Validation Error
Invalid request parameters (e.g., external URL not supported)
429
Rate Limited
Request limit has been exceeded for this resource
455
Service Unavailable
System is currently undergoing maintenance
500
Server Error
An unexpected error occurred while processing the request
505
Feature Disabled
The requested feature is currently disabled

Next Steps

Integration Examples

Support

Need help? Our technical support team is here to assist you.

Ready to start? Get your API key and begin using Common API services immediately!