Animagent.ai API Documentation
Comprehensive API reference for developers integrating with Animagent.ai's story animation platform
Table of Contents
Getting Started
Welcome to the Animagent.ai API! This documentation provides everything you need to integrate our story animation platform into your applications.
The Animagent.ai API allows you to programmatically create animated stories, manage credits, handle user assets, and more. All API requests require authentication via API key.
Quick Example
curl -X POST https://api.animagent.ai/api/v1/tasks \
-H "Authorization: Bearer ag_live_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"story_type": "fairytale_story",
"input_story": "A magical adventure in an enchanted forest",
"voice_language": "english",
"video_length_minutes": 5
}'Important Notes
- All API endpoints use the base URL: https://api.animagent.ai/api/v1
- API keys must be kept secure and never exposed in client-side code
- Credits are automatically deducted when tasks are completed successfully
Authentication
All API requests require authentication using your user API key. To get your API key, sign up at https://animagent.ai and visit the developer dashboard to generate your key. This key is used for all programmatic API access.
Bearer Token (Recommended)
curl -H "Authorization: Bearer ag_live_YOUR_API_KEY" \
https://api.animagent.ai/api/v1/credits/balanceJavaScript Example
const response = await fetch('https://api.animagent.ai/api/v1/credits/balance', {
headers: {
'Authorization': 'Bearer ag_live_YOUR_API_KEY',
'Content-Type': 'application/json'
}
});
const data = await response.json();Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| Authorization | string | Required | Bearer token with your user API key (format: 'Bearer ag_live_YOUR_API_KEY') |
Important Notes
- API keys follow the format: ag_(live|test)_[56 random characters]
- Use ag_live_ for production and ag_test_ for development
- Generate your API key through the web dashboard at https://animagent.ai/developer
- Never expose your API key in client-side code or public repositories
- Each API key is tied to your user account and billing
Task Management API
The Task Management API allows you to create, monitor, and manage story animation tasks. Tasks go through various states from creation to completion. This endpoint maps directly to the web_animation_tasks database table.
Create a New Task
curl -X POST https://api.animagent.ai/api/v1/tasks \
-H "Authorization: Bearer ag_live_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"story_type": "fairytale_story",
"input_story": "Once upon a time in a magical kingdom...",
"voice_language": "english",
"video_length_minutes": 5,
"dimension_type": "landscape",
"enable_subtitle": true,
"watermark_enabled": true,
"watermark_file_id": "watermark_123",
"use_templates": true
}'Get Task Status
curl -H "Authorization: Bearer ag_live_YOUR_API_KEY" \
https://api.animagent.ai/api/v1/tasks/YOUR_TASK_IDList Your Tasks
curl -H "Authorization: Bearer ag_live_YOUR_API_KEY" \
"https://api.animagent.ai/api/v1/tasks?limit=10&status=completed"Calculate Task Cost
curl -X POST https://api.animagent.ai/api/v1/tasks/calculate-cost \
-H "Authorization: Bearer ag_live_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"story_type": "fairytale_story",
"input_story": "A short story for cost estimation",
"video_length_minutes": 3,
"dimension_type": "landscape"
}'Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| story_type | string | Required | Category of story (adventure_story, bible_story, book_story, cinematic_story, comics_story, dream_story, educational_story, fairytale_story, fantasy_story, historical_story, lyric_story, poetry_story, romantic_story, sci_fi_story) |
| input_story | string | Required | The initial user-provided story prompt |
| voice_language | string | Required | Language for narration (english, chinese, spanish, french, german, japanese, korean, portuguese, italian, russian) |
| video_length_minutes | integer | Required | Target video length in minutes. Allowed values: 3, 5, 10, 15, 20, 25, 30 |
| dimension_type | string | Optional | Video dimensions: landscape (16:9) or portrait (9:16). Default: landscape |
| image_illustration_style | string | Optional | Detailed prompt for visual style customization |
| voice_id | string | Optional | Specific voice ID for narration. Default: '8Es4wFxsDlHBmFWAOWRS' |
| enable_subtitle | boolean | Optional | Whether to burn subtitles into the video. Default: false |
| watermark_enabled | boolean | Optional | Whether to apply a user-defined watermark. Default: false |
| watermark_file_id | string | Optional | The asset ID of the watermark file (required if watermark_enabled is true) |
| use_fixed_character | boolean | Optional | Whether to use a consistent character image. Default: false |
| fixed_character_name | string | Optional | The name of the fixed character |
| fixed_character_file_id | string | Optional | The asset ID of the fixed character image |
| temperature | number | Optional | AI generation temperature for creativity (0.0-1.0). Default: 0.1 |
| narrator_name | string | Optional | The name of the narrator character |
| audience_age | string | Optional | Target age group (all, children, adults, teens). Default: all |
| audience_gender | string | Optional | Target gender (all genders, male, female). Default: all genders |
| audience_geo_location | string | Optional | Target geographic location. Default: global |
| user_thematic_purpose | string | Optional | User's thematic goal for the story |
| user_signature_phrases | string | Optional | User's specific catchphrases to include |
| copy_to_email | string | Optional | Email address to send a copy of the result to |
| webhook_endpoint | string | Optional | URL to send a webhook to upon completion |
| callback_id | string | Optional | User-provided identifier for tracking (auto-generated if not provided) |
| mode | string | Optional | Task creation mode: create, repeat, continue, edit. Default: create |
| from_task_id | string | Optional | Source task ID for repeat or continue modes |
| use_templates | boolean | Optional | Whether to apply user templates as defaults. Default: false |
Response Example
{
"success": true,
"data": {
"task": {
"task_id": "task_1634567890123_abc123",
"callback_id": "user-callback-123",
"process_status": "pending",
"story_type": "fairytale_story",
"video_length_minutes": 5,
"video_scene_count": 15,
"dimension_type": "landscape",
"image_dimensions": "1600x900",
"credits_cost": 250,
"created_at": "2024-09-13T10:30:00Z",
"task_created_at": "2024-09-13T10:30:00Z"
}
}
}Important Notes
- Tasks are processed asynchronously - check status regularly
- Credits are held when task is created, deducted when completed successfully
- Failed or cancelled tasks will release held credits automatically
- Task IDs are unique and can be used to track progress
- Use templates (use_templates=true) to apply saved user preferences
- Watermarks and fixed characters require uploaded asset files
Credit Management API
Monitor your credit balance, track usage, and manage credit-related operations. Credits are used to pay for story animation tasks.
Get Credit Balance
curl -H "Authorization: Bearer ag_live_YOUR_API_KEY" \
https://api.animagent.ai/api/v1/credits/balanceGet Credit History
curl -H "Authorization: Bearer ag_live_YOUR_API_KEY" \
"https://api.animagent.ai/api/v1/credits/history?limit=20"Response Example
{
"success": true,
"data": {
"total_balance": 1000,
"available_balance": 750,
"credits_on_hold": 250,
"credits_deficit": 0,
"last_updated": "2024-09-13T10:30:00Z"
}
}Important Notes
- available_balance = total_balance - credits_on_hold
- Credits on hold are reserved for tasks currently being processed
- Credits are deducted from total when tasks complete successfully
- Credits are released back to available if tasks fail or are cancelled
User Assets API
Upload and manage assets like custom watermarks, character avatars, and other media files for use in your animations.
Upload Asset
curl -X POST https://api.animagent.ai/api/v1/assets/upload \
-H "Authorization: Bearer ag_live_YOUR_API_KEY" \
-F "file=@watermark.png" \
-F "asset_type=watermark" \
-F "asset_name=My Company Logo"List Assets
curl -H "Authorization: Bearer ag_live_YOUR_API_KEY" \
"https://api.animagent.ai/api/v1/assets?asset_type=watermark"Delete Asset
curl -X DELETE \
-H "Authorization: Bearer ag_live_YOUR_API_KEY" \
https://api.animagent.ai/api/v1/assets/ASSET_IDParameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| file | file | Required | The asset file to upload (max 2MB for images, 50MB for others) |
| asset_type | string | Required | Type of asset (watermark, character_avatar, background_music, etc.) |
| asset_name | string | Required | Display name for the asset |
Important Notes
- Images are validated for dimensions and file size
- Watermarks and character avatars must be square images
- Total storage limit is 1GB per user
- Supported formats: PNG, JPG, MP3, MP4, etc.
User Templates API
Save and reuse your preferred settings as templates for different story types, making it easy to maintain consistent configurations.
Create Template
curl -X POST https://api.animagent.ai/api/v1/templates \
-H "Authorization: Bearer ag_live_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"template_name": "My Fairytale Template",
"story_type": "fairytale_story",
"voice_language": "english",
"dimension_type": "landscape",
"enable_chapter_transitions": true,
"enable_zoom_effect": true
}'List Templates
curl -H "Authorization: Bearer ag_live_YOUR_API_KEY" \
https://api.animagent.ai/api/v1/templatesUse Template in Task
curl -X POST https://api.animagent.ai/api/v1/tasks \
-H "Authorization: Bearer ag_live_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"input_story": "A new story using my template",
"use_templates": true
}'Important Notes
- Templates can be used by setting use_templates=true in task creation
- User input parameters override template values
- Templates are private to each user account
Webhooks
Receive real-time notifications when your tasks complete or encounter issues. Webhooks are HTTP POST requests sent to your specified URL.
Webhook Payload Example
{
"event": "task_completed",
"timestamp": "2024-09-13T10:45:00Z",
"user_id": "23470f9e-cd9a-495f-a6fa-c8a8434b1cf0",
"task": {
"task_id": "task_1634567890123_abc123",
"code_name": "Magical Forest Adventure",
"tweet_content": "Just created an amazing animated story!",
"story_type": "fairytale_story",
"input_story": "Once upon a time in a magical kingdom...",
"full_story_text": "Chapter 1: The Beginning...",
"credit_cost": 250.0,
"video_length_minutes": 5,
"video_scene_count": 15,
"voice_language": "english",
"dimension_type": "landscape",
"final_video_url": "https://storage.animagent.ai/videos/task_123.mp4",
"final_image_url": "https://storage.animagent.ai/thumbnails/task_123.jpg",
"youtube_video_title": "Magical Forest Adventure",
"youtube_video_description": "An enchanting tale of adventure...",
"youtube_video_hashtags": "#animation #story #fairytale",
"completed_at": "2024-09-13T10:45:00Z"
}
}Express.js Webhook Handler
app.post('/webhook/animagent', (req, res) => {
const { event, timestamp, user_id, task } = req.body;
if (event === 'task_completed') {
console.log(`Task ${task.task_id} completed!`);
console.log(`Video URL: ${task.final_video_url}`);
console.log(`Credits used: ${task.credit_cost}`);
// Handle completion logic here
}
res.status(200).send('OK');
});Important Notes
- Webhooks are sent as HTTP POST requests
- Your endpoint should respond with 200 status code
- Failed webhooks will be retried up to 3 times
- Webhooks include authentication headers for verification
Error Handling
The API uses standard HTTP status codes and returns detailed error information to help you debug issues.
Response Example
{
"success": false,
"error": {
"code": "INSUFFICIENT_CREDITS",
"message": "Insufficient credits to create task. Required: 250, Available: 100",
"details": {
"required_credits": 250,
"available_credits": 100,
"credits_needed": 150
}
}
}HTTP Status Codes
| Status Code | Meaning | Description |
|---|---|---|
| 200 | OK | Request successful |
| 400 | Bad Request | Invalid request parameters |
| 401 | Unauthorized | Invalid or missing API key |
| 402 | Payment Required | Insufficient credits |
| 404 | Not Found | Resource not found |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server error |
Code Examples
Complete examples showing how to integrate the Animagent.ai API into different programming languages and frameworks.
Python Example
import requests
import time
API_KEY = "ag_live_YOUR_API_KEY"
BASE_URL = "https://api.animagent.ai/api/v1"
def create_animation(story, language="english"):
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"story_type": "fairytale_story",
"input_story": story,
"voice_language": language,
"video_length_minutes": 5
}
# Create task
response = requests.post(f"{BASE_URL}/tasks", json=payload, headers=headers)
task_data = response.json()
if not task_data["success"]:
raise Exception(f"Failed to create task: {task_data['error']}")
task_id = task_data["data"]["task"]["task_id"]
print(f"Task created: {task_id}")
# Poll for completion
while True:
response = requests.get(f"{BASE_URL}/tasks/{task_id}", headers=headers)
task_info = response.json()
status = task_info["data"]["task"]["process_status"]
print(f"Status: {status}")
if status == "completed":
video_url = task_info["data"]["task"]["final_video_url"]
print(f"Video ready: {video_url}")
return video_url
elif status == "failed":
raise Exception("Task failed")
time.sleep(30) # Check every 30 seconds
# Usage
video_url = create_animation("A magical adventure in an enchanted forest")Node.js Example
const axios = require('axios');
const API_KEY = 'ag_live_YOUR_API_KEY';
const BASE_URL = 'https://api.animagent.ai/api/v1';
const client = axios.create({
baseURL: BASE_URL,
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
}
});
async function createAnimation(story, language = 'english') {
try {
// Create task
const taskResponse = await client.post('/tasks', {
story_type: 'fairytale_story',
input_story: story,
voice_language: language,
video_length_minutes: 5
});
const taskId = taskResponse.data.data.task.task_id;
console.log(`Task created: ${taskId}`);
// Poll for completion
while (true) {
const statusResponse = await client.get(`/tasks/${taskId}`);
const status = statusResponse.data.data.task.process_status;
console.log(`Status: ${status}`);
if (status === 'completed') {
return statusResponse.data.data.task.final_video_url;
} else if (status === 'failed') {
throw new Error('Task failed');
}
await new Promise(resolve => setTimeout(resolve, 30000)); // Wait 30 seconds
}
} catch (error) {
console.error('Error:', error.response?.data || error.message);
throw error;
}
}
// Usage
createAnimation('A magical adventure in an enchanted forest')
.then(videoUrl => console.log(`Video ready: ${videoUrl}`))
.catch(error => console.error('Failed:', error));Reference Data
Reference tables and enums for API parameters and response values.
Story Types
| Value | Description |
|---|---|
| adventure_story | Thrilling, action-packed narratives from hero's perspective |
| bible_story | Faithful adaptations of biblical passages |
| book_story | Persuasive stories promoting specific books |
| cinematic_story | Non-linear tales starting at climax with flashbacks |
| comics_story | Recurring character hosts explaining complex topics |
| dream_story | Surreal narratives based on dream fragments |
| educational_story | Learning adventures presented as fascinating puzzles |
| fairytale_story | Gentle, magical tales with positive lessons for children |
| fantasy_story | Epic tales of magic and destiny in immersive worlds |
| historical_story | Deep-dive analyses exploring the 'why' behind events |
| lyric_story | Song lyrics transformed into romantic narratives |
| poetry_story | Poems expanded into cinematic stories |
| romantic_story | Intimate emotional journeys from first-person perspective |
| sci_fi_story | Thought-provoking future scenarios exploring humanity |
Voice Languages
| Value | Description | Region |
|---|---|---|
| english | English (🇺🇸) | US/UK |
| chinese | Chinese (🇨🇳) | China |
| spanish | Spanish (🇪🇸) | Spain/Latin America |
| french | French (🇫🇷) | France |
| german | German (🇩🇪) | Germany |
| japanese | Japanese (🇯🇵) | Japan |
| korean | Korean (🇰🇷) | South Korea |
| portuguese | Portuguese (🇧🇷) | Brazil/Portugal |
| italian | Italian (🇮🇹) | Italy |
| russian | Russian (🇷🇺) | Russia |
Video Length Options
| Value (minutes) | Scene Count | Use Case |
|---|---|---|
| 3 | 10 | Short social media clips |
| 5 | 15 | Standard short stories |
| 10 | 25 | Detailed narratives |
| 15 | 32 | Long-form content |
| 20 | 40 | Extended stories |
| 25 | 47 | Documentary style |
| 30 | 55 | Full-length animations |
Dimension Types
| Value | Aspect Ratio | Use Case |
|---|---|---|
| landscape | 16:9 | YouTube, web videos |
| portrait | 9:16 | TikTok, Instagram Stories |
Task Statuses
| Status | Description |
|---|---|
| pending | Task created, waiting to start |
| story_structure_designed | Story structure completed |
| scene_images_generated | Scene images generated |
| scenes_completed | Individual scenes completed |
| completed | Task fully completed |
| failed | Task failed with error |
| cancelled | Task cancelled by user |