### GET /templates Source: https://platform.zapcap.ai/docs/api Retrieves a list of all available templates. ```APIDOC ## GET /templates ### Description Retrieve the list of available templates including id, name, allowlisted categories, and preview URLs. Use the selected template id in the Create Task endpoint. ### Method GET ### Endpoint /templates ### Response #### Success Response (200) - **id** (string) - The ID of the template. - **categories** (array of strings) - List of categories the template belongs to. - **previewUrl** (string) - URL for a preview of the template. - **previews** (object) - Object containing different preview formats. ### Request Example ```curl curl --request GET \ --url https://api.zapcap.ai/templates \ --header 'X-Api-Key: YOUR_TOKEN' ``` ### Response Example ```json [ { "id": "a51c5222-47a7-4c37-b052-7b9853d66bf6", "categories": [ "animated", "highlighted", "basic" ], "previewUrl": "https://cdn.zapcap.ai/templates/7b946549-ae16-4085-9dd3-c20c82504daa.mp4", "previews": { "previewMp4": "…", "previewGif": "…" } } ] ``` ### Notes 1. Choose the template `id` from the response you wish to add to your video. 2. Supply the chosen `id` in the `templateId` field of the Create Task endpoint. ``` -------------------------------- ### Create Video Task with Auto Cut Settings Source: https://platform.zapcap.ai/docs/guides/captions-configuration Example request for applying silence removal to a video task. ```http POST /videos/{videoId}/task Content-Type: application/json x-api-key: YOUR_API_KEY { "templateId": "a51c5222-47a7-4c37-b052-7b9853d66bf6", "autoApprove": true, "language": "en", "autoCutSettings": { "silenceRemoval": 0.4, } } ``` -------------------------------- ### Webhook Notification Setup Source: https://platform.zapcap.ai/docs/guides/webhooks Configure webhook notifications when creating a video task by including a `notification` object in your request. ```APIDOC ## POST /api/video/tasks ### Description Creates a new video task and optionally configures webhook notifications for status updates. ### Method POST ### Endpoint /api/video/tasks ### Parameters #### Request Body - **notification** (object) - Optional - An object to configure webhook notifications. - **type** (string) - Required - Must be "webhook". - **notificationsFor** (array of strings) - Required - Specifies the events to receive notifications for. Possible values: `"transcript"`, `"render"`, `"renderProgress"`. - **recipient** (string) - Required - The URL endpoint where ZapCap will send webhook notifications. ``` -------------------------------- ### Create Video Task with Custom Render Options Source: https://platform.zapcap.ai/docs/guides/captions-configuration Example request to create a video task with detailed customization of subtitle rendering, including emoji settings, text animation, font styles, and keyword highlight colors. ```json POST /videos/{videoId}/task Content-Type: application/json x-api-key: YOUR_API_KEY { "templateId": "a51c5222-47a7-4c37-b052-7b9853d66bf6", "autoApprove": false, "language": "en", "renderOptions": { "subsOptions": { "emoji": true, "emojiAnimation": true, "emphasizeKeywords": true, "animation": true, "punctuation": false, "displayWords": 6 }, "styleOptions": { "top": 40, "fontUppercase": true, "fontSize": 46, "fontWeight": 900, "fontColor": "#ffffff", "fontShadow": "l", "stroke": "s", "strokeColor": "#000000" }, "highlightOptions": { "randomColourOne": "#2bf82a", "randomColourTwo": "#fdfa14", "randomColourThree": "#f01916" } } } ``` -------------------------------- ### Get List of All Templates (cURL) Source: https://platform.zapcap.ai/docs/api Retrieve a list of available video templates. Use the template ID from the response in the Create Task endpoint. ```curl curl --request GET \ --url https://api.zapcap.ai/templates \ --header 'X-Api-Key: YOUR_TOKEN' ``` -------------------------------- ### Create Video Task with Custom B-rolls Source: https://platform.zapcap.ai/docs/guides/captions-configuration Example request for adding specific b-roll clips to a video task. ```http POST /videos/{videoId}/task Content-Type: application/json x-api-key: YOUR_API_KEY { "templateId": "a51c5222-47a7-4c37-b052-7b9853d66bf6", "autoApprove": true, "language": "en", "transcribeSettings": { "broll": { "customBrolls": [ { "startTime": 5, "endTime": 15, "url": "https://example.com/intro-broll.mp4" }, { "startTime": 25, "endTime": 35, "url": "https://example.com/product-demo.mp4" } ] } } } ``` -------------------------------- ### Task Status Response Source: https://platform.zapcap.ai/docs/quickstart Example response showing the status of a video processing task. 'completed' status indicates that transcript and download URLs are available. ```json { "status": "completed", // or "pending", "transcribing", etc. "id": "54abe67d-be14-4c78-800b-01d12bcfaaa6", "transcript": "https://download-url-for-transcript", "downloadUrl": "https://download-url-for-video" // ... other fields } ``` -------------------------------- ### GET /videos/{videoId}/clipTask/{id} Source: https://platform.zapcap.ai/docs/api Retrieves details about a video clip task. ```APIDOC ## GET /videos/{videoId}/clipTask/{id} ### Description Retrieves details about a specific video clip task. ### Method GET ### Endpoint /videos/{videoId}/clipTask/{id} ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video. - **id** (string) - Required - The ID of the clip task. ``` -------------------------------- ### GET /fonts Source: https://platform.zapcap.ai/docs/api Retrieves a list of available fonts. ```APIDOC ## GET /fonts ### Description Retrieves a list of all available fonts, including custom and default fonts. ### Method GET ### Endpoint /fonts ``` -------------------------------- ### GET /videos/{videoId}/task/{id}/transcript Source: https://platform.zapcap.ai/docs/api Retrieves the transcript for a video task. ```APIDOC ## GET /videos/{videoId}/task/{id}/transcript ### Description Retrieves the generated transcript for a specific video task. ### Method GET ### Endpoint /videos/{videoId}/task/{id}/transcript ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video. - **id** (string) - Required - The ID of the task. ``` -------------------------------- ### GET /videos/{videoId}/task/{id} Source: https://platform.zapcap.ai/docs/api Retrieves the status and details of a video processing task. ```APIDOC ## GET /videos/{videoId}/task/{id} ### Description Retrieves the status and details of a specific video processing task. ### Method GET ### Endpoint /videos/{videoId}/task/{id} ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video. - **id** (string) - Required - The ID of the task. ``` -------------------------------- ### Get Video Clip Task Response Body Source: https://platform.zapcap.ai/docs/guides/clipping-tasks Response detailing the status and results of a clipping task, including clip URLs and themes, or an error message if the task failed. ```json { "id": string; "status": VideoClipTaskStatus; "clips": ClipResponse[]; "error": string; } ``` -------------------------------- ### GET /fonts/{id} Source: https://platform.zapcap.ai/docs/api Retrieves details of a specific font. ```APIDOC ## GET /fonts/{id} ### Description Retrieves detailed information about a specific font by its ID. ### Method GET ### Endpoint /fonts/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the font to retrieve. ``` -------------------------------- ### Add Animated Subtitles via CLI Source: https://platform.zapcap.ai/docs Upload a video file and initiate a captioning task using curl and jq. ```bash # First, upload the video and get the ID VIDEO_ID=$(curl -X POST "https://api.zapcap.ai/videos" \ -H "x-api-key: YOUR_API_KEY" \ -F "file=@video.mp4" | jq -r .id) # Then create the task using the video ID curl -X POST "https://api.zapcap.ai/videos/$VIDEO_ID/task" \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "templateId": "template_id", "autoApprove": true }' ``` -------------------------------- ### Configure Subtitle Templates Source: https://platform.zapcap.ai/docs Define rendering and styling options for subtitle generation. ```json // Customize templates programmatically { "renderOptions": { "subsOptions": { "emoji": true, "animation": true, "emphasizeKeywords": true }, "styleOptions": { "fontSize": 46, "fontColor": "#ffffff" } } } ``` -------------------------------- ### POST /videos/upload Source: https://platform.zapcap.ai/docs/api Initiates a video upload process. ```APIDOC ## POST /videos/upload ### Description Initiates a video upload process. This endpoint is typically followed by subsequent calls to upload video chunks. ### Method POST ### Endpoint /videos/upload ``` -------------------------------- ### Add Captions to Video using Bash Source: https://platform.zapcap.ai/docs/examples/caption-a-video This Bash script automates video captioning with the Zapcap AI API. It uses `curl` for API requests and `jq` for JSON parsing to fetch templates, upload videos, create tasks, and download results. ```bash #!/bin/bash # Get this from https://platform.zapcap.ai/dashboard/api-key API_KEY="YOUR_API_KEY" API_BASE="https://api.zapcap.ai" VIDEO_PATH="/path/to/your/video.mp4" check_status() { local video_id=$1 local task_id=$2 local attempt=0 while true; do echo "Checking status..." response=$(curl -s -H "x-api-key: $API_KEY" \ "$API_BASE/videos/$video_id/task/$task_id") status=$(echo $response | jq -r '.status') echo "Status: $status" if [ "$status" = "completed" ]; then download_url=$(echo $response | jq -r '.downloadUrl') echo "Downloading captioned video..." curl -o captioned_video.mp4 "$download_url" echo "Video saved to: captioned_video.mp4" break elif [ "$status" = "failed" ]; then error=$(echo $response | jq -r '.error') echo "Task failed: $error" exit 1 fi delay=2 sleep $delay ((attempt++)) done } # 1. Get available templates echo "Fetching templates..." templates_response=$(curl -s -H "x-api-key: $API_KEY" "$API_BASE/templates") TEMPLATE_ID=$(echo $templates_response | jq -r '.[0].id') echo "Using template: $TEMPLATE_ID" # 2. Upload video echo "Uploading video..." upload_response=$(curl -s -X POST "$API_BASE/videos" \ -H "x-api-key: $API_KEY" \ -F "file=@$VIDEO_PATH") video_id=$(echo $upload_response | jq -r '.id') echo "Video uploaded, ID: $video_id" # 3. Create task echo "Creating captioning task..." task_response=$(curl -s -X POST "$API_BASE/videos/$video_id/task" \ -H "x-api-key: $API_KEY" \ -H "Content-Type: application/json" \ -d "{ \"templateId\": \"$TEMPLATE_ID\", \"autoApprove\": true, \"language\": \"en\" }") task_id=$(echo $task_response | jq -r '.taskId') echo "Task created, ID: $task_id" ``` -------------------------------- ### POST /videos/upload/complete Source: https://platform.zapcap.ai/docs/api Completes the video upload process. ```APIDOC ## POST /videos/upload/complete ### Description Marks the video upload as complete after all chunks have been sent. ### Method POST ### Endpoint /videos/upload/complete ``` -------------------------------- ### Create Clipping Task Source: https://platform.zapcap.ai/docs/guides/clipping-tasks Initiates a task to generate viral short clips from a specified video. Requires video ID in the path and a JSON body specifying clip generation parameters. ```APIDOC ## POST /videos/{videoId}/clipTask ### Description Creates a clipping task to generate viral short clips from a long-form video. The task analyzes the video and extracts engaging segments based on the provided criteria. ### Method POST ### Endpoint /videos/{videoId}/clipTask ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video from which to generate clips. #### Request Body - **maxClips** (number) - Required - The maximum number of clips to generate (1-5). The actual number may be less. - **durationRange** (string) - Required - The desired duration range for the clips. Options: `lt_30s`, `gte_30s_lt_60s`, `gte_60s_lt_90s`, `gte_90s_lt_180s`. ### Request Example ```json { "maxClips": 3, "durationRange": "lt_30s" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created clipping task. This ID is used to monitor the task's status. #### Response Example ```json { "id": "clp_abc123xyz789" } ``` ``` -------------------------------- ### Define Export Settings Source: https://platform.zapcap.ai/docs/guides/advanced Configure output quality, frame rate, and processing speed using the exportSettings object. ```json { "templateId": "a51c5222-47a7-4c37-b052-7b9853d66bf6", "autoApprove": true, "exportSettings": { "fps": 60, "quality": "quadHD", "speed": "fast" } } ``` -------------------------------- ### Create Video Task with Advanced Options Source: https://platform.zapcap.ai/docs/guides/advanced Use this endpoint to create a video processing task. Specify transcription, translation, custom dictionaries, and export settings for detailed video analysis and output. ```http POST /videos/{videoId}/task Content-Type: application/json x-api-key: YOUR_API_KEY { "templateId": "a51c5222-47a7-4c37-b052-7b9853d66bf6", "autoApprove": true, "language": "en", "translateTo": "es", "dictionary": ["ZapCap", "API"], "exportSettings": { "fps": 60, "quality": "quadHD", "speed": "fast" } } ``` -------------------------------- ### POST /videos/{videoId}/task Source: https://platform.zapcap.ai/docs/api Creates a task for processing a video. ```APIDOC ## POST /videos/{videoId}/task ### Description Creates a task for processing a video, such as subtitle generation. ### Method POST ### Endpoint /videos/{videoId}/task ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video to create a task for. ### Request Body - **templateId** (string) - Required - The ID of the template to use for the task. ``` -------------------------------- ### POST /videos Source: https://platform.zapcap.ai/docs/guides/uploading-videos Directly uploads a video file from a local machine or server using multipart/form-data. ```APIDOC ## POST /videos ### Description Allows you to directly upload a video file from your local machine or server. ### Method POST ### Endpoint /videos ### Request Body - **file** (binary) - Required - The video file to upload as form-data. ``` -------------------------------- ### POST /videos/upload Source: https://platform.zapcap.ai/docs/guides/uploading-videos Initiates a multipart upload session for large files. ```APIDOC ## POST /videos/upload ### Description Initiates a multipart upload session for large files. ### Method POST ### Endpoint /videos/upload ### Request Body - **uploadParts** (array) - Required - List of parts with their content lengths. - **filename** (string) - Required - The name of the file being uploaded. ### Response - **uploadId** (string) - The ID of the upload session. - **videoId** (string) - The ID of the video. - **presignedUrls** (array) - URLs for uploading each part. ``` -------------------------------- ### Create Video Task - cURL Source: https://platform.zapcap.ai/docs/quickstart Initiate a video processing task using the video ID and a chosen template ID. Set 'autoApprove' to true to skip manual transcript approval. ```curl curl -X POST "https://api.zapcap.ai/videos/YOUR_VIDEO_ID/task" \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "templateId": "YOUR_TEMPLATE_ID", "autoApprove": true, "language": "en" }' ``` -------------------------------- ### POST /videos/{videoId}/clipTask Source: https://platform.zapcap.ai/docs/api Creates a video clip task. ```APIDOC ## POST /videos/{videoId}/clipTask ### Description Creates a task to generate a video clip based on specified parameters. ### Method POST ### Endpoint /videos/{videoId}/clipTask ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video to create a clip from. ``` -------------------------------- ### POST /videos/url Source: https://platform.zapcap.ai/docs/api Uploads a video from a URL to be processed. ```APIDOC ## POST /videos/url ### Description Uploads a video from a URL to be processed. ### Method POST ### Endpoint /videos/url ### Request Body - **url** (string) - Required - The URL of the video to upload. ### Request Example { "url": "http://example.com/video.mp4" } ### Response #### Success Response (200) - **id** (string) - The ID of the created video. - **status** (string enum) - The status of the video upload. Possible values: todo, uploaded, inProgress, aborted. - **storageId** (string) - The storage ID of the video. #### Response Example { "id": "cd97a23f-6c6d-4af7-ad66-b04ed4bb1c5e", "status": "uploaded", "storageId": "some_storage_id" } ``` -------------------------------- ### POST /videos/{videoId}/task Source: https://platform.zapcap.ai/docs/guides/captions-configuration Creates a new video task with custom transcription settings, including b-roll configuration. ```APIDOC ## POST /videos/{videoId}/task ### Description Creates a video task with custom b-roll settings to enhance video content. ### Method POST ### Endpoint /videos/{videoId}/task ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video to process. #### Request Body - **templateId** (string) - Required - The ID of the template to use. - **autoApprove** (boolean) - Optional - Whether to auto-approve the task. - **language** (string) - Optional - The language of the video. - **transcribeSettings** (object) - Optional - Configuration for transcription. - **broll** (object) - Optional - B-roll settings. - **brollPercent** (number) - Optional - Percentage of b-roll (0-100). - **customBrolls** (array) - Optional - List of custom b-roll objects. - **startTime** (number) - Required - Start time in seconds. - **endTime** (number) - Required - End time in seconds. - **url** (string) - Required - Publicly accessible URL of the b-roll video. ### Request Example { "templateId": "a51c5222-47a7-4c37-b052-7b9853d66bf6", "autoApprove": true, "language": "en", "transcribeSettings": { "broll": { "customBrolls": [ { "startTime": 5, "endTime": 15, "url": "https://example.com/intro-broll.mp4" } ] } } } ``` -------------------------------- ### Create Video Clip Task Request Body Source: https://platform.zapcap.ai/docs/guides/clipping-tasks Define the parameters for generating short clips, including the maximum number of clips and the desired duration range. ```json { "maxClips": number; "durationRange": ClipDurationRange; } ``` -------------------------------- ### Perform Multipart Upload in Python Source: https://platform.zapcap.ai/docs/guides/uploading-videos Uses the requests library to handle multipart file uploads in 10MB chunks. ```python import requests import os import math API_KEY = 'YOUR_API_KEY' API_BASE = 'https://api.zapcap.ai' CHUNK_SIZE = 10 * 1024 * 1024 # 10MB per part def multipart_upload(file_path): file_size = os.path.getsize(file_path) num_parts = math.ceil(file_size / CHUNK_SIZE) # 1. Calculate part sizes upload_parts = [] for i in range(num_parts): start = i * CHUNK_SIZE end = min(start + CHUNK_SIZE, file_size) upload_parts.append({'contentLength': end - start}) # 2. Initialize multipart upload print(f'Initializing upload with {num_parts} parts...') init_response = requests.post( f'{API_BASE}/videos/upload', headers={'x-api-key': API_KEY}, json={ 'uploadParts': upload_parts, 'filename': os.path.basename(file_path) } ) init_response.raise_for_status() data = init_response.json() upload_id = data['uploadId'] video_id = data['videoId'] parts = data['parts'] print(f'Upload initialized, videoId: {video_id}') # 3. Upload each part using presigned URLs with open(file_path, 'rb') as f: for i, part in enumerate(parts): chunk = f.read(CHUNK_SIZE) print(f'Uploading part {i + 1}/{num_parts}...') response = requests.put( part['presignedUrl'], data=chunk, headers={'Content-Length': str(len(chunk))} ) response.raise_for_status() # 4. Complete the upload print('Completing upload...') complete_response = requests.post( f'{API_BASE}/videos/upload/complete', headers={'x-api-key': API_KEY}, json={'uploadId': upload_id, 'videoId': video_id} ) complete_response.raise_for_status() print(f'Upload complete! Video ID: {video_id}') return video_id multipart_upload('/path/to/large-video.mp4') ``` -------------------------------- ### Video Upload Response Source: https://platform.zapcap.ai/docs/quickstart This is a sample response after successfully uploading a video. Save the 'id' for subsequent API calls. ```json { "status": "uploaded", "id": "cd97a23f-6c6d-4af7-ad66-b04ed4bb1c5e", "storageId": "storage-123" } ``` -------------------------------- ### POST /videos/{videoId}/task (Auto Cut) Source: https://platform.zapcap.ai/docs/guides/captions-configuration Creates a video task with auto-cut settings to remove silences from the video. ```APIDOC ## POST /videos/{videoId}/task ### Description Creates a video task with auto-cut settings to remove silences and create tighter content. ### Method POST ### Endpoint /videos/{videoId}/task ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video to process. #### Request Body - **templateId** (string) - Required - The ID of the template to use. - **autoCutSettings** (object) - Optional - Configuration for auto-cutting. - **silenceRemoval** (number) - Optional - Aggressiveness of silence removal (0 to 1). ### Request Example { "templateId": "a51c5222-47a7-4c37-b052-7b9853d66bf6", "autoCutSettings": { "silenceRemoval": 0.4 } } ``` -------------------------------- ### POST /videos/{videoId}/task - Create Video Task with Custom Render Options Source: https://platform.zapcap.ai/docs/guides/captions-configuration This endpoint allows you to create a video task with detailed customization of subtitle rendering. You can control emoji display, keyword emphasis, animations, punctuation, font styles, colors, and highlight colors. ```APIDOC ## POST /videos/{videoId}/task ### Description Creates a video task with custom subtitle rendering options. ### Method POST ### Endpoint /videos/{videoId}/task ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video to create a task for. #### Query Parameters None #### Request Body - **templateId** (string) - Required - The ID of the template to use for subtitle generation. - **autoApprove** (boolean) - Optional - Whether to automatically approve the generated subtitles. - **language** (string) - Required - The language of the subtitles. - **renderOptions** (object) - Optional - An object containing various rendering and styling options for the subtitles. - **subsOptions** (object) - Optional - Options related to subtitle content and behavior. - **emoji** (boolean) - Optional - Enables or disables emojis in the subtitles. - **emojiAnimation** (boolean) - Optional - Enables or disables animation for emojis. - **emphasizeKeywords** (boolean) - Optional - Highlights important keywords. - **animation** (boolean) - Optional - Toggles animation for the subtitles. - **punctuation** (boolean) - Optional - Determines whether punctuation should be added. - **displayWords** (number) - Optional - Guidance for the number of words to display per subtitle line. - **styleOptions** (object) - Optional - Options related to subtitle styling. - **top** (number) - Optional - The Y position of the subtitles as a percentage of video height. - **fontUppercase** (boolean) - Optional - Converts subtitle text to uppercase. - **fontSize** (number) - Optional - Specifies the font size of the subtitles. - **fontWeight** (number) - Optional - Specifies the font weight of the subtitles. - **fontColor** (string) - Optional - Sets the base color of the subtitles using a hex color code. - **fontShadow** (string) - Optional - Sets the shadow size of the subtitles ('none', 's', 'm', 'l'). - **stroke** (string) - Optional - Sets the stroke size of the subtitles ('none', 's', 'm', 'l'). - **strokeColor** (string) - Optional - Sets the stroke color of the subtitles using a hex color code. - **highlightOptions** (object) - Optional - Options related to keyword highlighting colors. - **randomColourOne** (string) - Optional - First random color option for highlighted keywords. - **randomColourTwo** (string) - Optional - Second random color option for highlighted keywords. - **randomColourThree** (string) - Optional - Third random color option for highlighted keywords. ### Request Example ```json { "templateId": "a51c5222-47a7-4c37-b052-7b9853d66bf6", "autoApprove": false, "language": "en", "renderOptions": { "subsOptions": { "emoji": true, "emojiAnimation": true, "emphasizeKeywords": true, "animation": true, "punctuation": false, "displayWords": 6 }, "styleOptions": { "top": 40, "fontUppercase": true, "fontSize": 46, "fontWeight": 900, "fontColor": "#ffffff", "fontShadow": "l", "stroke": "s", "strokeColor": "#000000" }, "highlightOptions": { "randomColourOne": "#2bf82a", "randomColourTwo": "#fdfa14", "randomColourThree": "#f01916" } } } ``` ### Response #### Success Response (200) - **taskId** (string) - The ID of the created task. - **status** (string) - The status of the created task. #### Response Example ```json { "taskId": "task_12345abcde", "status": "processing" } ``` ``` -------------------------------- ### Configure Auto Cut Settings Source: https://platform.zapcap.ai/docs/guides/captions-configuration Defines the structure for silence removal settings. ```yaml templateId: "a51c5222-47a7-4c37-b052-7b9853d66bf6", autoCutSettings: silenceRemoval: 0.3 ``` -------------------------------- ### Create Backend API Route for Subtitles Source: https://platform.zapcap.ai/docs Expose a secure endpoint to trigger subtitle generation without exposing API keys to the client. ```javascript // Server-side API route - never expose API keys to the client app.post("/api/add-subtitles", async (req, res) => { const { videoId, templateId } = req.body; const response = await fetch(`https://api.zapcap.ai/videos/${videoId}/task`, { method: "POST", headers: { "x-api-key": process.env.ZAPCAP_API_KEY, "Content-Type": "application/json", }, body: JSON.stringify({ templateId, autoApprove: true }), }); res.json(await response.json()); }); ``` -------------------------------- ### Create Task Response Source: https://platform.zapcap.ai/docs/quickstart Response after creating a video processing task. The 'taskId' is returned for monitoring the task's progress. ```json { "taskId": "54abe67d-be14-4c78-800b-01d12bcfaaa6" } ``` -------------------------------- ### Implement Express.js Webhook Handler Source: https://platform.zapcap.ai/docs/guides/webhooks A complete Express.js server implementation featuring HMAC signature verification, idempotency checks, and asynchronous event processing. ```javascript import express from "express"; import crypto from "crypto"; const app = express(); // Get this from https://platform.zapcap.ai/dashboard/api-key const WEBHOOK_SECRET = "your_webhook_secret"; // Store processed event IDs to prevent duplicate processing const processedEvents = new Set(); app.post("/webhook/zapcap", express.json(), (req, res) => { const payload = req.body; const receivedSignature = req.headers["x-signature"]; // 1. Verify signature const generatedSignature = crypto .createHmac("sha256", WEBHOOK_SECRET) .update(JSON.stringify(payload)) .digest("hex"); if (generatedSignature !== receivedSignature) { console.error("Invalid webhook signature"); return res.status(401).json({ error: "Invalid signature" }); } // 2. Check for duplicate events (idempotency) if (processedEvents.has(payload.eventId)) { return res.status(200).json({ message: "Already processed" }); } // 3. Acknowledge immediately, process async res.status(200).json({ received: true }); // 4. Process the webhook asynchronously processWebhook(payload); }); async function processWebhook(payload) { try { processedEvents.add(payload.eventId); switch (payload.notificationFor) { case "transcript": if (payload.event === "transcriptionCompleted") { console.log("Transcript ready:", payload.transcriptUrl); // Download and process transcript... } else if (payload.event === "failed") { console.error("Transcription failed for task:", payload.taskId); } break; case "render": if (payload.event === "completed") { console.log("Video ready:", payload.renderUrl); // Download and store the video... } else if (payload.event === "failed") { console.error("Render failed for task:", payload.taskId); } break; case "renderProgress": console.log(`Render progress: ${Math.round(payload.progress * 100)}%`); break; } } catch (error) { console.error("Error processing webhook:", error); } } app.listen(3000, () => console.log("Webhook server running on port 3000")); ``` -------------------------------- ### Add Captions to Video using Node.js Source: https://platform.zapcap.ai/docs/examples/caption-a-video This Node.js script demonstrates how to add captions to a video using the ZapCap API. It requires an API key and the path to the video file. The script handles template fetching, video upload, task creation, polling for completion, and downloading the captioned video. ```javascript import axios, { isAxiosError } from "axios"; import { createReadStream, createWriteStream } from "fs"; import FormData from "form-data"; // Get this from https://platform.zapcap.ai/dashboard/api-key const API_KEY = "YOUR_API_KEY"; const API_BASE = "https://api.zapcap.ai"; const VIDEO_PATH = "/path/to/your/video.mp4"; export async function addCaptions(videoPath) { try { // 1. Get available templates console.log("Fetching templates..."); const templatesResponse = await axios.get(`${API_BASE}/templates`, { headers: { "x-api-key": API_KEY }, }); const templateId = templatesResponse.data[0].id; console.log("Using template:", templateId); // 2. Upload video console.log("Uploading video..."); const form = new FormData(); form.append("file", createReadStream(videoPath)); const uploadResponse = await axios.post(`${API_BASE}/videos`, form, { headers: { "x-api-key": API_KEY, }, }); const videoId = uploadResponse.data.id; console.log("Video uploaded, Video ID:", videoId); // 3. Create task console.log("Creating captioning task..."); const taskResponse = await axios.post( `${API_BASE}/videos/${videoId}/task`, { templateId, // Read about it here: https://platform.zapcap.ai/docs/guides/tasks#-transcript-approval autoApprove: true, language: "en", }, { headers: { "x-api-key": API_KEY, "Content-Type": "application/json", }, } ); const taskId = taskResponse.data.taskId; console.log("Task created, Task ID:", taskId); // 4. Poll for completion console.log("Processing video..."); let attempts = 0; while (true) { const statusResponse = await axios.get( `${API_BASE}/videos/${videoId}/task/${taskId}`, { headers: { "x-api-key": API_KEY }, } ); const { status, downloadUrl, error } = statusResponse.data; console.log("Status:", status); if (status === "completed") { // Download the video console.log("Downloading captioned video..."); const videoResponse = await axios.get(downloadUrl, { responseType: "stream", }); const outputPath = "./captioned_video.mp4"; await new Promise((resolve, reject) => { const writeStream = createWriteStream(outputPath); videoResponse.data.pipe(writeStream); writeStream.on("finish", () => { console.log("Video saved to:", outputPath); resolve(); }); writeStream.on("error", reject); }); console.log("Video saved to:", outputPath); break; } else if (status === "failed") { throw new Error(`Task failed: ${error}`); } const delay = 2000; await new Promise((resolve) => setTimeout(resolve, delay)); attempts++; } } catch (error) { if (isAxiosError(error)) { console.log(error.response?.data); } console.error("Error:", error.message); } } const main = async () => { await addCaptions(VIDEO_PATH); }; main().then(() => process.exit(0)); ``` -------------------------------- ### Upload Video by URL Source: https://platform.zapcap.ai/docs/guides/uploading-videos Uploads a video using its existing URL. This method is suitable for videos hosted online or medium-sized files. ```APIDOC ## POST /videos/url ### Description Uploads a video by providing its URL. ### Method POST ### Endpoint /videos/url ### Request Body - **url** (string) - Required - The URL of the video to upload. ### Response #### Success Response (200) - **message** (string) - Confirmation message of successful upload initiation. - **video_id** (string) - The unique identifier for the uploaded video. ``` -------------------------------- ### Clip Response Object Source: https://platform.zapcap.ai/docs/guides/clipping-tasks Structure for each generated clip, providing its download URL and a descriptive theme. ```json { "url": string; "theme": string; } ``` -------------------------------- ### Create Video Clip Task Response Body Source: https://platform.zapcap.ai/docs/guides/clipping-tasks Response upon successful creation of a clipping task, containing the unique task ID. ```json { "id": string; } ``` -------------------------------- ### Direct Video Upload using Python Requests Source: https://platform.zapcap.ai/docs/guides/uploading-videos Upload a video file using Python's requests library. The library handles setting the Content-Type header with the correct boundary. ```python import requests url = "https://api.zapcap.ai/videos" files = {'file': open('path/to/your/video.mp4', 'rb')} headers = { 'x-api-key': 'YOUR_API_KEY' } response = requests.post(url, files=files, headers=headers) ``` -------------------------------- ### Handle Webhooks for Video Uploads Source: https://platform.zapcap.ai/docs Process video uploads and trigger captioning tasks within an Express.js server. ```javascript // Server-side webhook handler (Express.js) app.post("/video-uploaded", async (req, res) => { const { videoUrl } = req.body; // Upload video to ZapCap const uploadRes = await fetch("https://api.zapcap.ai/videos/url", { method: "POST", headers: { "x-api-key": process.env.ZAPCAP_API_KEY, "Content-Type": "application/json", }, body: JSON.stringify({ url: videoUrl }), }); const { id: videoId } = await uploadRes.json(); // Create captioning task await fetch(`https://api.zapcap.ai/videos/${videoId}/task`, { method: "POST", headers: { "x-api-key": process.env.ZAPCAP_API_KEY, "Content-Type": "application/json", }, body: JSON.stringify({ templateId: process.env.TEMPLATE_ID, autoApprove: true, }), }); res.json({ status: "processing" }); }); ``` -------------------------------- ### Direct Video Upload using cURL Source: https://platform.zapcap.ai/docs/guides/uploading-videos Upload a video file directly from your local machine using cURL. The Content-Type header is automatically set by cURL. ```bash curl -X POST "https://api.zapcap.ai/videos" \ -H "Content-Type: multipart/form-data" \ -H "x-api-key: YOUR_API_KEY" \ -F "file=@/path/to/your/video.mp4" ``` -------------------------------- ### Upload Video by URL Request Body Source: https://platform.zapcap.ai/docs/guides/uploading-videos Use this JSON body to upload a video by providing its URL. Ensure the URL points to a publicly accessible video file. ```json { "url": "https://example.com/path/to/video.mp4" } ``` -------------------------------- ### Render Options Overview Source: https://platform.zapcap.ai/docs/guides/captions-configuration Defines the structure for customizing subtitle rendering, including options for emojis, animations, keyword emphasis, display word count, font styling, and highlight colors. ```yaml renderOptions: subsOptions: emoji: boolean emojiAnimation: boolean emphasizeKeywords: boolean animation: boolean punctuation: boolean displayWords: number styleOptions: top: number fontUppercase: boolean fontSize: number fontWeight: number fontColor: string fontShadow: string stroke: string strokeColor: string highlightOptions: randomColourOne: string randomColourTwo: string randomColourThree: string ``` -------------------------------- ### Download Transcript and Video - cURL Source: https://platform.zapcap.ai/docs/quickstart Use the provided URLs from the task status response to download the generated transcript and the final processed video. ```curl # Download the transcript curl -o transcript.json "TRANSCRIPT_URL_FROM_STATUS" # Download the final video curl -o final_video.mp4 "DOWNLOAD_URL_FROM_STATUS" ``` -------------------------------- ### Add Captions to Video using Python Source: https://platform.zapcap.ai/docs/examples/caption-a-video Use this Python script to automate the process of adding captions to a video using the Zapcap AI API. It handles template fetching, video upload, task creation, and polling for completion. ```python API_KEY = 'YOUR_API_KEY' API_BASE = 'https://api.zapcap.ai' VIDEO_PATH = '/path/to/your/video.mp4' def add_captions(video_path): try: # 1. Get available templates print('Fetching templates...') templates_response = requests.get( f'{API_BASE}/templates', headers={'x-api-key': API_KEY} ) templates_response.raise_for_status() template_id = templates_response.json()[0]['id'] print('Using template:', template_id) # 2. Upload video print('Uploading video...') with open(video_path, 'rb') as f: upload_response = requests.post( f'{API_BASE}/videos', headers={'x-api-key': API_KEY}, files={'file': f} ) upload_response.raise_for_status() video_id = upload_response.json()['id'] print('Video uploaded, ID:', video_id) # 3. Create task print('Creating captioning task...') task_response = requests.post( f'{API_BASE}/videos/{video_id}/task', headers={ 'x-api-key': API_KEY, 'Content-Type': 'application/json' }, json={ 'templateId': template_id, 'autoApprove': True, 'language': 'en' } ) task_response.raise_for_status() task_id = task_response.json()['taskId'] print('Task created, ID:', task_id) # 4. Poll for completion print('Processing video...') attempts = 0 while True: status_response = requests.get( f'{API_BASE}/videos/{video_id}/task/{task_id}', headers={'x-api-key': API_KEY} ) status_response.raise_for_status() data = status_response.json() status = data['status'] print('Status:', status) if status == 'completed': # Download the video print('Downloading captioned video...') download_response = requests.get(data['downloadUrl']) download_response.raise_for_status() output_path = 'captioned_video.mp4' with open(output_path, 'wb') as f: f.write(download_response.content) print('Video saved to:', output_path) break elif status == 'failed': raise Exception(f"Task failed: {data.get('error')}") time.sleep(2) attempts += 1 except Exception as e: print('Error:', str(e)) add_captions(VIDEO_PATH) ``` -------------------------------- ### Batch Process Multi-Language Translations Source: https://platform.zapcap.ai/docs Generate multiple translated versions of a video by mapping over a list of language codes. ```javascript // Server-side batch translation async function createTranslations(videoId, templateId, languages) { const tasks = await Promise.all( languages.map((language) => fetch(`https://api.zapcap.ai/videos/${videoId}/task`, { method: "POST", headers: { "x-api-key": process.env.ZAPCAP_API_KEY, "Content-Type": "application/json", }, body: JSON.stringify({ templateId, translateTo: language, autoApprove: true, }), }).then((res) => res.json()) ) ); return tasks; } // Usage: Create Spanish, French, and German versions createTranslations(videoId, "template_id", ["es", "fr", "de"]); ```