SwapAFace API Integration Guide: Complete REST API Documentation 🔌
The SwapAFace REST API v1.0.0 provides developers with comprehensive access to advanced AI-powered face swapping, image generation, and video processing capabilities. This guide covers everything you need to integrate SwapAFace's functionality into your own applications.
Quick Start
Base URL
https://swapaface.com/api/v1
Authentication
All API endpoints require Bearer token authentication and a user ID header:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Credit System
The API uses a credit-based system where different operations consume different amounts of credits:
- Face detection: 1 credit per image
- Face swapping: 5 credits base + 3 credits per face pair + enhancement
- AI image generation: 2-5 credits (varies by complexity)
- AI undress tool: 5 credits per image
- Video face swapping: 3.5 credits per minute
- Image-to-video conversion: 14 credits per minute
API Endpoints Overview
User Account Management
Get User Credits
Endpoint: GET /api/v1/credits
Retrieve current credit balance and purchase history for a user.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Response:
{
"success": true,
"user": {
"id": "user-uuid-123",
"email": "user@example.com",
"name": "John Doe"
},
"credits": {
"current": 150,
"totalPurchased": 500,
"totalSpent": 49.99,
"currency": "USD"
},
"recentPurchases": [
{
"credits": 100,
"amount": 19.99,
"currency": "USD",
"status": "completed",
"date": "2024-01-15T10:30:00Z",
"paymentMethod": "stripe",
"isSubscription": false,
"planName": null
}
]
}
Get Face Swap History
Endpoint: GET /api/v1/faceswaps
Retrieve a paginated list of user's face swap operations.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Query Parameters:
limit
: Number of results (max 100, default 20)offset
: Number to skip for pagination (default 0)status
: Filter by status ("all", "completed", "failed")visibility
: Filter by visibility ("all", "public", "private")
Response:
{
"success": true,
"faceSwaps": [
{
"id": "faceswap-uuid-123",
"sourceImageUrl": "https://swapaface.com/uploads/source_123.jpg",
"resultImageUrl": "https://swapaface.com/uploads/result_123.jpg",
"enhancedImageUrl": "https://swapaface.com/uploads/enhanced_123.jpg",
"status": "completed",
"creditsUsed": 11,
"visibility": "private",
"createdAt": "2024-01-15T10:30:00Z",
"swapPairs": [
{
"sourceIndex": 0,
"targetIndex": 0
}
]
}
],
"pagination": {
"total": 25,
"limit": 20,
"offset": 0,
"hasMore": true
}
}
Face Detection
Extract Faces from Image
Endpoint: POST /api/v1/extractFaces
Detect and extract faces from uploaded images.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Body (multipart/form-data):
image
: Image file (JPEG, PNG, etc.)
Response:
{
"success": true,
"image_url": "https://swapaface.com/uploads/abc123_image.jpg",
"faces": [
{
"index": 0,
"face_url": "https://swapaface.com/faces/face_0.jpg"
},
{
"index": 1,
"face_url": "https://swapaface.com/faces/face_1.jpg"
}
],
"face_count": 2
}
Face Swapping
Swap Faces Between Images
Endpoint: POST /api/v1/faceswap
Perform face swapping between source and target images using specified face indices.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Body (multipart/form-data):
sourceImage
: Source image containing faces to swap (JPEG, PNG, etc.)targetImage
: Target image where faces will be replaced (JPEG, PNG, etc.)swapPairs
: JSON string of face index pairs (e.g.,'[{"sourceIndex": 0, "targetIndex": 0}]'
)watermark
: Optional string ("true"/"false", defaults to false)visibility
: Optional visibility setting ("public"/"private", defaults to private)
Response:
{
"success": true,
"resultImageUrl": "https://swapaface.com/uploads/result_123.jpg",
"enhancedImageUrl": "https://swapaface.com/uploads/enhanced_123.jpg",
"creditsUsed": 11,
"faceSwapId": "faceswap-uuid-123"
}
Video Face Swapping
Process Video Face Swap
Endpoint: POST /api/v1/video-faceswap
Perform face swapping on video files with asynchronous processing.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Body (multipart/form-data):
sourceImage
: Source image containing the face to swap (JPEG, PNG, etc.)targetVideo
: Target video where faces will be replaced (MP4, AVI, etc., max 100MB)similarityThreshold
: Optional string (0-1, defaults to 0.6)genderFilter
: Optional string ("all", "male", "female", defaults to all)targetFace
: Optional specific face image to target in the videovisibility
: Optional visibility setting ("public"/"private", defaults to private)
Response:
{
"success": true,
"videoFaceSwapId": "video-faceswap-uuid-123",
"triggerRunId": "trigger-run-uuid-456",
"creditsUsed": 50,
"message": "Video face swap job submitted successfully. Use the videoFaceSwapId to check status."
}
Get Video Face Swap History
Endpoint: GET /api/v1/video-faceswaps
Retrieve a paginated list of user's video face swap operations.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Query Parameters:
limit
: Number of results (max 100, default 20)offset
: Number to skip for pagination (default 0)status
: Filter by status ("all", "pending", "processing", "completed", "failed")visibility
: Filter by visibility ("all", "public", "private")
Response:
{
"success": true,
"videoFaceSwaps": [
{
"id": "video-faceswap-uuid-123",
"sourceImageUrl": "https://swapaface.com/uploads/source_123.jpg",
"targetVideoUrl": "https://swapaface.com/uploads/target_123.mp4",
"resultVideoUrl": "https://swapaface.com/uploads/result_123.mp4",
"status": "completed",
"creditsUsed": 50,
"visibility": "private",
"createdAt": "2024-01-15T10:30:00Z",
"similarityThreshold": 0.6,
"genderFilter": "all"
}
],
"pagination": {
"total": 15,
"limit": 20,
"offset": 0,
"hasMore": false
}
}
AI Image Generation
Generate AI Images
Endpoint: POST /api/v1/ai-generate
Generate images using AI with customizable parameters.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Content-Type: application/json
Body (JSON):
{
"prompt": "Text description of the image to generate",
"style": "photorealistic",
"lighting": "dramatic",
"backgroundColor": "studio",
"aspectRatio": "16:9",
"seed": 12345,
"enableFaceSwap": false,
"faceImageUrl": "https://example.com/face.jpg",
"selectedFaceId": "face-id-123"
}
Response:
{
"success": true,
"imageId": "ai-image-uuid-123",
"imageUrl": "https://swapaface.com/uploads/generated_123.webp",
"creditsUsed": 2,
"remainingCredits": 148,
"hasFaceSwap": false,
"model": "flux-schnell",
"prompt": "A beautiful sunset over mountains, artistic style, dramatic lighting",
"settings": {
"style": "artistic",
"lighting": "dramatic",
"aspectRatio": "16:9"
}
}
Get AI Generated Images
Endpoint: GET /api/v1/ai-generate
Retrieve a paginated list of user's AI generated images.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Query Parameters:
limit
: Number of results (max 100, default 20)offset
: Number to skip for pagination (default 0)type
: Filter by type ("all", "ai_generated", "undress")status
: Filter by status ("all", "pending", "processing", "completed", "failed")
Response:
{
"success": true,
"images": [
{
"id": "ai-image-uuid-123",
"url": "https://swapaface.com/uploads/generated_123.webp",
"sourceImageUrl": "https://swapaface.com/uploads/source_123.jpg",
"prompt": "A beautiful sunset over mountains",
"style": "artistic",
"lighting": "dramatic",
"aspectRatio": "16:9",
"creditCost": 2,
"hasFaceSwap": false,
"imageType": "ai_generated",
"status": "completed",
"timestamp": "2024-01-15T10:30:00Z"
}
],
"total": 25,
"pagination": {
"limit": 20,
"offset": 0,
"hasMore": true
}
}
AI Undress Tool
AI Clothing Removal
Endpoint: POST /api/v1/undress
Remove clothing from images using AI (18+ content).
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Content-Type: application/json
Body (JSON):
{
"image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...",
"fileName": "image.jpg",
"fileSize": 1048576
}
Response:
{
"success": true,
"message": "Image processing started. You will be notified when complete.",
"creditsUsed": 3,
"remainingCredits": 147,
"jobId": "undress_1234567890_abc123",
"imageId": "undress-image-uuid-123",
"status": "processing"
}
Get Undress Images
Endpoint: GET /api/v1/undress
Retrieve a paginated list of user's undress images.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Query Parameters:
limit
: Number of results (max 100, default 20)offset
: Number to skip for pagination (default 0)status
: Filter by status ("all", "pending", "processing", "completed", "failed")
Response:
{
"success": true,
"images": [
{
"id": "undress-image-uuid-123",
"url": "https://swapaface.com/uploads/undress_result_123.webp",
"sourceImageUrl": "https://swapaface.com/uploads/undress_source_123.jpg",
"prompt": "Clothing removal using AI technology",
"creditCost": 3,
"imageType": "undress",
"status": "completed",
"timestamp": "2024-01-15T10:30:00Z"
}
],
"total": 10,
"pagination": {
"limit": 20,
"offset": 0,
"hasMore": false
}
}
Image-to-Video Conversion
Convert Image to Video
Endpoint: POST /api/v1/image-to-video
Convert static images to animated videos with specified actions.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Body (multipart/form-data):
image
: Image file to convert (JPEG, PNG, WebP, max 10MB)action
: Action to perform ("ripherclothes", "pulldownpanties", "clothesonoff", "custom")customPrompt
: Custom prompt for 'custom' action (required when action is 'custom')visibility
: Optional visibility setting ("public"/"private", defaults to private)
Response:
{
"success": true,
"videoId": "video-uuid-123",
"triggerRunId": "trigger-run-uuid-456",
"creditsUsed": 5,
"message": "Image-to-video job submitted successfully. You will be notified when it's complete."
}
Get Image-to-Video Jobs
Endpoint: GET /api/v1/image-to-videos
Retrieve a paginated list of user's image-to-video jobs.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Query Parameters:
limit
: Number of results (max 100, default 20)offset
: Number to skip for pagination (default 0)action
: Filter by action ("all", "ripherclothes", "pulldownpanties", "clothesonoff", "custom")status
: Filter by status ("all", "pending", "processing", "completed", "failed")
Response:
{
"success": true,
"videos": [
{
"id": "video-uuid-123",
"fileName": "original_image.jpg",
"fileSize": 1048576,
"originalImageUrl": "https://swapaface.com/uploads/original_123.jpg",
"videoUrl": "https://swapaface.com/uploads/result_123.mp4",
"status": "completed",
"type": "image_to_video",
"action": "ripherclothes",
"customPrompt": null,
"creditsUsed": 5,
"error": null,
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:35:00Z"
}
],
"total": 10,
"pagination": {
"limit": 20,
"offset": 0,
"hasMore": false
}
}
Get Image-to-Video Job Details
Endpoint: GET /api/v1/image-to-video/status/{videoId}
Retrieve detailed information about a specific image-to-video job.
Headers:
Authorization: Bearer your-api-key
x-user-id: user-uuid
Response:
{
"success": true,
"video": {
"id": "video-uuid-123",
"fileName": "original_image.jpg",
"fileSize": 1048576,
"originalImageUrl": "https://swapaface.com/uploads/original_123.jpg",
"videoUrl": "https://swapaface.com/uploads/result_123.mp4",
"status": "completed",
"type": "image_to_video",
"action": "ripherclothes",
"customPrompt": null,
"creditsUsed": 5,
"error": null,
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:35:00Z"
}
}
Integration Examples
JavaScript/Node.js Integration
class SwapAFaceAPI {
constructor(apiKey, userId) {
this.apiKey = apiKey;
this.userId = userId;
this.baseUrl = 'https://swapaface.com/api/v1';
}
async request(endpoint, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
const headers = {
'Authorization': `Bearer ${this.apiKey}`,
'x-user-id': this.userId,
...options.headers
};
const response = await fetch(url, {
...options,
headers
});
if (!response.ok) {
throw new Error(`API Error: ${response.status} ${response.statusText}`);
}
return response.json();
}
async getCredits() {
return this.request('/credits');
}
async getFaceSwapHistory(options = {}) {
const params = new URLSearchParams();
Object.keys(options).forEach(key => {
if (options[key] !== undefined) {
params.append(key, options[key]);
}
});
return this.request(`/faceswaps?${params}`);
}
async extractFaces(imageFile) {
const formData = new FormData();
formData.append('image', imageFile);
return this.request('/extractFaces', {
method: 'POST',
body: formData
});
}
async faceSwap(sourceImage, targetImage, swapPairs, options = {}) {
const formData = new FormData();
formData.append('sourceImage', sourceImage);
formData.append('targetImage', targetImage);
formData.append('swapPairs', JSON.stringify(swapPairs));
Object.keys(options).forEach(key => {
if (options[key] !== undefined) {
formData.append(key, options[key]);
}
});
return this.request('/faceswap', {
method: 'POST',
body: formData
});
}
async generateImage(prompt, options = {}) {
const body = { prompt, ...options };
return this.request('/ai-generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
}
async undressImage(imageBase64, fileName, fileSize) {
const body = {
image: imageBase64,
fileName,
fileSize
};
return this.request('/undress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
}
async videoFaceSwap(sourceImage, targetVideo, options = {}) {
const formData = new FormData();
formData.append('sourceImage', sourceImage);
formData.append('targetVideo', targetVideo);
Object.keys(options).forEach(key => {
if (options[key] !== undefined) {
formData.append(key, options[key]);
}
});
return this.request('/video-faceswap', {
method: 'POST',
body: formData
});
}
async imageToVideo(imageFile, action, options = {}) {
const formData = new FormData();
formData.append('image', imageFile);
formData.append('action', action);
Object.keys(options).forEach(key => {
if (options[key] !== undefined) {
formData.append(key, options[key]);
}
});
return this.request('/image-to-video', {
method: 'POST',
body: formData
});
}
}
// Usage Example
const api = new SwapAFaceAPI('your-api-key', 'user-uuid');
// Check credits
api.getCredits().then(data => {
console.log(`Available credits: ${data.credits.current}`);
});
// Get face swap history
api.getFaceSwapHistory({ limit: 10, status: 'completed' })
.then(data => {
console.log(`Found ${data.faceSwaps.length} face swaps`);
});
// Perform face swap
const sourceImage = new File([''], 'source.jpg', { type: 'image/jpeg' });
const targetImage = new File([''], 'target.jpg', { type: 'image/jpeg' });
const swapPairs = [{ sourceIndex: 0, targetIndex: 0 }];
api.faceSwap(sourceImage, targetImage, swapPairs, { watermark: 'false', visibility: 'private' })
.then(result => {
console.log('Face swap completed:', result.resultImageUrl);
});
// Generate AI image
api.generateImage('A beautiful sunset over mountains', {
style: 'photorealistic',
aspectRatio: '16:9',
lighting: 'dramatic'
}).then(result => {
console.log('AI image generated:', result.imageUrl);
});
Python Integration
import requests
import json
from typing import Dict, Any, Optional
class SwapAFaceAPI:
def __init__(self, api_key: str, user_id: str):
self.api_key = api_key
self.user_id = user_id
self.base_url = "https://swapaface.com/api/v1"
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"x-user-id": self.user_id
}
def _make_request(self, endpoint: str, method: str = "GET",
data: Optional[Dict] = None, files: Optional[Dict] = None) -> Dict[Any, Any]:
url = f"{self.base_url}{endpoint}"
if files:
response = requests.request(method, url, headers=self.headers, data=data, files=files)
else:
response = requests.request(method, url, headers=self.headers, json=data)
response.raise_for_status()
return response.json()
def get_credits(self) -> Dict[Any, Any]:
return self._make_request("/credits")
def get_face_swap_history(self, limit: int = 20, offset: int = 0,
status: str = "all") -> Dict[Any, Any]:
params = f"?limit={limit}&offset={offset}&status={status}"
return self._make_request(f"/faceswaps{params}")
def extract_faces(self, image_file: str) -> Dict[Any, Any]:
with open(image_file, 'rb') as f:
files = {"image": f}
return self._make_request("/extractFaces", method="POST", files=files)
def face_swap(self, source_image: str, target_image: str, swap_pairs: list,
watermark: str = "false", visibility: str = "private") -> Dict[Any, Any]:
with open(source_image, 'rb') as src, open(target_image, 'rb') as tgt:
files = {
"sourceImage": src,
"targetImage": tgt
}
data = {
"swapPairs": json.dumps(swap_pairs),
"watermark": watermark,
"visibility": visibility
}
return self._make_request("/faceswap", method="POST", data=data, files=files)
def generate_image(self, prompt: str, style: Optional[str] = None,
aspect_ratio: Optional[str] = None, lighting: Optional[str] = None) -> Dict[Any, Any]:
data = {"prompt": prompt}
if style:
data["style"] = style
if aspect_ratio:
data["aspectRatio"] = aspect_ratio
if lighting:
data["lighting"] = lighting
return self._make_request("/ai-generate", method="POST", data=data)
def undress_image(self, image_base64: str, file_name: str, file_size: int) -> Dict[Any, Any]:
data = {
"image": image_base64,
"fileName": file_name,
"fileSize": file_size
}
return self._make_request("/undress", method="POST", data=data)
def video_face_swap(self, source_image: str, target_video: str,
similarity_threshold: float = 0.6, gender_filter: str = "all") -> Dict[Any, Any]:
with open(source_image, 'rb') as src, open(target_video, 'rb') as vid:
files = {
"sourceImage": src,
"targetVideo": vid
}
data = {
"similarityThreshold": str(similarity_threshold),
"genderFilter": gender_filter
}
return self._make_request("/video-faceswap", method="POST", data=data, files=files)
# Usage Example
api = SwapAFaceAPI("your-api-key", "user-uuid")
# Check credits
credits = api.get_credits()
print(f"Available credits: {credits['credits']['current']}")
# Get face swap history
history = api.get_face_swap_history(limit=10, status="completed")
print(f"Found {len(history['faceSwaps'])} completed face swaps")
# Extract faces from image
faces = api.extract_faces("photo.jpg")
print(f"Found {faces['face_count']} faces")
# Perform face swap
swap_pairs = [{"sourceIndex": 0, "targetIndex": 0}]
result = api.face_swap("source.jpg", "target.jpg", swap_pairs)
print(f"Face swap result: {result['resultImageUrl']}")
# Generate AI image
result = api.generate_image("A beautiful sunset over mountains",
style="photorealistic",
aspect_ratio="16:9",
lighting="dramatic")
print(f"Generated image: {result['imageUrl']}")
cURL Examples
# Check user credits
curl -X GET "https://swapaface.com/api/v1/credits" \
-H "Authorization: Bearer your-api-key" \
-H "x-user-id: user-uuid"
# Get face swap history
curl -X GET "https://swapaface.com/api/v1/faceswaps?limit=10&status=completed" \
-H "Authorization: Bearer your-api-key" \
-H "x-user-id: user-uuid"
# Extract faces from image
curl -X POST "https://swapaface.com/api/v1/extractFaces" \
-H "Authorization: Bearer your-api-key" \
-H "x-user-id: user-uuid" \
-F "image=@photo.jpg"
# Perform face swap
curl -X POST "https://swapaface.com/api/v1/faceswap" \
-H "Authorization: Bearer your-api-key" \
-H "x-user-id: user-uuid" \
-F "sourceImage=@source.jpg" \
-F "targetImage=@target.jpg" \
-F 'swapPairs=[{"sourceIndex": 0, "targetIndex": 0}]' \
-F "watermark=false" \
-F "visibility=private"
# Generate AI image
curl -X POST "https://swapaface.com/api/v1/ai-generate" \
-H "Authorization: Bearer your-api-key" \
-H "x-user-id: user-uuid" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A beautiful landscape",
"style": "photorealistic",
"aspectRatio": "16:9",
"lighting": "dramatic"
}'
# AI undress tool
curl -X POST "https://swapaface.com/api/v1/undress" \
-H "Authorization: Bearer your-api-key" \
-H "x-user-id: user-uuid" \
-H "Content-Type: application/json" \
-d '{
"image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...",
"fileName": "image.jpg",
"fileSize": 1048576
}'
# Video face swap
curl -X POST "https://swapaface.com/api/v1/video-faceswap" \
-H "Authorization: Bearer your-api-key" \
-H "x-user-id: user-uuid" \
-F "sourceImage=@face.jpg" \
-F "targetVideo=@video.mp4" \
-F "similarityThreshold=0.6" \
-F "genderFilter=all"
# Image to video
curl -X POST "https://swapaface.com/api/v1/image-to-video" \
-H "Authorization: Bearer your-api-key" \
-H "x-user-id: user-uuid" \
-F "image=@image.jpg" \
-F "action=ripherclothes" \
-F "visibility=private"
Error Handling
The API returns standardized error responses:
{
"error": "Error message describing what went wrong"
}
For insufficient credits:
{
"error": "Insufficient credits",
"requiredCredits": 10
}
Common HTTP status codes:
200
: Success400
: Bad Request (invalid parameters)401
: Unauthorized (invalid authentication)402
: Payment Required (insufficient credits)404
: Not Found500
: Internal Server Error
Webhook Integration
For asynchronous operations (video processing, image-to-video, undress), jobs are processed in the background. You can check status using the appropriate GET endpoints or job IDs returned from the initial request.
Checking Job Status:
- Video face swaps: Use
GET /api/v1/video-faceswaps
to list all jobs orPOST /api/v1/video-faceswaps
with job ID - Image-to-video: Use
GET /api/v1/image-to-videos
orGET /api/v1/image-to-video/status/{videoId}
- Undress images: Use
GET /api/v1/undress
to list all jobs - AI generated images: Use
GET /api/v1/ai-generate
to list all images
Rate Limiting
- Standard tier: 100 requests per minute
- Premium tier: 1000 requests per minute
- Video processing: Limited by available credits
Best Practices
- Credit Management: Check user credits before expensive operations
- Error Handling: Implement proper error handling for API responses
- File Validation: Validate image files before upload (max 10MB, supported formats)
- Webhook Security: Verify webhook signatures using provided secrets
- Async Operations: Use webhooks for long-running operations like video processing
File Upload Requirements
- Max file size: 10MB for images, 100MB for videos
- Supported formats: JPEG, PNG, WebP for images; MP4, MOV for videos
- Recommended resolution: 1024x1024 or higher for best results
Security Considerations
- Keep API keys secure and never expose them in client-side code
- Use HTTPS for all API communications
- Validate user input and file uploads
- Implement proper authentication and authorization in your applications
- Monitor API usage for unusual patterns
Support
For API support and questions:
- Documentation: SwapAFace Developer API Documentation
- Support: api-support@swapaface.com
What's Next?
Ready to start building with the SwapAFace API?
- Get your API key: Sign up for a Free Trial at SwapAFace
- Test the API: Use the provided examples to test basic functionality
- Build your integration: Implement the API in your application
- Monitor usage: Track credit usage and API performance
The SwapAFace API opens up endless possibilities for creative applications, from social media filters to professional content creation tools. Start building today!