DEV Community

Hommy
Hommy

Posted on

[JCAIGC]Get draft file list

GET_DRAFT API Documentation

πŸ“‹ Table of Contents

πŸ”§ API Information

GET /openapi/capcut-mate/v1/get_draft
Enter fullscreen mode Exit fullscreen mode

Function Description

Get draft file list. This interface is used to get all file lists corresponding to a specified draft ID, allowing you to view material files, configuration files, and other information contained in the draft. Typically used for draft content preview, file management, or status checking.

More Documentation

πŸ“– For more detailed documentation and tutorials, please visit: https://docs.jcaigc.cn

Request Parameters

Query Parameters

Parameter Name Type Required Default Description
draft_id string βœ… - Draft ID, length 20-32 characters

Parameter Details

draft_id

  • Type: string
  • Required: Yes
  • Length: 20-32 characters
  • Format: Usually UUID format or similar unique identifier
  • Example: 2f52a63b-8c6a-4417-8b01-1b2a569ccb6c
  • How to get: Usually extracted from draft_url or returned by create_draft interface

draft_id Extraction Method

Extract draft_id from draft_url:

// Example draft_url:
// https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_draft?draft_id=2025092811473036584258"2f52a63b-8c6a-4417-8b01-1b2a569ccb6c"
Enter fullscreen mode Exit fullscreen mode

Response Format

Success Response (200)

{
  "files": [
    "2f52a63b-8c6a-4417-8b01-1b2a569ccb6c.json",
    "video_123456789.mp4",
    "audio_987654321.mp3",
    "image_555666777.jpg",
    "thumbnail_888999000.png"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Response Field Description

Field Name Type Description
files array List of files related to the draft

File Type Description

The returned file list may contain the following types:

File Type Extension Description
Draft configuration file .json Main configuration file of the draft, containing all editing information
Video files .mp4, .avi, .mov Video materials used in the draft
Audio files .mp3, .wav, .aac Audio materials used in the draft
Image files .jpg, .png, .gif Image materials used in the draft
Thumbnail files .png, .jpg Thumbnail files of materials
Temporary files .tmp Temporary files during processing

Error Response (4xx/5xx)

{
  "detail": "Error message description"
}
Enter fullscreen mode Exit fullscreen mode

Usage Examples

cURL Example

1. Basic get draft file list

curl -X GET "https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_draft?draft_id=2f52a63b-8c6a-4417-8b01-1b2a569ccb6c" \
  -H "Content-Type: application/json"
Enter fullscreen mode Exit fullscreen mode

2. Use complete draft_id

curl -X GET "https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_draft?draft_id=7e8f9a0b-1c2d-3e4f-5g6h-7i8j9k0l1m2n" \
  -H "Content-Type: application/json"
Enter fullscreen mode Exit fullscreen mode

JavaScript Example

const getDraft = async (draftId) => {
  const response = await fetch(`/v1/get_draft?draft_id=${draftId}`, {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' }
  });
  return response.json();
};

// Usage example
const draftId = "2f52a63b-8c6a-4417-8b01-1b2a569ccb6c";
const result = await getDraft(draftId);
console.log('Draft file list:', result.files);

// Extract draft_id from draft_url
function extractDraftId(draftUrl) {
  const match = draftUrl.match(/\/([^\/]+)\.json$/);
  return match ? match[1] : null;
}

const draftUrl = "https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_draft?draft_id=2025092811473036584258";
const extractedId = extractDraftId(draftUrl);

if (extractedId) {
  const files = await getDraft(extractedId);
  console.log('File list:', files);
}
Enter fullscreen mode Exit fullscreen mode

Advanced JavaScript Example

class DraftManager {
  constructor(baseUrl = 'https://capcut-mate.jcaigc.cn') {
    this.baseUrl = baseUrl;
  }

  async getDraft(draftId) {
    const response = await fetch(`${this.baseUrl}/v1/get_draft?draft_id=${draftId}`, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    });

    if (!response.ok) {
      throw new Error(`Failed to get draft: ${response.statusText}`);
    }

    return response.json();
  }

  // Extract draft_id from draft_url
  extractDraftId(draftUrl) {
    try {
      const url = new URL(draftUrl);
      const draftIdParam = url.searchParams.get('drafId');
      if (draftIdParam) {
        const match = draftIdParam.match(/\/([^\/]+)\.json$/);
        return match ? match[1] : null;
      }
      return null;
    } catch (error) {
      console.error('URL parsing failed:', error);
      return null;
    }
  }

  // Analyze file types
  analyzeFiles(files) {
    const analysis = {
      total: files.length,
      types: {
        config: [],
        video: [],
        audio: [],
        image: [],
        thumbnail: [],
        other: []
      }
    };

    files.forEach(file => {
      const ext = file.split('.').pop()?.toLowerCase();

      switch (ext) {
        case 'json':
          analysis.types.config.push(file);
          break;
        case 'mp4':
        case 'avi':
        case 'mov':
        case 'mkv':
          analysis.types.video.push(file);
          break;
        case 'mp3':
        case 'wav':
        case 'aac':
        case 'flac':
          analysis.types.audio.push(file);
          break;
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
        case 'bmp':
          if (file.includes('thumbnail')) {
            analysis.types.thumbnail.push(file);
          } else {
            analysis.types.image.push(file);
          }
          break;
        default:
          analysis.types.other.push(file);
      }
    });

    return analysis;
  }

  // Get draft details
  async getDraftDetails(draftUrl) {
    const draftId = this.extractDraftId(draftUrl);
    if (!draftId) {
      throw new Error('Unable to extract draft ID from URL');
    }

    const result = await this.getDraft(draftId);
    const analysis = this.analyzeFiles(result.files);

    return {
      draftId,
      draftUrl,
      files: result.files,
      analysis
    };
  }

  // Batch get multiple draft information
  async getBatchDrafts(draftUrls) {
    const results = {};

    for (const [name, url] of Object.entries(draftUrls)) {
      try {
        const details = await this.getDraftDetails(url);
        results[name] = details;

        // Add delay to avoid too fast requests
        await new Promise(resolve => setTimeout(resolve, 100));
      } catch (error) {
        console.error(`Failed to get draft ${name}:`, error);
        results[name] = { error: error.message };
      }
    }

    return results;
  }

  // Monitor draft file changes
  async monitorDraftChanges(draftId, callback, intervalMs = 5000) {
    let lastFileList = [];

    const checkChanges = async () => {
      try {
        const result = await this.getDraft(draftId);
        const currentFiles = result.files.sort();

        // Check if file list has changed
        if (JSON.stringify(currentFiles) !== JSON.stringify(lastFileList)) {
          const changes = {
            added: currentFiles.filter(f => !lastFileList.includes(f)),
            removed: lastFileList.filter(f => !currentFiles.includes(f)),
            current: currentFiles
          };

          callback(changes);
          lastFileList = currentFiles;
        }
      } catch (error) {
        console.error('Failed to monitor draft changes:', error);
      }
    };

    // Initial check
    await checkChanges();

    // Regular checks
    const interval = setInterval(checkChanges, intervalMs);

    // Return function to stop monitoring
    return () => clearInterval(interval);
  }
}

// Usage example
const draftManager = new DraftManager();

// Get single draft details
const draftUrl = "https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_draft?draft_id=2025092811473036584258";
const details = await draftManager.getDraftDetails(draftUrl);

console.log('Draft details:', {
  id: details.draftId,
  totalFiles: details.analysis.total,
  videoCount: details.analysis.types.video.length,
  audioCount: details.analysis.types.audio.length,
  imageCount: details.analysis.types.image.length
});

// Batch get draft information
const multipleDrafts = {
  "project1": "https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_draft?draft_id=2025092811473036584258",
  "project2": "https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_draft?draft_id=2025092811473036584258"
};

const batchResults = await draftManager.getBatchDrafts(multipleDrafts);
console.log('Batch draft information:', batchResults);

// Monitor draft file changes
const draftId = "2f52a63b-8c6a-4417-8b01-1b2a569ccb6c";
const stopMonitoring = await draftManager.monitorDraftChanges(draftId, (changes) => {
  console.log('Draft files changed:', changes);
  if (changes.added.length > 0) {
    console.log('Added files:', changes.added);
  }
  if (changes.removed.length > 0) {
    console.log('Removed files:', changes.removed);
  }
});

// Stop monitoring after 30 seconds
setTimeout(() => {
  stopMonitoring();
  console.log('Stopped monitoring draft changes');
}, 30000);
Enter fullscreen mode Exit fullscreen mode

Python Example

import requests
import re
import time
import threading
from urllib.parse import urlparse, parse_qs
from typing import Dict, List, Optional, Callable

class DraftManager:
    def __init__(self, base_url: str = "https://api.assets.jcaigc.cn"):
        self.base_url = base_url

    def get_draft(self, draft_id: str) -> Dict:
        """Get draft file list"""
        response = requests.get(
            f'{self.base_url}/openapi/capcut-mate/v1/get_draft',
            params={'draft_id': draft_id},
            headers={'Content-Type': 'application/json'}
        )
        response.raise_for_status()
        return response.json()

    def extract_draft_id(self, draft_url: str) -> Optional[str]:
        """Extract draft_id from draft_url"""
        try:
            parsed_url = urlparse(draft_url)
            query_params = parse_qs(parsed_url.fragment.split('?')[1] if '?' in parsed_url.fragment else '')

            draft_id_param = query_params.get('drafId', [None])[0]
            if draft_id_param:
                match = re.search(r'/([^/]+)\.json$', draft_id_param)
                return match.group(1) if match else None
            return None
        except Exception as e:
            print(f"URL parsing failed: {e}")
            return None

    def analyze_files(self, files: List[str]) -> Dict:
        """Analyze file types"""
        analysis = {
            'total': len(files),
            'types': {
                'config': [],
                'video': [],
                'audio': [],
                'image': [],
                'thumbnail': [],
                'other': []
            }
        }

        for file in files:
            ext = file.split('.')[-1].lower() if '.' in file else ''

            if ext == 'json':
                analysis['types']['config'].append(file)
            elif ext in ['mp4', 'avi', 'mov', 'mkv']:
                analysis['types']['video'].append(file)
            elif ext in ['mp3', 'wav', 'aac', 'flac']:
                analysis['types']['audio'].append(file)
            elif ext in ['jpg', 'jpeg', 'png', 'gif', 'bmp']:
                if 'thumbnail' in file:
                    analysis['types']['thumbnail'].append(file)
                else:
                    analysis['types']['image'].append(file)
            else:
                analysis['types']['other'].append(file)

        return analysis

    def get_draft_details(self, draft_url: str) -> Dict:
        """Get draft details"""
        draft_id = self.extract_draft_id(draft_url)
        if not draft_id:
            raise ValueError('Unable to extract draft ID from URL')

        result = self.get_draft(draft_id)
        analysis = self.analyze_files(result['files'])

        return {
            'draft_id': draft_id,
            'draft_url': draft_url,
            'files': result['files'],
            'analysis': analysis
        }

    def get_batch_drafts(self, draft_urls: Dict[str, str]) -> Dict:
        """Batch get draft information"""
        results = {}

        for name, url in draft_urls.items():
            try:
                details = self.get_draft_details(url)
                results[name] = details
                time.sleep(0.1)  # Avoid too fast requests
            except Exception as e:
                print(f"Failed to get draft {name}: {e}")
                results[name] = {'error': str(e)}

        return results

    def monitor_draft_changes(self, draft_id: str, callback: Callable, interval_seconds: int = 5) -> str:
        """Monitor draft file changes"""
        last_file_list = []
        stop_event = threading.Event()

        def check_changes():
            nonlocal last_file_list
            while not stop_event.is_set():
                try:
                    result = self.get_draft(draft_id)
                    current_files = sorted(result['files'])

                    if current_files != last_file_list:
                        changes = {
                            'added': [f for f in current_files if f not in last_file_list],
                            'removed': [f for f in last_file_list if f not in current_files],
                            'current': current_files
                        }

                        callback(changes)
                        last_file_list = current_files

                except Exception as e:
                    print(f"Failed to monitor draft changes: {e}")

                stop_event.wait(interval_seconds)

        # Initial check
        try:
            result = self.get_draft(draft_id)
            last_file_list = sorted(result['files'])
        except Exception as e:
            print(f"Initial check failed: {e}")

        # Start monitoring thread
        thread = threading.Thread(target=check_changes, daemon=True)
        thread.start()

        # Return stop function
        def stop_monitoring():
            stop_event.set()
            thread.join(timeout=1)

        return stop_monitoring

# Usage example
manager = DraftManager()

# Get single draft
draft_url = "https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_draft?draft_id=2025092811473036584258"
details = manager.get_draft_details(draft_url)

print(f"Draft ID: {details['draft_id']}")
print(f"Total files: {details['analysis']['total']}")
print(f"Video files: {len(details['analysis']['types']['video'])} files")
print(f"Audio files: {len(details['analysis']['types']['audio'])} files")
print(f"Image files: {len(details['analysis']['types']['image'])} files")

# Batch get drafts
multiple_drafts = {
    "project1": "https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_draft?draft_id=2025092811473036584258",
    "project2": "https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_draft?draft_id=2025092811473036584258"
}

batch_results = manager.get_batch_drafts(multiple_drafts)
for name, result in batch_results.items():
    if 'error' not in result:
        print(f"{name}: {result['analysis']['total']} files")

# Monitor draft changes
def on_change(changes):
    print(f"Draft files changed:")
    if changes['added']:
        print(f"Added: {changes['added']}")
    if changes['removed']:
        print(f"Removed: {changes['removed']}")

draft_id = "2f52a63b-8c6a-4417-8b01-1b2a569ccb6c"
stop_monitoring = manager.monitor_draft_changes(draft_id, on_change)

# Stop monitoring after 30 seconds
time.sleep(30)
stop_monitoring()
print("Stopped monitoring")
Enter fullscreen mode Exit fullscreen mode

Error Code Description

Error Code Error Message Description Solution
400 draft_id is required Missing draft_id parameter Provide valid draft_id
400 draft_id length is invalid draft_id length not in 20-32 character range Check if draft_id format is correct
400 draft_id format is invalid draft_id format is incorrect Ensure using correct draft ID format
404 Draft does not exist Specified draft ID cannot be found Confirm draft ID is correct and exists
500 Failed to get file list Internal service error Contact technical support or retry later
503 Service unavailable System under maintenance Retry later

Notes

  1. Parameter format: Ensure draft_id format is correct and length is between 20-32 characters
  2. ID extraction: Correctly extract draft_id from draft_url
  3. File types: The returned file list contains multiple types of files
  4. Permission verification: Ensure you have permission to access the specified draft
  5. Real-time: File list may not be updated in real-time, there may be some delay
  6. File status: Files in the list may be in different processing states

Workflow

  1. Validate draft_id parameter
  2. Check draft_id format and length
  3. Find specified draft
  4. Get all files associated with the draft
  5. Return file list

Best Practices

  1. ID validation: Validate draft_id validity before calling
  2. Error handling: Properly handle cases where draft does not exist
  3. File analysis: Classify and analyze the returned file list
  4. Caching strategy: Consider appropriate caching for frequently queried drafts
  5. Change monitoring: Implement change monitoring for scenarios requiring real-time updates

Related APIs


πŸ“š Project Resources

GitHub: https://github.com/Hommy-master/capcut-mate

Gitee: https://gitee.com/taohongmin-gitee/capcut-mate

Top comments (0)