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
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"
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"
}
Use images as input to generate videos: {
"prompt" : "Animate this image with natural motion effects" ,
"imageUrls" : [ "https://example.com/source-image.jpg" ],
"aspectRatio" : "landscape" ,
"quality" : "hd"
}
Add watermark to generated videos: {
"prompt" : "A cute kitten playing in a garden on a bright spring day" ,
"aspectRatio" : "portrait" ,
"quality" : "hd" ,
"watermark" : "My Watermark"
}
Aspect Ratios
Choose the appropriate aspect ratio for your needs:
Landscape Use Cases HD videos, desktop wallpapers, horizontal viewing content
Portrait Use Cases Phone wallpapers, short videos, vertical viewing content
Quality Options
Standard Standard Quality Suitable for quick generation and preview, saves credits
HD High Definition High-quality output, suitable for official releases and commercial use
Key Parameters
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”)
Output video aspect ratio. Options:
landscape - Horizontal (suitable for desktop viewing)
portrait - Vertical (suitable for mobile viewing)
Video quality:
standard - Standard quality
hd - High definition
Array of image URLs for image-to-video mode. Notes:
Images must be publicly accessible URLs
Supports common image formats (JPG, PNG, etc.)
Watermark text to display on the generated video. Note: Optional parameter, can be omitted if watermark is not needed.
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:
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 ();
import requests
import time
class Sora2API :
def __init__ ( self , api_key ):
self .api_key = api_key
self .base_url = 'https://api.sora2api.ai/api/v1/sora2'
self .headers = {
'Authorization' : f 'Bearer { api_key } ' ,
'Content-Type' : 'application/json'
}
def generate_video ( self , ** options ):
response = requests.post( f ' { self .base_url } /generate' ,
headers = self .headers, json = options)
result = response.json()
if not response.ok or result.get( 'code' ) != 200 :
raise Exception ( f "Generation failed: { result.get( 'msg' , 'Unknown error' ) } " )
return result[ 'data' ][ 'taskId' ]
def wait_for_completion ( self , task_id , max_wait_time = 600 ):
start_time = time.time()
while time.time() - start_time < max_wait_time:
status = self .get_task_status(task_id)
success_flag = status[ 'successFlag' ]
if success_flag == 0 :
print ( "Task generating, waiting..." )
elif success_flag == 1 :
print ( "Generation completed successfully!" )
return status[ 'response' ]
elif success_flag == 2 :
task_error = status.get( 'errorMessage' , 'Task creation failed' )
print ( f "Task creation failed: { task_error } " )
if status.get( 'errorCode' ):
print ( f "Error code: { status[ 'errorCode' ] } " )
raise Exception (task_error)
elif success_flag == 3 :
generate_error = status.get( 'errorMessage' , 'Task generation failed' )
print ( f "Generation failed: { generate_error } " )
if status.get( 'errorCode' ):
print ( f "Error code: { status[ 'errorCode' ] } " )
raise Exception (generate_error)
else :
print ( f "Unknown status: { success_flag } " )
if status.get( 'errorMessage' ):
print ( f "Error message: { status[ 'errorMessage' ] } " )
time.sleep( 30 ) # Wait 30 seconds
raise Exception ( 'Generation timeout' )
def get_task_status ( self , task_id ):
response = requests.get( f ' { self .base_url } /record-info?taskId= { task_id } ' ,
headers = { 'Authorization' : f 'Bearer { self .api_key } ' })
result = response.json()
if not response.ok or result.get( 'code' ) != 200 :
raise Exception ( f "Status check failed: { result.get( 'msg' , 'Unknown error' ) } " )
return result[ 'data' ]
# Usage example
def main ():
api = Sora2API( 'YOUR_API_KEY' )
try :
# Text to video generation
print ( 'Starting video generation...' )
task_id = api.generate_video(
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
print ( f 'Task ID: { task_id } . Waiting for completion...' )
result = api.wait_for_completion(task_id)
print ( 'Video generation successful!' )
print ( f 'Video URL: { result[ "imageUrl" ] } ' )
except Exception as error:
print ( f 'Error: { error } ' )
if __name__ == '__main__' :
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 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
Request processed successfully
Invalid request parameters or malformed JSON
Missing or invalid API key
Account doesn’t have enough credits for the operation
Too many requests - implement backoff strategy
Internal server error - contact support if persists
Generation Task Status
Task is currently being processed
Task completed successfully
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!