iSamurai Logo

iSamurai Face Swap API Documentation

Complete developer guide for integrating AI-powered face swap, slow motion video, and image restoration into your applications.

🚀 Getting Started

The iSamurai API provides programmatic access to our suite of AI-powered video and image processing tools. Whether you're building a content creation platform, integrating face swap technology into your app, or adding cinematic slow motion effects, our RESTful API makes it simple.

Base URL

https://isamur.ai/api/

Quick Start Steps

  1. Create an account on iSamurai
  2. Navigate to your Profile page and generate an API key
  3. Include the API key in your request headers
  4. Start making API calls!
💡

Credit System: All processing operations consume credits. Check your balance at /api/user-credits/ before submitting jobs. View our pricing plans for credit packages.

📦 SDK & Tools

Accelerate your development with our official client libraries and code examples.

Python

Official SDK

Complete Python wrapper with automatic polling, type hinting, and error handling.

View on GitHub →
Code

API Examples

Raw scripts and usage examples for direct API integration.

View on GitHub →

🔐 Authentication

All API endpoints require authentication. Include your credentials in the Authorization header with every request.

API Key Authentication (Recommended)

API keys are the recommended authentication method for server-to-server integrations. Keys never expire and provide a simple, secure way to access all endpoints.

curl -H "Authorization: Api-Key isk_your_api_key_here" \
  https://isamur.ai/api/user-credits/

🎭 Face Swap API

The Face Swap API allows you to seamlessly swap faces in videos and images. Use the preview endpoint to test with a single frame first, then process the full video.

Quick Preview (Single Frame)

POST /api/preview-swap-api/

Generate a single-frame preview of the face swap before processing the full video. Uses base64-encoded images. Costs ~1-2 credits.

Request Body (JSON)

ParameterTypeRequiredDescription
source_image_base64stringRequiredBase64-encoded source face image
target_image_base64stringRequiredBase64-encoded target frame (from video or image)
instanceUUIDOptionalExisting FaceSwap instance ID
enhancebooleanOptionalApply face enhancement (default: false)
import requests
import base64

API_KEY = "isk_your_api_key_here"
BASE_URL = "https://isamur.ai/api"

# Convert images to base64
def to_base64(file_path):
    with open(file_path, "rb") as f:
        return base64.b64encode(f.read()).decode()

# Generate preview
response = requests.post(
    f"{BASE_URL}/preview-swap-api/",
    headers={
        "Authorization": f"Api-Key {API_KEY}",
        "Content-Type": "application/json"
    },
    json={
        "source_image_base64": to_base64("face.jpg"),
        "target_image_base64": to_base64("target_frame.jpg"),
        "enhance": False
    }
)

# Save preview image
preview_base64 = response.json()["image_base64"]
with open("preview.jpg", "wb") as f:
    f.write(base64.b64decode(preview_base64))

Response

{
  "image_base64": "/9j/4AAQSkZJRgABAQAAAQ...",
  "preview_id": "abc123"
}

Full Video Processing (Combined Upload + Process)

POST /api/full-process-swap/

Upload files and immediately start processing in one request. This is the recommended endpoint for automated workflows. Credits deducted at ~50 per minute of video.

Request Parameters (multipart/form-data)

ParameterTypeRequiredDescription
source_imageFileRequiredFace image file (JPG/PNG)
target_mediaFileRequiredVideo file (MP4/MOV) or image
gqualitystringRequired480p, 720p, or 1080p
namestringOptionalJob name (max 20 chars)
descriptionstringOptionalDescription (max 20 chars)
import requests

API_KEY = "isk_your_api_key_here"
BASE_URL = "https://isamur.ai/api"

# Upload local files and start processing
with open("face.jpg", "rb") as source, open("video.mp4", "rb") as target:
    response = requests.post(
        f"{BASE_URL}/full-process-swap/",
        headers={"Authorization": f"Api-Key {API_KEY}"},
        files={
            "source_image": ("face.jpg", source, "image/jpeg"),
            "target_media": ("video.mp4", target, "video/mp4")
        },
        data={
            "gquality": "720p",
            "name": "My Swap",
            "description": "Demo"
        }
    )

result = response.json()
instance_id = result["faceswap"]["id"]
print(f"Processing started: {instance_id}")

Check Progress

GET /api/swap-progress/?id={instance_id}

Poll this endpoint to monitor job progress until status is Done.

Status Values

StatusDescription
QueuedWaiting in queue
ProcessingCurrently processing
DoneComplete - output available
FailedError occurred
CancelledUser cancelled
import time

while True:
    response = requests.get(
        f"{BASE_URL}/swap-progress/",
        headers={"Authorization": f"Api-Key {API_KEY}"},
        params={"id": instance_id}
    )
    data = response.json()
    print(f"Status: {data['status']} - {data.get('progress_percentage', 0)}%")
    
    if data["status"] == "Done":
        print(f"Output: {data['output_media_url']}")
        break
    elif data["status"] in ["Failed", "Cancelled"]:
        print(f"Error: {data.get('error')}")
        break
    time.sleep(5)

Stop/Cancel Job

POST /api/stop-job/

Cancel a running job. You receive a 50% credit refund.

{"id": "instance_uuid", "type": "faceswap"}

👥 Multi-Face Swap API

Swap multiple faces in a single video. Analyze the frame to detect all faces, assign source images to each, then process.

Step 1: Analyze Frame (Detect Faces)

POST /api/analyse-frame/

Detect all faces in a video frame. Send a base64-encoded frame from your target video.

Request Body (JSON)

ParameterTypeDescription
target_image_base64stringBase64-encoded frame from target video
import base64

# Capture a frame from your video (using OpenCV, ffmpeg, etc.)
with open("frame.jpg", "rb") as f:
    frame_b64 = base64.b64encode(f.read()).decode()

response = requests.post(
    f"{BASE_URL}/analyse-frame/",
    headers={
        "Authorization": f"Api-Key {API_KEY}",
        "Content-Type": "application/json"
    },
    json={"target_image_base64": frame_b64}
)

faces = response.json()["analysis"]
for face in faces:
    print(f"Face detected: {face['person_id']}")

Response

{
  "analysis": [
    {"person_id": "P1", "thumbnail": "base64...", "bbox": [x, y, w, h]},
    {"person_id": "P2", "thumbnail": "base64...", "bbox": [x, y, w, h]}
  ]
}

Step 2: Preview Multi-Swap (Optional)

POST /api/multi-preview-swap-api/

Preview the multi-face swap on a single frame before full processing.

Request Body (JSON)

{
  "target_image_base64": "base64_frame...",
  "analysis_results": [
    {
      "person_id": "P1",
      "thumbnail": "base64...",
      "source_image": "base64_of_source_face_1"
    },
    {
      "person_id": "P2", 
      "thumbnail": "base64...",
      "source_image": "base64_of_source_face_2"
    }
  ],
  "enhance": false
}

Response

{"preview_image": "base64_result..."}

Step 3: Full Multi-Face Processing

POST /api/multiple-face-swap/

Process the full video with all face mappings. Use multipart/form-data.

Request Parameters (multipart/form-data)

ParameterTypeDescription
target_mediaFileVideo file (MP4/MOV)
gqualitystring480p, 720p, or 1080p
analysis_resultsJSON stringArray with source_image base64 for each face

Step 4: Check Progress

GET /api/swap-progress/?id={instance_id}&multi=True

Poll for progress. Add multi=True for multi-face swap jobs.

⏱️ Slow Motion & FPS Boost API

Create stunning slow motion videos using AI frame interpolation. Our slow motion technology generates new frames between existing ones, allowing you to slow down footage up to 8x while maintaining smooth, fluid motion.

Credit Pricing

FactorCost per SecondUse Case
2x Slow2 credits/secSmooth slow motion
4x Ultra3 credits/secDramatic slow motion
8x Super7 credits/secExtreme slow motion

Create Slow Motion Project

POST /api/slowmotion/

Upload a video and configure slow motion settings.

Request Parameters (multipart/form-data)

ParameterTypeOptionsDescription
source_videoFile-Video to slow down (MP4/MOV)
slowdown_factorint2, 4, 8How much to slow down
qualitystring480p, 720p, 1080pOutput quality
modestringslowmo, fpsslowmo = slower video, fps = smoother video
with open("action_clip.mp4", "rb") as video:
    response = requests.post(
        f"{BASE_URL}/slowmotion/",
        headers={"Authorization": f"Api-Key {API_KEY}"},
        files={"source_video": video},
        data={
            "slowdown_factor": 4,
            "quality": "720p",
            "mode": "slowmo"
        }
    )
    
project = response.json()["slowmotion"]
print(f"Project ID: {project['id']}")

Start Processing

POST /api/faceswap/slowmotion/process/

Begin slow motion processing.

{ "project_id": "uuid" }
GET /api/faceswap/slowmotion/progress/{project_id}/

Check slow motion processing progress.

✨ Image Restore & Enhance API

Restore old, damaged photos or enhance face quality using our AI-powered image restoration tool. Perfect for breathing new life into vintage photographs or improving low-resolution face images.

POST /api/restore-image/

Process an image with AI restoration or enhancement.

Request Parameters (multipart/form-data)

ParameterTypeOptions
imageFileJPG/PNG image
modestringrestore or face_enhance

Response

{
  "url": "/api/media/restored/output.jpg",
  "image_base64": "/9j/4AAQSkZ...",
  "status": "success"
}

💳 User & Credits API

Monitor your credit balance and account status. Check your credits before submitting jobs to ensure you have sufficient balance. View our pricing plans to purchase more credits.

GET /api/user-credits/

Get your current credit balance and plan information.

Response

{
  "user_id": 123,
  "user_credits": 9500,
  "plan_id": 5,
  "plan_name": "Samurai"
}

⚠️ Error Handling

All API errors return a consistent JSON structure with an error message. Use HTTP status codes to determine the type of error.

Status CodeMeaningAction
400Bad RequestCheck request parameters
401UnauthorizedCheck API key is valid
403ForbiddenInsufficient credits or permissions
404Not FoundResource doesn't exist
500Server ErrorContact support

Error Response Format

{
  "error": "Insufficient credits: need 500, have 200",
  "success": false
}

🚦 Rate Limits

Each user can run one concurrent job at a time. Wait for your current job to complete before submitting a new one. If you submit a new job while one is processing, it will be queued.

📚 Complete Code Examples

Full working examples for common use cases.

Python: Complete Face Swap Workflow

import requests
import time

API_KEY = "isk_your_key_here"
BASE_URL = "https://isamur.ai/api"
HEADERS = {"Authorization": f"Api-Key {API_KEY}"}

def face_swap(source_path, target_path, quality="720p"):
    # Step 1: Upload
    with open(source_path, "rb") as src, open(target_path, "rb") as tgt:
        resp = requests.post(f"{BASE_URL}/faceswap/", headers=HEADERS,
            files={"source_image": src, "target_media": tgt},
            data={"gquality": quality})
    job_id = resp.json()["faceswap"]["id"]
    
    # Step 2: Process
    requests.post(f"{BASE_URL}/process-swap/",
        headers={**HEADERS, "Content-Type": "application/json"},
        json={"instance": job_id})
    
    # Step 3: Wait for completion
    while True:
        resp = requests.get(f"{BASE_URL}/swap-progress/",
            headers=HEADERS, params={"id": job_id})
        data = resp.json()
        print(f"Progress: {data.get('progress_percentage', 0)}%")
        
        if data["status"] == "Done":
            return data["output_media_url"]
        elif data["status"] == "Failed":
            raise Exception(data.get("error"))
        time.sleep(3)

# Usage
output = face_swap("face.jpg", "video.mp4")
print(f"Result: https://isamur.ai{output}")

JavaScript: Complete Face Swap Workflow

const API_KEY = "isk_your_key_here";
const BASE_URL = "https://isamur.ai/api";

async function faceSwap(sourceFile, targetFile, quality = "720p") {
    // Step 1: Upload
    const formData = new FormData();
    formData.append("source_image", sourceFile);
    formData.append("target_media", targetFile);
    formData.append("gquality", quality);
    
    let resp = await fetch(`${BASE_URL}/faceswap/`, {
        method: "POST",
        headers: { "Authorization": `Api-Key ${API_KEY}` },
        body: formData
    });
    const jobId = (await resp.json()).faceswap.id;
    
    // Step 2: Process
    await fetch(`${BASE_URL}/process-swap/`, {
        method: "POST",
        headers: {
            "Authorization": `Api-Key ${API_KEY}`,
            "Content-Type": "application/json"
        },
        body: JSON.stringify({ instance: jobId })
    });
    
    // Step 3: Poll for completion
    while (true) {
        resp = await fetch(`${BASE_URL}/swap-progress/?id=${jobId}`, {
            headers: { "Authorization": `Api-Key ${API_KEY}` }
        });
        const data = await resp.json();
        console.log(`Progress: ${data.progress_percentage || 0}%`);
        
        if (data.status === "Done") return data.output_media_url;
        if (data.status === "Failed") throw new Error(data.error);
        await new Promise(r => setTimeout(r, 3000));
    }
}

Ready to get started? Create your account and generate an API key from your profile page.