Skip to content

Code Examples

Contoh implementasi Face Recognition API dalam berbagai bahasa pemrograman.

Python

Face Find Example

python
import requests
import base64

def image_to_base64(image_path):
    """Convert image to base64 format"""
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
        return f"data:image/jpeg;base64,{encoded_string}"

def find_face(api_key, image_path, threshold=0.5, limit=10):
    """Find matching faces in database"""
    url = "https://api.rivalistic.com/v1/face/find"
    
    payload = {
        "database_name": "default",
        "image_base64": image_to_base64(image_path),
        "threshold": threshold,
        "limit": limit
    }
    
    headers = {
        "x-api-key": api_key,
        "Content-Type": "application/json"
    }
    
    response = requests.post(url, json=payload, headers=headers)
    return response.json()

# Usage
api_key = "riv_sh7mLX53C0wka5b65P5LoLKYJm6PaDUv"
result = find_face(api_key, "path/to/image.jpg", threshold=0.4, limit=5)
print(result)

Face Enroll Example

python
def enroll_face(api_key, image_path, metadata=None):
    """Enroll a new face to database"""
    url = "https://api.rivalistic.com/v1/face/enroll"
    
    payload = {
        "database_name": "default",
        "image_base64": image_to_base64(image_path)
    }
    
    if metadata:
        payload["metadata"] = metadata
    
    headers = {
        "x-api-key": api_key,
        "Content-Type": "application/json"
    }
    
    response = requests.post(url, json=payload, headers=headers)
    return response.json()

# Usage
metadata = {
    "name": "John Doe",
    "employee_id": "EMP123",
    "department": "IT"
}

result = enroll_face(api_key, "path/to/image.jpg", metadata)
print(result)

Face Verify Example

python
def verify_face(api_key, image_path_1, image_path_2):
    """Verify if two faces are the same person"""
    url = "https://api.rivalistic.com/v1/face/verify"
    
    payload = {
        "database_name": "default",
        "image_base64_1": image_to_base64(image_path_1),
        "image_base64_2": image_to_base64(image_path_2)
    }
    
    headers = {
        "x-api-key": api_key,
        "Content-Type": "application/json"
    }
    
    response = requests.post(url, json=payload, headers=headers)
    return response.json()

# Usage
result = verify_face(api_key, "path/to/image1.jpg", "path/to/image2.jpg")
print(f"Match: {result['data']['match']}")
print(f"Confidence: {result['data']['confidence']}")

JavaScript

Face Find Example

javascript
async function imageToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

async function findFace(apiKey, imageFile, threshold = 0.5, limit = 10) {
  const url = "https://api.rivalistic.com/v1/face/find";
  
  const imageBase64 = await imageToBase64(imageFile);
  
  const payload = {
    database_name: "default",
    image_base64: imageBase64,
    threshold: threshold,
    limit: limit
  };
  
  const headers = {
    "x-api-key": apiKey,
    "Content-Type": "application/json"
  };
  
  const response = await fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(payload)
  });
  
  return await response.json();
}

// Usage
const apiKey = "riv_sh7mLX53C0wka5b65P5LoLKYJm6PaDUv";
const fileInput = document.getElementById('imageInput');
const file = fileInput.files[0];

findFace(apiKey, file, 0.4, 5)
  .then(result => console.log(result))
  .catch(error => console.error(error));

Face Enroll Example

javascript
async function enrollFace(apiKey, imageFile, metadata = null) {
  const url = "https://api.rivalistic.com/v1/face/enroll";
  
  const imageBase64 = await imageToBase64(imageFile);
  
  const payload = {
    database_name: "default",
    image_base64: imageBase64
  };
  
  if (metadata) {
    payload.metadata = metadata;
  }
  
  const headers = {
    "x-api-key": apiKey,
    "Content-Type": "application/json"
  };
  
  const response = await fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(payload)
  });
  
  return await response.json();
}

// Usage
const metadata = {
  name: "John Doe",
  employee_id: "EMP123",
  department: "IT"
};

enrollFace(apiKey, file, metadata)
  .then(result => console.log(result))
  .catch(error => console.error(error));

cURL

Face Find

bash
curl --location 'https://api.rivalistic.com/v1/face/find' \
--header 'x-api-key: riv_sh7mLX53C0wka5b65P5LoLKYJm6PaDUv' \
--header 'Content-Type: application/json' \
--data '{
  "database_name": "default",
  "image_base64": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...",
  "threshold": 0.4,
  "limit": 5
}'

Face Enroll

bash
curl --location 'https://api.rivalistic.com/v1/face/enroll' \
--header 'x-api-key: riv_sh7mLX53C0wka5b65P5LoLKYJm6PaDUv' \
--header 'Content-Type: application/json' \
--data '{
  "database_name": "default",
  "image_base64": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...",
  "metadata": {
    "name": "John Doe",
    "employee_id": "EMP123",
    "department": "IT"
  }
}'

Face Verify

bash
curl --location 'https://api.rivalistic.com/v1/face/verify' \
--header 'x-api-key: riv_sh7mLX53C0wka5b65P5LoLKYJm6PaDUv' \
--header 'Content-Type: application/json' \
--data '{
  "database_name": "default",
  "image_base64_1": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...",
  "image_base64_2": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD..."
}'

Error Handling Examples

Python with Error Handling

python
def safe_find_face(api_key, image_path, threshold=0.5, limit=10):
    try:
        result = find_face(api_key, image_path, threshold, limit)
        
        if 'error' in result:
            print(f"API Error: {result['error']}")
            return None
            
        return result
        
    except FileNotFoundError:
        print("Image file not found")
        return None
    except requests.exceptions.RequestException as e:
        print(f"Network error: {e}")
        return None
    except Exception as e:
        print(f"Unexpected error: {e}")
        return None

# Usage with error handling
result = safe_find_face(api_key, "path/to/image.jpg")
if result and result['data']:
    print(f"Found {len(result['data'])} matches")
else:
    print("No matches found or error occurred")

Dokumentasi API Rivalistic