🎉 Unlimited Free KYC - Forever!!

Identity Verification
API Reference
Face Match

Face Match API

The Face Match API allows you to compare two facial images to determine if they belong to the same person. This API can be used for identity verification, access control, or user authentication.

  • Base URL: https://verification.didit.me
  • Endpoint: /v2/face-match/
  • Authentication: Client Token (Bearer Token)
⚠️

The authentication endpoint uses a different base URL than the API endpoints. Ensure you use the correct URLs to avoid connectivity issues.

This API requires a Pro Plan subscription and has an associated cost per call. Results won't be saved in your console. For pricing details, visit our API Pricing page.

Process Overview

Follow these steps to submit face images for comparison:

Step 1: Authenticate

Obtain a valid access_token by following the Authentication documentation. This token is required in the Authorization header of your request.

ℹ️

The access_token is valid for 24 hours. You only need to re-authenticate once it expires.

Step 2: Prepare Request Parameters

ParameterTypeRequired?DescriptionExample Value
user_imagefileYesUser's face image to be verified (JPEG, PNG, or WebP).Binary image file
ref_imagefileYesReference image to compare against (JPEG, PNG, or WebP).Binary image file
optionsjsonNoCustomization options for face match verification.See options details below

Options Object

The options parameter allows you to customize the face match verification thresholds:

OptionTypeRequired?DescriptionDefault Value
face_match_score_decline_thresholdnumberNoResults with face match score below this will be declined. Must be between 0-100.30

Image Requirements

  • Images must be in JPEG, PNG, or WebP format
  • Minimum resolution: 480x480 pixels
  • Maximum file size: 5MB per image
  • Face must be clearly visible, well-lit, and unobstructed
  • If more than one face is present, the API will use the largest face in the image

Step 3: Send the Request

Make a POST request to /v2/face-match with the prepared parameters and include the access_token obtained in step 1 in the header.

Example Request

POST /v2/face-match HTTP/1.1
Host: verification.didit.me
Content-Type: multipart/form-data
Authorization: Bearer {access_token}
 
--boundary
Content-Disposition: form-data; name="user_image"; filename="user.jpg"
Content-Type: image/jpeg
 
[Binary image data]
--boundary
Content-Disposition: form-data; name="ref_image"; filename="reference.jpg"
Content-Type: image/jpeg
 
[Binary image data]
--boundary
Content-Disposition: form-data; name="options"
Content-Type: application/json
 
{
  "face_match_score_decline_threshold": 40,
}
--boundary--

Response

The response provides detailed information about the face match results, including similarity score and any warnings.

Example Response

{
  "request_id": "11111111-2222-3333-4444-555555555555",
  "face_match": {
    "status": "In Review",
    "score": 65.43,
    "source_image": "https://example.com/source-image.jpg",
    "target_image": "https://example.com/target-image.jpg",
    "warnings": [
      {
        "risk": "LOW_FACE_MATCH_SIMILARITY",
        "additional_data": null,
        "log_type": "warning",
        "short_description": "Low face match similarity",
        "long_description": "The facial features of the provided image don't closely match the reference image, suggesting a potential identity mismatch."
      }
    ]
  },
  "created_at": "2024-07-24T08:54:25.443172Z"
}

Response Fields

FieldTypeDescription
request_idstringUnique identifier for the API request.
face_match.statusstringFace match result status ("Approved", "Declined" or "In Review").
face_match.scorenumberSimilarity score between the two faces (0-100).
face_match.source_imagestringTemporary URL to the processed source image.
face_match.target_imagestringTemporary URL to the processed target image.
face_match.warningsarrayArray of warning objects related to the face match process.
created_atstringTimestamp when the request was created (ISO 8601 format).

The image URLs in the response are temporary and will expire after 60 minutes.

Error Handling

Status CodeErrorDescription
400Bad RequestInvalid parameters or missing required files.
401UnauthorizedInvalid or missing access_token.
403ForbiddenNot authorized to access this API or insufficient subscription plan.

Example Error Response

{
  "detail": "Invalid image format. Supported formats: JPEG, PNG, WebP."
}

Code Examples

async function submitFaceMatch(accessToken: string, userImageFile: File, referenceImageFile: File, options = null) {
 
  const url = `https://verification.didit.me/v2/face-match`;
 
  const formData = new FormData();
  formData.append('user_image', userImageFile);
  formData.append('ref_image', referenceImageFile);
 
  // Add options if provided
  if (options) {
    formData.append('options', JSON.stringify(options));
  }
 
  const requestOptions = {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${accessToken}`
    },
    body: formData
  };
 
  try {
    const response = await fetch(url, requestOptions);
 
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.detail || errorData.error?.message || 'Unknown error occurred');
    }
 
    return await response.json();
  } catch (error) {
    console.error('Error in face match:', error);
    throw error;
  }
}
 
// Example usage
async function performFaceMatch() {
  try {
    // 1. Get client token (implement based on auth documentation)
    const token = await getClientToken();
 
    // 2. Get image files (from file input or other source)
    const userImageFile = document.getElementById('user-image-input').files[0];
    const referenceImageFile = document.getElementById('reference-image-input').files[0];
 
    // 3. Custom options (optional)
    const options = {
      face_match_score_decline_threshold: 35,
    };
 
    // 4. Submit face match
    const result = await submitFaceMatch(
      token.access_token,
      userImageFile,
      referenceImageFile,
      options
    );
 
    console.log('Face match result:', result);
    return result;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}
import requests
import json
 
def submit_face_match(access_token: str, user_image_file: bytes, ref_image_file: bytes, options=None):
    """
    Submit two facial images for comparison.
 
    Args:
        access_token (str): The access token for authorization.
        user_image_file (file): The user's face image file object.
        ref_image_file (file): The reference face image file object.
        options (dict, optional): Custom threshold options for face matching.
 
    Returns:
        dict: The face match results.
    """
    url = "https://verification.didit.me/v2/face-match"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }
    files = {
        "user_image": user_image_file,
        "ref_image": ref_image_file
    }
 
    # Add options if provided
    data = {}
    if options:
        data['options'] = json.dumps(options)
 
    try:
        response = requests.post(url, headers=headers, files=files, data=data)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error in face match: {e}")
        if hasattr(e, 'response') and e.response:
            print(f"Response: {e.response.text}")
        raise
 
# Example usage
def perform_face_match():
    try:
        # 1. Get client token (implement based on auth documentation)
        token = get_client_token()
 
        # 2. Custom options (optional)
        options = {
            "face_match_score_decline_threshold": 35,
        }
 
        # 3. Get image files (from file input or other source)
        with open("user_image.jpg", "rb") as user_img, open("ref_image.jpg", "rb") as ref_img:
            # 4. Submit face match
            result = submit_face_match(
                token["access_token"],
                user_img,
                ref_img,
                options
            )
 
        print('Face match result:', result)
        return result
    except Exception as e:
        print(f"Error: {e}")
        raise

Best Practices

  1. Image Quality: Use high-quality, well-lit images for more accurate results.
  2. Face Positioning: Ensure the face is clearly visible and centered in the frame.
  3. Face Coverage: Face should occupy at least 20% of the image area.
  4. Error Handling: Implement proper error handling to manage cases where face detection fails.
  5. Threshold Setting: Configure your verification settings or use the options parameter to set appropriate similarity thresholds based on your security requirements.