Skip to main content

Welcome to Sora2API

Sora2API empowers you to generate high-quality video content using advanced AI models. Whether you’re building applications, automating workflows, or creating content, our API provides simple and reliable access to AI video generation.

Authentication

All API requests require authentication using a Bearer token. Please obtain your API key from the API Key Management Page.
Keep your API key secure and never share it publicly. Reset it immediately if you suspect it has been compromised.

API Base URL

https://api.sora2api.ai

Authentication Header

Authorization: Bearer YOUR_API_KEY

Quick Start Guide

Step 1: Generate Your First Video

Start with a simple text-to-video generation request:
async function generateVideo() {
  try {
    const response = await fetch('https://api.sora2api.ai/api/v1/sora2/generate', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        prompt: 'A cute kitten playing in a garden on a bright spring day',
        aspectRatio: 'landscape',
        quality: 'hd'
      })
    });
    
    const data = await response.json();
    
    if (response.ok && data.code === 200) {
      console.log('Task submitted:', data);
      console.log('Task ID:', data.data.taskId);
      return data.data.taskId;
    } else {
      console.error('Request failed:', data.msg || 'Unknown error');
      return null;
    }
  } catch (error) {
    console.error('Error:', error.message);
    return null;
  }
}

generateVideo();

Step 2: Check Task Status

Use the returned task ID to check the generation status:
curl -X GET "https://api.sora2api.ai/api/v1/sora2/record-info?taskId=YOUR_TASK_ID" \
  -H "Authorization: Bearer YOUR_API_KEY"

Response Format

Success Response:
{
  "code": 200,
  "msg": "success",
  "data": {
    "taskId": "sora2_task_abcdef123456"
  }
}
Task Status Response:
{
  "code": 200,
  "msg": "success",
  "data": {
    "taskId": "sora2_task_abcdef123456",
    "paramJson": "{\"prompt\":\"A cute kitten playing in a garden on a bright spring day\",\"aspectRatio\":\"landscape\",\"quality\":\"hd\"}",
    "completeTime": "2024-03-20 10:30:00",
    "response": {
      "imageUrl": "https://cdn.sora2api.ai/videos/example_video.mp4"
    },
    "successFlag": 1,
    "errorCode": 0,
    "errorMessage": null,
    "createTime": "2024-03-20 10:25:00"
  }
}

Generation Modes

  • Text to Video
  • Image to Video
  • Add Watermark
Generate videos from text descriptions:
{
  "prompt": "A cute kitten playing in a garden on a bright spring day",
  "aspectRatio": "landscape",
  "quality": "hd"
}

Aspect Ratios

Choose the appropriate aspect ratio for your needs:

Landscape

Use CasesHD videos, desktop wallpapers, horizontal viewing content

Portrait

Use CasesPhone wallpapers, short videos, vertical viewing content

Quality Options

Standard

Standard QualitySuitable for quick generation and preview, saves credits

HD

High DefinitionHigh-quality output, suitable for official releases and commercial use

Key Parameters

prompt
string
required
Text description of the desired video content. Be specific and descriptive for best results.Tips for Better Prompts:
  • Include scene descriptions (e.g., “garden”, “beach”, “city street”)
  • Specify subject actions (e.g., “running”, “dancing”, “flying”)
  • Add atmosphere descriptions (e.g., “sunny”, “mysterious night”, “warm ambiance”)
aspectRatio
string
Output video aspect ratio. Options:
  • landscape - Horizontal (suitable for desktop viewing)
  • portrait - Vertical (suitable for mobile viewing)
quality
string
Video quality:
  • standard - Standard quality
  • hd - High definition
imageUrls
array
Array of image URLs for image-to-video mode.Notes:
  • Images must be publicly accessible URLs
  • Supports common image formats (JPG, PNG, etc.)
watermark
string
Watermark text to display on the generated video.Note: Optional parameter, can be omitted if watermark is not needed.
callBackUrl
string
Callback URL to receive task completion notifications.Recommendation: Use callbacks instead of polling in production environments for better efficiency.

Complete Workflow Example

Here’s a complete example of generating a video and waiting for completion:
  • JavaScript
  • Python
class Sora2API {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.sora2api.ai/api/v1/sora2';
  }
  
  async generateVideo(options) {
    const response = await fetch(`${this.baseUrl}/generate`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(options)
    });
    
    const result = await response.json();
    if (!response.ok || result.code !== 200) {
      throw new Error(`Generation failed: ${result.msg || 'Unknown error'}`);
    }
    
    return result.data.taskId;
  }
  
  async waitForCompletion(taskId, maxWaitTime = 600000) { // Max wait 10 minutes
    const startTime = Date.now();
    
    while (Date.now() - startTime < maxWaitTime) {
      const status = await this.getTaskStatus(taskId);
      
      switch (status.successFlag) {
        case 0:
          console.log('Task generating, waiting...');
          break;
          
        case 1:
          console.log('Generation completed successfully!');
          return status.response;
          
        case 2:
          const taskError = status.errorMessage || 'Task creation failed';
          console.error('Task creation failed:', taskError);
          if (status.errorCode) {
            console.error('Error code:', status.errorCode);
          }
          throw new Error(taskError);
          
        case 3:
          const generateError = status.errorMessage || 'Task generation failed';
          console.error('Generation failed:', generateError);
          if (status.errorCode) {
            console.error('Error code:', status.errorCode);
          }
          throw new Error(generateError);
          
        default:
          console.log(`Unknown status: ${status.successFlag}`);
          if (status.errorMessage) {
            console.error('Error message:', status.errorMessage);
          }
          break;
      }
      
      // Wait 30 seconds before checking again
      await new Promise(resolve => setTimeout(resolve, 30000));
    }
    
    throw new Error('Generation timeout');
  }
  
  async getTaskStatus(taskId) {
    const response = await fetch(`${this.baseUrl}/record-info?taskId=${taskId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`
      }
    });
    
    const result = await response.json();
    if (!response.ok || result.code !== 200) {
      throw new Error(`Status check failed: ${result.msg || 'Unknown error'}`);
    }
    
    return result.data;
  }
}

// Usage example
async function main() {
  const api = new Sora2API('YOUR_API_KEY');
  
  try {
    // Text to video generation
    console.log('Starting video generation...');
    const taskId = await api.generateVideo({
      prompt: 'A cute kitten playing in a garden on a bright spring day, camera slowly zooming in',
      aspectRatio: 'landscape',
      quality: 'hd',
      watermark: 'My Video'
    });
    
    // Wait for completion
    console.log(`Task ID: ${taskId}. Waiting for completion...`);
    const result = await api.waitForCompletion(taskId);
    
    console.log('Video generation successful!');
    console.log('Video URL:', result.imageUrl);
    
  } catch (error) {
    console.error('Error:', error.message);
  }
}

main();

Asynchronous Processing with Callbacks

For production applications, use callbacks instead of polling:
{
  "prompt": "A cute kitten playing in a garden on a bright spring day",
  "aspectRatio": "landscape",
  "quality": "hd",
  "callBackUrl": "https://your-app.com/webhook/sora2-callback"
}
When generation is complete, the system will POST the results to your callback URL.

Learn More About Callbacks

Complete guide to implementing and handling Sora2API callbacks

Best Practices

  • Be specific and descriptive in your prompts
  • Include scene, action, and atmosphere details
  • Describe desired camera movements (e.g., “slow push in”, “orbit shot”)
  • Test different prompt variations to find the best results
  • Use callbacks instead of frequent polling
  • Implement proper error handling and retry logic
  • Cache results when possible
  • Choose appropriate quality based on your needs
  • Use standard quality for testing and preview
  • Use HD option only when needed
  • Monitor your credit usage regularly
  • Set up usage alerts in your application
  • Always check response status codes
  • Use successFlag to determine actual task status
  • Implement exponential backoff for retries
  • Handle rate limiting gracefully
  • Log errors for debugging and monitoring

Status Codes

200
Success
Request processed successfully
400
Bad Request
Invalid request parameters or malformed JSON
401
Unauthorized
Missing or invalid API key
402
Insufficient Credits
Account doesn’t have enough credits for the operation
429
Rate Limited
Too many requests - implement backoff strategy
500
Server Error
Internal server error - contact support if persists

Generation Task Status

successFlag: 0
Generating
Task is currently being processed
successFlag: 1
Success
Task completed successfully
successFlag: 2
Task Creation Failed
Task creation failed
successFlag: 3
Generation Failed
Task created successfully but generation failed

Video Storage and Retention

Generated video files are retained for 15 days before deletion. Please download and save your videos within this timeframe.
  • Video URLs remain accessible for 15 days after generation
  • Plan your workflow to download or process videos before expiration
  • Consider implementing automatic download systems for production use

Next Steps

Support

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

Ready to start generating amazing AI videos? Get your API key and begin creating today!