Apple DeviceCheck API

1.3.3 · active · verified Sun Apr 12

The `devicecheck` Python library provides a wrapper for the Apple DeviceCheck API, allowing developers to manage device state and assert app integrity to reduce fraudulent use of services. It supports both synchronous and asynchronous operations. The library is actively maintained, with regular releases, currently at version 1.3.3.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `DeviceCheck` client and validate a device token. It uses environment variables for sensitive Apple credentials, which is a recommended security practice. Remember to obtain `team_id`, `bundle_id`, `key_id`, and the `private_key` path from your Apple Developer account, and set `dev_environment` appropriately for your testing or production environment. The `device_token` must be generated by your iOS application on a physical device.

import os
from devicecheck import DeviceCheck

# Configure DeviceCheck client using environment variables for security
dc_client = DeviceCheck(
    team_id=os.environ.get("APPLE_TEAM_ID", ""),
    bundle_id=os.environ.get("APPLE_BUNDLE_ID", ""),
    key_id=os.environ.get("APPLE_KEY_ID", ""),
    private_key=os.environ.get("APPLE_PRIVATE_KEY_PATH", ""),
    dev_environment=bool(os.environ.get("DC_DEV_ENVIRONMENT", "False").lower() == "true"),
    # Set raise_on_error=True to get Python exceptions on API errors
    raise_on_error=True
)

# IMPORTANT: Replace with an actual device token generated by your iOS app
# For testing, you might use a mocked token if the library supports it via env vars.
device_token = os.environ.get("TEST_DEVICE_TOKEN", "YOUR_ACTUAL_DEVICE_TOKEN_HERE")

if not device_token:
    print("Error: TEST_DEVICE_TOKEN environment variable not set, or placeholder not replaced.")
    print("Please provide a valid device token from your iOS app for real testing.")
else:
    try:
        # Validate the device token
        validation_result = dc_client.validate_device_token(device_token)
        
        if validation_result.is_ok:
            print('Device is valid!')
            # Example: Query bits data if needed
            # bits_data = dc_client.query_two_bits(device_token)
            # print(f'Bit 0: {bits_data.bit0}, Bit 1: {bits_data.bit1}')
        else:
            print(f'Device validation failed: {validation_result.description}')

    except Exception as e:
        print(f"An error occurred during DeviceCheck operation: {e}")

view raw JSON →