🎉 Unlimited Free KYC - Forever!!

Identity Verification
API Reference
Face Search

Face Search API

The Face Search API allows you to search for matches of a given face across all previously approved verification sessions in your account. This can be used to detect duplicate users, find returning customers, or enhance fraud prevention.

  • Base URL: https://verification.didit.me
  • Endpoint: /v2/face-search/
  • 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 (opens in a new tab).

Process Overview

Follow these steps to submit a face image for searching:

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_imagefileYesFace image to search for matches (JPEG, PNG, or WebP).Binary image file
optionsjsonNoCustomization options for face searchSee options details below

Options Object

The options parameter allows you to customize the face search process:

OptionTypeRequired?DescriptionDefault Value
similarity_thresholdnumberNoMinimum similarity percentage required to consider a face as a match. Must be between 0-100.70

Image Requirements

  • Images must be in JPEG, PNG, or WebP format
  • Minimum resolution: 480x480 pixels
  • Maximum file size: 5MB
  • Face must be clearly visible, well-lit, and unobstructed
  • Only one face should be present in the image

Step 3: Send the Request

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

Example Request

POST /v2/face-search/ 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="search.jpg"
Content-Type: image/jpeg
 
[Binary image data]
--boundary
Content-Disposition: form-data; name="options"
Content-Type: application/json
 
{
  "similarity_threshold": 75
}
--boundary--

Response

The response provides detailed information about the face search results, including potential matches and similarity scores.

Example Response

{
  "request_id": "11111111-2222-3333-4444-555555555555",
  "face_search": {
    "status": "Approved",
    "total_matches": 3,
    "matches": [
      {
        "session_id": "session-789012",
        "similarity": 96.8,
        "vendor_data": "user-555",
        "verification_date": "2024-07-15T10:23:45.123Z",
        "user_details": {
          "name": "John Smith",
          "document_type": "Passport",
          "document_number": "XXXXXXXX"
        },
        "match_image_url": "https://example.com/face/789012.jpg"
      },
      {
        "session_id": "session-345678",
        "similarity": 82.4,
        "vendor_data": "user-777",
        "verification_date": "2024-06-20T15:17:32.789Z",
        "user_details": {
          "name": "John A Smith",
          "document_type": "Driver's License",
          "document_number": "XXXXXXXX"
        },
        "match_image_url": "https://example.com/face/345678.jpg"
      },
      {
        "session_id": "session-234567",
        "similarity": 71.2,
        "vendor_data": "user-999",
        "verification_date": "2024-05-10T09:45:22.456Z",
        "user_details": {
          "name": "Jonathan Smith",
          "document_type": "ID Card",
          "document_number": "XXXXXXXX"
        },
        "match_image_url": "https://example.com/face/234567.jpg"
      }
    ],
    "warnings": [
      {
        "risk": "LOW_QUALITY_SEARCH_IMAGE",
        "additional_data": null,
        "log_type": "information",
        "short_description": "Low quality search image",
        "long_description": "The image used for searching has low quality, which may reduce the accuracy of matching results."
      }
    ]
  },
  "created_at": "2024-07-24T08:54:25.443172Z"
}

Response Fields

FieldTypeDescription
request_idstringUnique identifier for the API request.
face_search.statusstringFace search status (Approved, Declined).
face_search.total_matchesnumberTotal number of matches found.
face_search.matchesarrayArray of matching face records.
face_search.matches[].session_idstringSession ID where the match was found.
face_search.matches[].similaritynumberSimilarity score between the search face and the match (0-100).
face_search.matches[].vendor_datastringVendor data associated with the matched session.
face_search.matches[].verification_datestringTimestamp when the matched session was verified.
face_search.matches[].user_detailsobjectUser details from the matched session.
face_search.matches[].match_image_urlstringTemporary URL to the matched face image.
face_search.warningsarrayArray of warning objects related to the face search 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.
404Not FoundResource not found.

Example Error Response

{
  "error": {
    "code": "INVALID_IMAGE",
    "message": "No face detected in the image"
  }
}

Common Error Codes

Error CodeDescription
INVALID_IMAGENo face or multiple faces detected in the image.
PROCESSING_ERRORError processing the image.
INSUFFICIENT_QUALITYImage quality is too low for accurate analysis.

Code Examples

async function submitFaceSearch(accessToken, userImageFile, options = null) {
  const url = `https://verification.didit.me/v2/face-search/`;
 
  const formData = new FormData();
  formData.append('user_image', userImageFile);
 
  // 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 search:', error);
    throw error;
  }
}
 
// Example usage
async function performFaceSearch() {
  try {
    // 1. Get client token (implement based on auth documentation)
    const token = await getClientToken();
 
    // 2. Get image file (from file input or other source)
    const userImageFile = document.getElementById('user-image-input').files[0];
 
    // 3. Custom options (optional)
    const options = {
      similarity_threshold: 75 // Customize the similarity threshold (default is 70)
    };
 
    // 4. Submit face search
    const result = await submitFaceSearch(
      token.access_token,
      userImageFile,
      options
    );
 
    console.log('Face search results:', result);
 
    // Display matches if found
    if (result.face_search.total_matches > 0) {
      console.log(`Found ${result.face_search.total_matches} potential matches`);
      result.face_search.matches.forEach(match => {
        console.log(`Match with similarity: ${match.similarity}%, User: ${match.vendor_data}`);
      });
    } else {
      console.log('No matches found');
    }
 
    return result;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}
import requests
import json
 
def submit_face_search(access_token: str, user_image_file: bytes, options=None):
    """
    Submit a facial image for searching across previously verified users.
 
    Args:
        access_token (str): The access token for authentication.
        user_image_file (file): The user's face image file object.
        options (dict, optional): Customization options for face search.
 
    Returns:
        dict: The face search results.
    """
    url = "https://verification.didit.me/v2/face-search/"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }
    files = {
        "user_image": user_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 search: {e}")
        if hasattr(e, 'response') and e.response:
            print(f"Response: {e.response.text}")
        raise
 
# Example usage
def perform_face_search():
    try:
        # 1. Get client token (implement based on auth documentation)
        token = get_client_token()
 
        # 2. Custom options (optional)
        options = {
            "similarity_threshold": 75  # Customize the similarity threshold (default is 70)
        }
 
        # 3. Get image file (from file input or other source)
        with open("user_image.jpg", "rb") as user_img:
            # 4. Submit face search
            result = submit_face_search(
                token["access_token"],
                user_img,
                options
            )
 
        print('Face search results:', result)
 
        # Display matches if found
        if result["face_search"]["total_matches"] > 0:
            print(f"Found {result['face_search']['total_matches']} potential matches")
            for match in result["face_search"]["matches"]:
                print(f"Match with similarity: {match['similarity']}%, User: {match['vendor_data']}")
        else:
            print('No matches found')
 
        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 search 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. Similarity Threshold Configuration:
    • Use the options.similarity_threshold parameter to adjust the minimum similarity percentage required for a match.
    • Set higher thresholds (e.g., 80-90) for more strict matching with fewer false positives.
    • Set lower thresholds (e.g., 60-70) for more lenient matching that may catch more potential matches but with more false positives.
    • Adjust based on your specific use case and risk tolerance.
  5. Privacy Considerations: Ensure you have proper user consent for facial recognition and facial database searching.