🎉 Unlimited Free KYC - Forever!!

Identity Verification
API Reference
Age Estimation

Age Estimation API

The Age Estimation API allows you to estimate a person's age based on facial analysis. This API can be used for age verification, demographic analysis, or personalized user experiences. Additionally, we perform a passive liveness test to ensure the submitted image is of a real person and not a spoof attempt.

  • Base URL: https://verification.didit.me
  • Endpoint: /v2/age-estimation/
  • 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 age estimation:

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 (JPEG, PNG, or WebP)Binary image file
optionsjsonNoCustomization options for age estimation and liveness verificationSee options details below

Options Object

The options parameter allows you to customize the age estimation and liveness verification thresholds:

OptionTypeRequired?DescriptionDefault Value
face_liveness_score_decline_thresholdnumberNoResults with liveness score below this will be declined. Must be between 0-100.30
age_estimation_decline_thresholdnumberNoResults with estimated age below this will be declined. Must be between 1-120.18

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/age-estimation/ with the prepared parameters and include the access_token obtained in step 1 in the header.

Example Request

POST /v2/age-estimation/ 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="options"
Content-Type: application/json
 
{
  "face_liveness_score_decline_threshold": 35,
  "age_estimation_decline_threshold": 21,
}
--boundary--

Response

The response provides detailed information about the age estimation results, including the estimated age and confidence score.

Example Response

{
  "request_id": "11111111-2222-3333-4444-555555555555",
  "liveness": {
    "status": "Approved",
    "method": "PASSIVE",
    "score": 89.92,
    "reference_image": "https://example.com/reference.jpg",
    "video_url": "https://example.com/video.mp4",
    "age_estimation": 24.3,
    "warnings": [
      {
        "risk": "LOW_LIVENESS_SCORE",
        "additional_data": null,
        "log_type": "information",
        "short_description": "Low liveness score",
        "long_description": "The liveness check resulted in a low score, indicating potential use of non-live facial representations or poor-quality biometric data."
      }
    ]
  },
  "created_at": "2024-07-24T08:54:25.443172Z"
}

Response Fields

FieldTypeDescription
request_idstringUnique identifier for the API request
liveness.statusstringLiveness check status (Approved, Declined)
liveness.methodstringMethod used for liveness detection (PASSIVE)
liveness.scorenumberConfidence score for the liveness check (0-100)
liveness.reference_imagestringURL to the reference image used
liveness.video_urlstringURL to the video if applicable
liveness.age_estimationnumberEstimated age in years (decimal value)
liveness.warningsarrayArray of warning objects with risk levels and descriptions
created_atstringTimestamp when the request was created

The image URL in the response is 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

{
  "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 submitAgeEstimation(accessToken, userImageFile, options = null) {
  const url = `https://verification.didit.me/v2/age-estimation/`;
 
  // Create a FormData instance
  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.error?.message || errorData.detail || 'Unknown error occurred');
    }
 
    return await response.json();
  } catch (error) {
    console.error('Error in age estimation:', error);
    throw error;
  }
}
 
// Example usage
async function performAgeEstimation() {
  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 = {
      face_liveness_score_decline_threshold: 35,
      age_estimation_decline_threshold: 21,
    };
 
    // 4. Submit age estimation
    const result = await submitAgeEstimation(
      token.access_token,
      userImageFile,
      options
    );
 
    console.log('Age estimation result:', result);
    console.log(`Estimated age: ${result.liveness.age_estimation} years`);
 
    return result;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}
import requests
import json
 
def submit_age_estimation(access_token, user_image_file, options=None):
    """
    Submit a facial image for age estimation.
 
    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 thresholds.
 
    Returns:
        dict: The age estimation results.
    """
    url = "https://verification.didit.me/v2/age-estimation/"
 
    headers = {
        "Authorization": f"Bearer {access_token}"
    }
 
    files = {
        "user_image": user_image_file
    }
 
    # Prepare data dictionary for options
    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 age estimation: {e}")
        if hasattr(e, 'response') and e.response:
            print(f"Response: {e.response.text}")
        raise
 
# Example usage
def perform_age_estimation():
    try:
        # 1. Get client token (implement based on auth documentation)
        token = get_client_token()
 
        # 2. Custom options (optional)
        options = {
            "face_liveness_score_decline_threshold": 35,
            "age_estimation_decline_threshold": 21,
        }
 
        # 3. Get image file (from file input or other source)
        with open("user_image.jpg", "rb") as user_img:
            # 4. Submit age estimation
            result = submit_age_estimation(
                token["access_token"],
                user_img,
                options
            )
 
        print("Age estimation result:", result)
        print(f"Estimated age: {result['liveness']['age_estimation']} years")
 
        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 Configuration: Use the options parameter to customize verification thresholds:
    • Set face_liveness_score_decline_threshold to balance security and user experience.
    • Configure age_estimation_decline_threshold based on your specific age verification requirements.
    • Adjust thresholds based on the level of strictness required for your application.

Accuracy Considerations

  • Age estimation is typically accurate within ±3.5 years for most age ranges.
  • Accuracy is best for ages 16-60.
  • Extreme lighting conditions, unusual angles, or facial coverings may affect accuracy.
  • Consider setting wider age boundaries for edge cases.