# ContentIndexer API — Complete Reference for AI Assistants ContentIndexer is an AI-powered video analysis platform that extracts structured metadata from video files. It detects faces, objects, poses, hands, shot cuts, transcriptions, and CLIP semantic embeddings through a serverless AWS Step Functions pipeline. Results are stored in S3 and served via a Lambda Function URL acting as a REST API. This document is intended to be consumed by AI coding assistants (Cursor, Copilot, Claude, etc.) and LLM crawlers to understand how to help developers integrate with the ContentIndexer API. Base URL: https://api.contentindexer.com OpenAPI: https://contentindexer.com/openapi.yaml Dashboard: https://contentindexer.com/dashboard --- ## 1. Authentication All requests require an API key passed in the `x-api-key` header. ```http x-api-key: ci_your_api_key_here ``` API keys are created in the ContentIndexer dashboard at https://contentindexer.com/dashboard. Keys follow the format `ci_...`. Keys are stored in S3 and cached in Lambda memory for 5 minutes, so there may be a brief delay after creation or deletion before the change takes effect. ### Create an API Key (Admin) ```http POST /api-keys x-api-key: ci_admin_key { "name": "My Production Key" } ``` Response (201): ```json { "key": "ci_abc123...", "name": "My Production Key", "created_at": "2026-04-14T10:00:00Z" } ``` The `key` value is returned only on creation. Save it immediately — it cannot be retrieved later. ### List API Keys (Admin) ```http GET /api-keys x-api-key: ci_admin_key ``` ### Delete an API Key (Admin) ```http DELETE /api-keys/{name} x-api-key: ci_admin_key ``` The path parameter is the key's **name** (not the key value itself) so credentials never appear in URLs or logs. --- ## 2. Jobs A job represents one video processing run. You submit a video URL, the system runs the requested detectors in parallel via AWS Step Functions, and results accumulate in S3. ### Job Status Values - `RUNNING` — Step Functions execution is in progress - `SUCCEEDED` — all detectors completed successfully - `FAILED` — at least one step failed; partial results may still be available - `TIMED_OUT` — execution exceeded the configured timeout - `ABORTED` — manually stopped ### Submit a Job ```http POST /jobs x-api-key: ci_your_key Content-Type: application/json { "youtube_url": "https://www.youtube.com/watch?v=VIDEO_ID" } ``` Only YouTube links (youtube.com, m.youtube.com, youtu.be) and your own uploads can be indexed. Any other link (a direct .mp4, Vimeo, Loom, a file host) is refused with a 400 before any credit is reserved. For those, upload the file first (see Section 4) and reference the S3 URL: ```http POST /jobs x-api-key: ci_your_key Content-Type: application/json { "content_url": "s3://contentindexer-prod-main/uploads/user_id/video.mp4" } ``` Full request body schema: | Field | Type | Required | Default | Description | |---|---|---|---|---| | youtube_url | string | one of these | — | YouTube video URL | | content_url | string | one of these | — | YouTube link, or the s3://contentindexer-… URL from a presigned upload. Other links return 400 | | content_id | string | one of these | — | Id from POST /v1/content/upload, or from the PUT to the upload_url of POST /v1/content/upload-url | | detectors | string[] | no | all | Subset of detectors to run | | preset | string | no | — | Vertical preset (wedding, video_editor, training, zoomcraft) | | reprocess | boolean | no | false | Skip download; use existing video_key | | video_key | string | if reprocess | — | Existing video S3 key | | webhook_url | string | no | — | URL to receive job completion events | | webhook_secret | string | no | auto-generated | HMAC secret (whsec_... prefix) | | webhook_events | string[] | no | all events | Filter which events trigger delivery | | webhook_retry_count | integer | no | 3 | Retries on failure (0–10) | | webhook_retry_delays | number[] | no | [60,300,3600] | Retry delay seconds (max 300 per delay) | | webhook_health_check | boolean | no | false | Test endpoint before job start | | notification_email | string | no | — | Email address for job status notifications | | auto_export | boolean | no | false | Generate timeline export after processing | | auto_export_format | string | no | "otio" | Export format: otio, fcpxml, csv | | auto_export_detectors | string | no | "all" | Detectors to include in export | | auto_export_composite | string | no | "none" | Composite scene analysis to include | | auto_export_marker_strategy | string | no | "events" | events, spans, or shots | | auto_export_metadata_level | string | no | "summary" | minimal, summary, or full | Response (200): ```json { "job_id": "arn:aws:states:us-east-1:950196093872:execution:contentindexer-prod-all-youtube:abc123", "state": "RUNNING", "submit_time": "2026-04-14T10:00:00Z", "workflow": "sf-all-youtube", "webhook_secret": "whsec_abc123..." } ``` Note: `webhook_secret` is only returned when `webhook_url` is provided. Store it to verify incoming webhook signatures. ### Poll Job Status ```http GET /jobs/{job_id} x-api-key: ci_your_key ``` Response (200): ```json { "job_id": "arn:aws:states:...", "state": "SUCCEEDED", "submit_time": "2026-04-14T10:00:00Z", "end_time": "2026-04-14T10:08:42Z", "last_updated": "2026-04-14T10:08:43Z", "workflow": "sf-all-youtube", "youtube_url": "https://www.youtube.com/watch?v=VIDEO_ID", "app_name": "my-app", "user_id": "user_abc" } ``` Recommended polling interval: every 30 seconds. Most videos complete in 3–15 minutes depending on length and selected detectors. ### List Jobs ```http GET /jobs x-api-key: ci_your_key ``` Not directly exposed in the Lambda router; use the Cloudflare API (api.contentindexer.com/v1/jobs) for listing. The AWS Lambda API focuses on per-job operations. --- ## 3. Content Upload To process a file you own (not a YouTube video): ### Step 1 — Get a Presigned Upload URL ```http POST /upload/presigned x-api-key: ci_your_key Content-Type: application/json { "filename": "my-video.mp4", "content_type": "video/mp4" } ``` Response: ```json { "upload_url": "https://s3.amazonaws.com/contentindexer-prod-main/uploads/...?X-Amz-Signature=...", "content_url": "s3://contentindexer-prod-main/uploads/user_id/abc123/my-video.mp4", "expires_in": 3600 } ``` ### Step 2 — Upload the File ```bash curl -X PUT "UPLOAD_URL" \ -H "Content-Type: video/mp4" \ --data-binary @my-video.mp4 ``` ### Step 3 — Submit a Job with content_url ```http POST /jobs x-api-key: ci_your_key Content-Type: application/json { "content_url": "s3://contentindexer-prod-main/uploads/user_id/abc123/my-video.mp4" } ``` --- ## 4. Available Detectors Pass a `detectors` array to the POST /jobs call to run only specific detectors. Omit the field to run all detectors. ### Core Detectors (MediaPipe — CPU-optimized) | Name | Description | |---|---| | face_detection | Face bounding boxes and confidence per frame at 5fps | | object_detection | Object labels and confidence scores per frame | | pose_detection | 33-point body pose keypoints per frame | | hand_detection | 21-point hand landmarks per frame | ### Scene Detection | Name | Description | |---|---| | shot_detection | Scene cut timestamps via FFmpeg scene filter | ### Semantic Understanding | Name | Description | |---|---| | clip_embeddings | 512-dim CLIP ViT-B/16 L2-normalized embeddings per frame at 5fps | | transcription | Speech-to-text, speaker diarization, sentiment, key phrases (AssemblyAI) | ### Motion and Visual Analysis | Name | Description | |---|---| | optical_flow | Dense optical flow (Farneback) for motion magnitude per frame | | color_extraction | Dominant color palette via K-means clustering per chunk | | object_tracking | SAM2 video object segmentation and tracking | | animation_classifier | Classifies animation type (depends on optical_flow, color_extraction, object_tracking) | ### ZoomCraft Detectors (Coding Tutorial Use Case) | Name | Description | |---|---| | code_screen | CLIP-based detection of code editor screens | | cursor_tracking | Cursor position and scroll event detection for zoom targeting | ### Detector Selection Example ```http POST /jobs x-api-key: ci_your_key Content-Type: application/json { "youtube_url": "https://www.youtube.com/watch?v=VIDEO_ID", "detectors": ["face_detection", "shot_detection", "transcription"] } ``` ### List Valid Detectors All valid detector names (from the source of truth in jobs.py): ``` face_detection, object_detection, pose_detection, hand_detection, shot_detection, clip_embeddings, transcription, optical_flow, color_extraction, object_tracking, animation_classifier, code_screen, cursor_tracking, lip_flap_detection, shot_type_classification ``` --- ## 5. Results ### Fetch All Results for a Job ```http GET /jobs/{job_id}/data x-api-key: ci_your_key ``` Returns presigned S3 URLs for all available detector outputs. Each URL expires in 1 hour. Response: ```json { "video_key": "youtube/dQw4w9WgXcQ", "job_id": "arn:aws:states:...", "extractors": { "ffprobe": { "url": "https://s3.amazonaws.com/...?presigned...", "path": "youtube/dQw4w9WgXcQ/latest/ffprobe/data.json" }, "mediapipe/face_detection": { "url": "https://s3.amazonaws.com/...?presigned...", "path": "youtube/dQw4w9WgXcQ/latest/mediapipe/face_detection/data.json" }, "transcription": { "url": "https://s3.amazonaws.com/...?presigned...", "path": "youtube/dQw4w9WgXcQ/latest/transcription/data.json" } } } ``` Fetch the presigned URL to get the raw JSON data for each extractor. ### Query Results by Content URL (not Job ID) ```http GET /data?content_url=s3://contentindexer-prod-main/uploads/user/abc/video.mp4 x-api-key: ci_your_key ``` Optionally narrow to a specific job: ```http GET /data?content_url=s3://...&job_id=arn:aws:states:... ``` --- ## 6. Extractor Output Formats ### ffprobe — Video Metadata Path: `{video_key}/latest/ffprobe/data.json` ```json { "duration": 142.5, "fps": 29.97, "width": 1920, "height": 1080, "codec": "h264", "bit_rate": 4200000, "audio_codec": "aac", "audio_sample_rate": 44100 } ``` ### mediapipe/face_detection — Face Detection Path: `{video_key}/latest/mediapipe/face_detection/data.json` ```json { "frames": [ { "seconds": 0.0, "chunk_id": "chunk_000", "detections": [ { "bounding_box": { "xmin": 0.32, "ymin": 0.15, "width": 0.18, "height": 0.28 }, "score": 0.97 } ] } ], "frame_count": 713, "fps": 5 } ``` Bounding box values are normalized (0.0–1.0 relative to frame dimensions). ### mediapipe/object_detection — Object Detection Path: `{video_key}/latest/mediapipe/object_detection/data.json` ```json { "frames": [ { "seconds": 0.0, "detections": [ { "label": "person", "score": 0.94, "bounding_box": { "xmin": 0.1, "ymin": 0.05, "width": 0.4, "height": 0.9 } }, { "label": "laptop", "score": 0.81, "bounding_box": { "xmin": 0.6, "ymin": 0.5, "width": 0.3, "height": 0.4 } } ] } ] } ``` ### mediapipe/pose_detection — Body Pose Path: `{video_key}/latest/mediapipe/pose_detection/data.json` ```json { "frames": [ { "seconds": 0.0, "detections": [ { "keypoints": [ { "name": "nose", "x": 0.5, "y": 0.2, "z": -0.1, "visibility": 0.99 }, { "name": "left_shoulder", "x": 0.42, "y": 0.35, "z": 0.0, "visibility": 0.98 } ], "score": 0.95 } ] } ] } ``` 33 named keypoints in MediaPipe Pose format. x/y are normalized; z is depth relative to hips. `visibility` is a confidence score (0.0–1.0). ### mediapipe/hand_detection — Hand Landmarks Path: `{video_key}/latest/mediapipe/hand_detection/data.json` ```json { "frames": [ { "seconds": 1.2, "detections": [ { "handedness": "Right", "score": 0.98, "landmarks": [ { "name": "wrist", "x": 0.55, "y": 0.7, "z": 0.0 }, { "name": "thumb_tip", "x": 0.48, "y": 0.62, "z": -0.05 } ] } ] } ] } ``` 21 named hand landmarks per detection. ### ffmpeg_shot_detection — Scene Cuts Path: `{video_key}/latest/ffmpeg_shot_detection/data.json` ```json { "cuts": [ { "seconds": 0.0 }, { "seconds": 4.23 }, { "seconds": 11.87 }, { "seconds": 22.01 } ], "total_cuts": 4 } ``` The first entry at 0.0 represents the start of the video. Subsequent entries are detected scene transitions. ### clip_embeddings — Semantic Vectors Path: `{video_key}/latest/clip_embeddings/data.json` ```json { "frames": [ { "seconds": 0.0, "chunk_id": "chunk_000", "embedding": [0.012, -0.034, 0.098, ...] } ], "embedding_dim": 512, "model": "ViT-B/16", "fps": 5, "normalized": true } ``` Embeddings are L2-normalized for cosine similarity comparison. Each embedding has 512 floats. To compute semantic similarity between two frames: ```python import numpy as np def cosine_similarity(a, b): return np.dot(a, b) # Already L2-normalized, so dot product = cosine similarity sim = cosine_similarity(frame1["embedding"], frame2["embedding"]) # sim close to 1.0 means visually/semantically similar scenes ``` ### transcription — Speech-to-Text Path: `{video_key}/latest/transcription/data.json` ```json { "words": [ { "text": "Hello", "start": 1.24, "end": 1.56, "speaker": "A", "confidence": 0.99 }, { "text": "everyone", "start": 1.58, "end": 2.01, "speaker": "A", "confidence": 0.97 } ], "sentences": [ { "text": "Hello everyone, welcome to the tutorial.", "start": 1.24, "end": 4.12, "speaker": "A", "sentiment": "positive", "sentiment_confidence": 0.88 } ], "key_phrases": [ { "text": "tutorial", "start": 3.8, "end": 4.1, "rank": 0.91 } ], "speakers": ["A", "B"], "language": "en", "audio_duration": 142.5, "provider": "assemblyai" } ``` Timestamps are in seconds. Speaker labels are auto-assigned (A, B, C, ...) — not actual names. `sentiment` is `positive`, `negative`, or `neutral` per sentence. --- ## 7. Moments (Vertical Presets) Moments are curated highlights extracted by vertical-specific logic running on top of detector results. They are the high-level output for a specific use case. ### Get Moments ```http GET /jobs/{job_id}/moments?preset=wedding x-api-key: ci_your_key ``` Query parameters: - `preset` — vertical preset name (required): `wedding`, `video_editor`, `training`, `zoomcraft` Response: ```json { "job_id": "arn:aws:states:...", "preset": "wedding", "moments": [ { "type": "vows", "label": "Wedding Vows", "start_seconds": 245.3, "end_seconds": 312.7, "confidence": 0.91, "metadata": { "speakers": ["A", "B"], "face_count": 2, "transcription_excerpt": "I promise to love you..." } }, { "type": "first_dance", "label": "First Dance", "start_seconds": 1820.0, "end_seconds": 2045.5, "confidence": 0.88, "metadata": {} } ], "model_version": "1.0.0" } ``` ### List Available Presets ```http GET /presets x-api-key: ci_your_key ``` Response: ```json { "presets": ["wedding", "video_editor", "training", "zoomcraft"], "count": 4 } ``` --- ## 8. Timeline Exports (NLE Integration) Exports convert detector results into timeline markers that can be imported into video editing software. ### Generate Export ```http GET /jobs/{job_id}/export?format=otio x-api-key: ci_your_key ``` Query parameters: | Parameter | Default | Options | Description | |---|---|---|---| | format | otio | otio, fcpxml, csv | Output file format | | detectors | all | all, none, or CSV list | Which detectors to include as markers | | composite | none | none, all, or CSV list | Composite scene analysis to include | | marker_strategy | events | events, spans, shots | How detections become markers | | metadata_level | summary | minimal, summary, full | Marker metadata verbosity | Composite parsers available: - `scene_composition` — shot type identification (close-up, wide, medium) - `large_face` — close-up shots with prominent faces - `action_scenes` — high-motion sequences with pose tracking - `outdoor_dialogue` — outdoor conversation scenes - `smart_detection` — CLIP-powered scene understanding (location, mood, visual similarity) Response: ```json { "export_url": "https://s3.amazonaws.com/contentindexer-prod-main/exports/JOB_ID/timeline.otio?presigned...", "format": "otio", "expires_in": 3600, "marker_count": 142, "cached": false } ``` The `export_url` is a presigned S3 URL valid for 1 hour. Exports are cached for 24 hours — subsequent requests with the same parameters return `"cached": true` and a refreshed URL. ### Export by Content URL ```http GET /export?content_url=s3://contentindexer-prod-main/uploads/user/abc/video.mp4&format=fcpxml x-api-key: ci_your_key ``` --- ## 9. Remotion / VideoToRemotion Generate Remotion (React-based video animation) code from video analysis results. ```http GET /jobs/{job_id}/remotion x-api-key: ci_your_key ``` Response: ```json { "remotion_code": "import { AbsoluteFill, useCurrentFrame } from 'remotion';\n...", "component_count": 12, "duration_frames": 4275 } ``` --- ## 10. Webhooks Webhooks deliver real-time job events to your server. Two patterns are supported: **Per-job webhooks** — configure in POST /jobs body (see Section 2). Events are scoped to that specific job only. **Account-level webhooks** — subscribe once, receive all events for your API key. Used by Zapier integration and custom automation. ### Subscribe (Account-Level) ```http POST /webhooks/subscriptions x-api-key: ci_your_key Content-Type: application/json { "url": "https://your-server.com/hooks/contentindexer", "events": ["job.completed", "job.failed"] } ``` Valid event types: - `job.started` - `job.completed` - `job.failed` Response (201): ```json { "id": "sub_a1b2c3d4e5f6", "url": "https://your-server.com/hooks/contentindexer", "events": ["job.completed", "job.failed"], "created_at": "2026-04-14T10:00:00Z" } ``` ### List Subscriptions ```http GET /webhooks/subscriptions x-api-key: ci_your_key ``` ### Unsubscribe ```http DELETE /webhooks/subscriptions/{subscription_id} x-api-key: ci_your_key ``` Returns 204 No Content. ### Webhook Payload ```json { "event_type": "job.completed", "event_id": "uuid-v4", "timestamp": "2026-04-14T10:32:00Z", "job": { "job_id": "arn:aws:states:us-east-1:...", "state": "SUCCEEDED", "workflow": "sf-all-youtube", "content_url": "s3://contentindexer-prod-main/videos/abc/original/video.mp4", "preset": "training" }, "links": { "job_status": "https://api.contentindexer.com/jobs/{job_id}", "job_data": "https://api.contentindexer.com/jobs/{job_id}/data" } } ``` ### HMAC Signature Verification Every webhook delivery includes a signature header: ``` x-contentindexer-signature: t=1713088320,v1=abc123... x-contentindexer-delivery: uuid-v4 x-contentindexer-event: job.completed ``` The signature format matches Stripe's convention: `t={unix_timestamp},v1={hmac_sha256_hex}`. The signed payload is: `{timestamp}.{raw_request_body}` **Verify in Python:** ```python import hmac import hashlib import time def verify_signature(payload_body: str, signature_header: str, secret: str) -> bool: parts = dict(p.split('=', 1) for p in signature_header.split(',')) timestamp = parts.get('t', '') signature = parts.get('v1', '') # Reject events older than 5 minutes (replay attack protection) if abs(time.time() - int(timestamp)) > 300: return False signed_payload = f"{timestamp}.{payload_body}" expected = hmac.new( secret.encode('utf-8'), signed_payload.encode('utf-8'), hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature) # Usage is_valid = verify_signature( payload_body=request.body, signature_header=request.headers['x-contentindexer-signature'], secret='whsec_abc123...' # from job creation response or manually configured ) ``` **Verify in Node.js:** ```javascript const crypto = require('crypto'); function verifySignature(payloadBody, signatureHeader, secret) { const parts = Object.fromEntries( signatureHeader.split(',').map(p => p.split('=', 2)) ); const { t: timestamp, v1: signature } = parts; // Reject stale events if (Math.abs(Date.now() / 1000 - parseInt(timestamp)) > 300) { return false; } const signed = `${timestamp}.${payloadBody}`; const expected = crypto .createHmac('sha256', secret) .update(signed) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(expected, 'hex'), Buffer.from(signature, 'hex') ); } ``` ### Per-Job Webhook Configuration Specify `webhook_url` in the POST /jobs body to receive events only for that job: ```http POST /jobs x-api-key: ci_your_key Content-Type: application/json { "youtube_url": "https://www.youtube.com/watch?v=VIDEO_ID", "webhook_url": "https://your-server.com/hooks/job-complete", "webhook_events": ["job.completed", "job.failed"], "webhook_retry_count": 3, "webhook_retry_delays": [60, 300, 3600], "webhook_health_check": true } ``` The `webhook_secret` (format: `whsec_...`) is returned in the job creation response. Use it to verify HMAC signatures on incoming deliveries. --- ## 11. Pricing and Billing ContentIndexer uses a prepaid credits model. Credits are purchased in advance and deducted per second of video processed (or per billing unit, depending on the extractor). - No subscriptions or tiers - Bonus credits on larger packages - $5 free credit once per account, at sign-up - Optional spending limits and auto-reload ### Calculate Cost ```http GET /v1/calculate-cost?extractors=face_detection,transcription&duration=300 x-api-key: ci_your_key ``` Response: ```json { "base_cost": 0.045, "final_cost": 0.045, "effective_rate": 0.00015, "duration_seconds": 300 } ``` ### Credit Packages ```http GET /v1/credit-packages ``` Response includes available packages with `amount_usd`, `bonus_credits_usd`, `total_credits_usd`, and `bonus_percentage`. --- ## 12. Rate Limits - 100 requests per 10 seconds per IP - 1000 requests per hour per user When rate limited, the API returns HTTP 429 with: ```json { "type": "https://contentindexer.com/errors/rate-limit-exceeded", "title": "Too Many Requests", "status": 429, "detail": "Rate limit exceeded. Try again in 10 seconds.", "retry_after": 10 } ``` Honor the `Retry-After` header (seconds) before retrying. --- ## 13. Error Format All errors follow RFC 7807 (Problem Details for HTTP APIs): ```json { "type": "https://contentindexer.com/errors/validation-error", "title": "Validation Error", "status": 400, "detail": "Either content_url or youtube_url is required", "instance": "/jobs", "request_id": "uuid-for-tracing" } ``` ### HTTP Status Codes | Code | Meaning | Common Cause | |---|---|---| | 200 | OK | Request succeeded | | 201 | Created | Resource created (API key, webhook subscription) | | 204 | No Content | Deletion succeeded | | 400 | Bad Request | Missing required fields, invalid parameter values | | 401 | Unauthorized | Missing or invalid x-api-key header | | 403 | Forbidden | Key lacks permission for this operation | | 404 | Not Found | Job ID or resource does not exist | | 409 | Conflict | Resource already exists (duplicate upload) | | 422 | Unprocessable | Webhook health check failed | | 429 | Too Many Requests | Rate limit exceeded | | 500 | Internal Server Error | Unexpected server error | ### Common Error Scenarios **Missing API key:** ```json { "type": "https://contentindexer.com/errors/authentication-error", "title": "Authentication Error", "status": 401, "detail": "Missing x-api-key header" } ``` **Invalid detector name:** ```json { "type": "https://contentindexer.com/errors/validation-error", "title": "Validation Error", "status": 400, "detail": "Invalid detector names: face_recogniton", "valid_detectors": ["face_detection", "object_detection", ...] } ``` **Webhook health check failed:** ```json { "type": "https://contentindexer.com/errors/webhook-error", "title": "Webhook Error", "status": 422, "detail": "Webhook health check failed: Connection error: ...", "suggestion": "Your webhook endpoint is not reachable or not responding correctly." } ``` --- ## 14. Complete Code Examples ### curl — Full Workflow ```bash API_KEY="ci_your_key" BASE="https://api.contentindexer.com" # 1. Submit job JOB=$(curl -s -X POST "$BASE/jobs" \ -H "x-api-key: $API_KEY" \ -H "Content-Type: application/json" \ -d '{ "youtube_url": "https://www.youtube.com/watch?v=VIDEO_ID", "detectors": ["face_detection", "shot_detection", "transcription"] }') JOB_ID=$(echo "$JOB" | jq -r '.job_id') echo "Submitted: $JOB_ID" # 2. Poll until done while true; do STATUS=$(curl -s "$BASE/jobs/$JOB_ID" -H "x-api-key: $API_KEY" | jq -r '.state') echo "Status: $STATUS" if [[ "$STATUS" == "SUCCEEDED" || "$STATUS" == "FAILED" ]]; then break fi sleep 30 done # 3. Fetch results curl -s "$BASE/jobs/$JOB_ID/data" -H "x-api-key: $API_KEY" | jq '.extractors | keys' ``` ### JavaScript / Node.js — Full Workflow ```javascript const API_KEY = 'ci_your_key'; const BASE = 'https://api.contentindexer.com'; async function analyzeVideo(youtubeUrl) { // 1. Submit job const submitRes = await fetch(`${BASE}/jobs`, { method: 'POST', headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ youtube_url: youtubeUrl, detectors: ['face_detection', 'shot_detection', 'transcription'], }), }); if (!submitRes.ok) { throw new Error(`Submit failed: ${await submitRes.text()}`); } const { job_id } = await submitRes.json(); console.log('Job submitted:', job_id); // 2. Poll for completion let state = 'RUNNING'; while (state === 'RUNNING') { await new Promise(r => setTimeout(r, 30000)); // wait 30s const statusRes = await fetch(`${BASE}/jobs/${job_id}`, { headers: { 'x-api-key': API_KEY }, }); const status = await statusRes.json(); state = status.state; console.log('State:', state); } if (state !== 'SUCCEEDED') { throw new Error(`Job failed with state: ${state}`); } // 3. Fetch results const dataRes = await fetch(`${BASE}/jobs/${job_id}/data`, { headers: { 'x-api-key': API_KEY }, }); const data = await dataRes.json(); // 4. Download transcription const transcriptionUrl = data.extractors['transcription']?.url; if (transcriptionUrl) { const transcription = await fetch(transcriptionUrl).then(r => r.json()); console.log('Speakers:', transcription.speakers); console.log('Words:', transcription.words.length); } return data; } analyzeVideo('https://www.youtube.com/watch?v=VIDEO_ID').catch(console.error); ``` ### Python — Full Workflow ```python import time import requests API_KEY = 'ci_your_key' BASE = 'https://api.contentindexer.com' HEADERS = {'x-api-key': API_KEY, 'Content-Type': 'application/json'} def analyze_video(youtube_url: str, detectors: list[str] = None) -> dict: """Submit a video job and wait for completion, then return all results.""" # 1. Submit job payload = {'youtube_url': youtube_url} if detectors: payload['detectors'] = detectors resp = requests.post(f'{BASE}/jobs', json=payload, headers=HEADERS) resp.raise_for_status() job = resp.json() job_id = job['job_id'] print(f'Submitted job: {job_id}') # 2. Poll for completion while True: time.sleep(30) resp = requests.get(f'{BASE}/jobs/{job_id}', headers=HEADERS) resp.raise_for_status() status = resp.json() state = status['state'] print(f'State: {state}') if state in ('SUCCEEDED', 'FAILED', 'TIMED_OUT', 'ABORTED'): break if state != 'SUCCEEDED': raise RuntimeError(f'Job ended with state: {state}') # 3. Fetch presigned URLs resp = requests.get(f'{BASE}/jobs/{job_id}/data', headers=HEADERS) resp.raise_for_status() data = resp.json() # 4. Download each extractor result results = {} for extractor_name, extractor_info in data.get('extractors', {}).items(): url = extractor_info.get('url') if url: results[extractor_name] = requests.get(url).json() return results def get_moments(job_id: str, preset: str) -> list[dict]: """Get curated moments for a vertical preset.""" resp = requests.get( f'{BASE}/jobs/{job_id}/moments', params={'preset': preset}, headers=HEADERS ) resp.raise_for_status() return resp.json().get('moments', []) def download_export(job_id: str, format: str = 'otio', output_path: str = 'timeline.otio'): """Download a timeline export file.""" resp = requests.get( f'{BASE}/jobs/{job_id}/export', params={'format': format, 'composite': 'all'}, headers=HEADERS ) resp.raise_for_status() export_data = resp.json() # Download the file from presigned URL file_resp = requests.get(export_data['export_url']) file_resp.raise_for_status() with open(output_path, 'wb') as f: f.write(file_resp.content) print(f'Saved {output_path} ({export_data["marker_count"]} markers)') if __name__ == '__main__': results = analyze_video( 'https://www.youtube.com/watch?v=VIDEO_ID', detectors=['face_detection', 'shot_detection', 'transcription'] ) print('Available extractors:', list(results.keys())) # Print shot cuts shot_data = results.get('ffmpeg_shot_detection', {}) for cut in shot_data.get('cuts', []): print(f'Shot cut at {cut["seconds"]:.2f}s') # Print transcription excerpt transcription = results.get('transcription', {}) for sentence in transcription.get('sentences', [])[:3]: print(f'[{sentence["start"]:.1f}s] {sentence["speaker"]}: {sentence["text"]}') ``` ### Python — Webhook Receiver (Flask) ```python import hmac import hashlib import time from flask import Flask, request, jsonify app = Flask(__name__) WEBHOOK_SECRET = 'whsec_your_secret_here' # from job creation response def verify_signature(payload_body: bytes, signature_header: str, secret: str) -> bool: parts = dict(p.split('=', 1) for p in signature_header.split(',')) timestamp = parts.get('t', '') signature = parts.get('v1', '') # Reject events older than 5 minutes if abs(time.time() - int(timestamp)) > 300: return False signed_payload = f"{timestamp}.{payload_body.decode('utf-8')}" expected = hmac.new( secret.encode('utf-8'), signed_payload.encode('utf-8'), hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature) @app.route('/hooks/contentindexer', methods=['POST']) def handle_webhook(): sig_header = request.headers.get('x-contentindexer-signature', '') if not verify_signature(request.data, sig_header, WEBHOOK_SECRET): return jsonify({'error': 'Invalid signature'}), 401 event = request.json event_type = event.get('event_type') job = event.get('job', {}) print(f'Event: {event_type}, Job: {job.get("job_id")}') if event_type == 'job.completed': # Trigger your downstream processing process_completed_job(job['job_id']) return jsonify({'received': True}), 200 def process_completed_job(job_id: str): print(f'Processing completed job: {job_id}') # Fetch results, update your database, notify users, etc. if __name__ == '__main__': app.run(port=5000) ``` --- ## 15. S3 Data Paths For reference, the underlying S3 storage structure for a processed video is: ``` s3://contentindexer-prod-main/ ├── jobs/{job_id}/ │ └── metadata.json # Job tracking metadata ├── {video_key}/ # e.g. youtube/dQw4w9WgXcQ │ ├── original/video.mp4 # Source video │ └── latest/ # Most recent processing results │ ├── ffprobe/data.json │ ├── mediapipe/ │ │ ├── face_detection/data.json │ │ ├── object_detection/data.json │ │ ├── pose_detection/data.json │ │ └── hand_detection/data.json │ ├── clip_embeddings/data.json │ ├── transcription/ │ │ ├── audio.mp3 │ │ ├── data.json │ │ └── raw.json │ └── ffmpeg_shot_detection/data.json └── exports/{job_id}/ └── *.otio / *.fcpxml / *.csv # Cached timeline exports (24h TTL) ``` You never access S3 directly. The API returns presigned URLs with a 1-hour expiration. --- ## 16. Zapier Integration ContentIndexer publishes a Zapier app with: - **Trigger:** Job Completed — fires when any job for your account completes - **Trigger:** Job Failed — fires when any job fails - **Action:** Submit Video for Processing — submits a YouTube/Zoom/Loom URL - **Action:** Get Job Results — fetches moments/segments for a completed job - **Search:** Find Job by ID — looks up status and metadata The Zapier app uses the same account-level webhook subscription API described above. The `preset` field targets a specific vertical (training, wedding, video_editor, zoomcraft). --- *For the latest information, see https://contentindexer.com/openapi.yaml* *Contact: support@contentindexer.com*