Animagent.ai

Animagent.ai API Documentation

Comprehensive API reference for developers integrating with Animagent.ai's story animation platform

Version: 1.4.0
Base URL: https://api.animagent.ai/api/v1
Last Updated: September 2025

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/balance

JavaScript 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

ParameterTypeRequiredDescription
AuthorizationstringRequiredBearer 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_ID

List 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

ParameterTypeRequiredDescription
story_typestringRequiredCategory 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_storystringRequiredThe initial user-provided story prompt
voice_languagestringRequiredLanguage for narration (english, chinese, spanish, french, german, japanese, korean, portuguese, italian, russian)
video_length_minutesintegerRequiredTarget video length in minutes. Allowed values: 3, 5, 10, 15, 20, 25, 30
dimension_typestringOptionalVideo dimensions: landscape (16:9) or portrait (9:16). Default: landscape
image_illustration_stylestringOptionalDetailed prompt for visual style customization
voice_idstringOptionalSpecific voice ID for narration. Default: '8Es4wFxsDlHBmFWAOWRS'
enable_subtitlebooleanOptionalWhether to burn subtitles into the video. Default: false
watermark_enabledbooleanOptionalWhether to apply a user-defined watermark. Default: false
watermark_file_idstringOptionalThe asset ID of the watermark file (required if watermark_enabled is true)
use_fixed_characterbooleanOptionalWhether to use a consistent character image. Default: false
fixed_character_namestringOptionalThe name of the fixed character
fixed_character_file_idstringOptionalThe asset ID of the fixed character image
temperaturenumberOptionalAI generation temperature for creativity (0.0-1.0). Default: 0.1
narrator_namestringOptionalThe name of the narrator character
audience_agestringOptionalTarget age group (all, children, adults, teens). Default: all
audience_genderstringOptionalTarget gender (all genders, male, female). Default: all genders
audience_geo_locationstringOptionalTarget geographic location. Default: global
user_thematic_purposestringOptionalUser's thematic goal for the story
user_signature_phrasesstringOptionalUser's specific catchphrases to include
copy_to_emailstringOptionalEmail address to send a copy of the result to
webhook_endpointstringOptionalURL to send a webhook to upon completion
callback_idstringOptionalUser-provided identifier for tracking (auto-generated if not provided)
modestringOptionalTask creation mode: create, repeat, continue, edit. Default: create
from_task_idstringOptionalSource task ID for repeat or continue modes
use_templatesbooleanOptionalWhether 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/balance

Get 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_ID

Parameters

ParameterTypeRequiredDescription
filefileRequiredThe asset file to upload (max 2MB for images, 50MB for others)
asset_typestringRequiredType of asset (watermark, character_avatar, background_music, etc.)
asset_namestringRequiredDisplay 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/templates

Use 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 CodeMeaningDescription
200OKRequest successful
400Bad RequestInvalid request parameters
401UnauthorizedInvalid or missing API key
402Payment RequiredInsufficient credits
404Not FoundResource not found
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer 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

ValueDescription
adventure_storyThrilling, action-packed narratives from hero's perspective
bible_storyFaithful adaptations of biblical passages
book_storyPersuasive stories promoting specific books
cinematic_storyNon-linear tales starting at climax with flashbacks
comics_storyRecurring character hosts explaining complex topics
dream_storySurreal narratives based on dream fragments
educational_storyLearning adventures presented as fascinating puzzles
fairytale_storyGentle, magical tales with positive lessons for children
fantasy_storyEpic tales of magic and destiny in immersive worlds
historical_storyDeep-dive analyses exploring the 'why' behind events
lyric_storySong lyrics transformed into romantic narratives
poetry_storyPoems expanded into cinematic stories
romantic_storyIntimate emotional journeys from first-person perspective
sci_fi_storyThought-provoking future scenarios exploring humanity

Voice Languages

ValueDescriptionRegion
englishEnglish (🇺🇸)US/UK
chineseChinese (🇨🇳)China
spanishSpanish (🇪🇸)Spain/Latin America
frenchFrench (🇫🇷)France
germanGerman (🇩🇪)Germany
japaneseJapanese (🇯🇵)Japan
koreanKorean (🇰🇷)South Korea
portuguesePortuguese (🇧🇷)Brazil/Portugal
italianItalian (🇮🇹)Italy
russianRussian (🇷🇺)Russia

Video Length Options

Value (minutes)Scene CountUse Case
310Short social media clips
515Standard short stories
1025Detailed narratives
1532Long-form content
2040Extended stories
2547Documentary style
3055Full-length animations

Dimension Types

ValueAspect RatioUse Case
landscape16:9YouTube, web videos
portrait9:16TikTok, Instagram Stories

Task Statuses

StatusDescription
pendingTask created, waiting to start
story_structure_designedStory structure completed
scene_images_generatedScene images generated
scenes_completedIndividual scenes completed
completedTask fully completed
failedTask failed with error
cancelledTask cancelled by user