Google Cloud reCAPTCHA Enterprise API client library for protecting websites and applications from fraud
—
Comprehensive management of reCAPTCHA keys for different platforms including web applications, Android apps, and iOS apps. Key management operations handle the full lifecycle from creation and configuration through updates, deletion, and migration from legacy reCAPTCHA versions.
Creates a new reCAPTCHA key with platform-specific settings. Keys can be configured for web, Android, or iOS platforms with appropriate security settings and domain/package restrictions.
def create_key(
request: CreateKeyRequest = None,
*,
parent: str = None,
key: Key = None,
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
metadata: Sequence[Tuple[str, str]] = ()
) -> Key:
"""
Creates a new reCAPTCHA Enterprise key.
Args:
request: The request object for creating a key
parent: Required. The name of the project in format 'projects/{project}'
key: Required. Key configuration and settings
retry: Retry configuration for the request
timeout: Timeout for the request in seconds
metadata: Additional metadata for the request
Returns:
Key: The created key with generated name and settings
Raises:
google.api_core.exceptions.InvalidArgument: If key configuration is invalid
google.api_core.exceptions.AlreadyExists: If key with same display name exists
google.api_core.exceptions.PermissionDenied: If insufficient permissions
"""from google.cloud import recaptchaenterprise
from google.cloud.recaptchaenterprise_v1.types import Key, WebKeySettings
client = recaptchaenterprise.RecaptchaEnterpriseServiceClient()
# Create a web key
web_settings = WebKeySettings(
allowed_domains=["example.com", "app.example.com"],
allow_amp_traffic=True,
integration_type=WebKeySettings.IntegrationType.SCORE,
challenge_security_preference=WebKeySettings.ChallengeSecurityPreference.USABILITY
)
key = Key(
display_name="My Website Key",
web_settings=web_settings,
labels={"environment": "production", "team": "security"}
)
request = recaptchaenterprise.CreateKeyRequest(
parent="projects/your-project-id",
key=key
)
created_key = client.create_key(request=request)
print(f"Created key: {created_key.name}")Retrieves all reCAPTCHA keys for a project with support for pagination and filtering.
def list_keys(
request: ListKeysRequest = None,
*,
parent: str = None,
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
metadata: Sequence[Tuple[str, str]] = ()
) -> ListKeysResponse:
"""
Get a list of keys in a project.
Args:
request: The request object for listing keys
parent: Required. The name of the project in format 'projects/{project}'
retry: Retry configuration for the request
timeout: Timeout for the request in seconds
metadata: Additional metadata for the request
Returns:
ListKeysResponse: List of keys with pagination information
Raises:
google.api_core.exceptions.PermissionDenied: If insufficient permissions
google.api_core.exceptions.InvalidArgument: If parent format is invalid
"""Retrieves detailed information about a specific reCAPTCHA key.
def get_key(
request: GetKeyRequest = None,
*,
name: str = None,
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
metadata: Sequence[Tuple[str, str]] = ()
) -> Key:
"""
Returns the specified key.
Args:
request: The request object for getting a key
name: Required. The name of the key in format 'projects/{project}/keys/{key}'
retry: Retry configuration for the request
timeout: Timeout for the request in seconds
metadata: Additional metadata for the request
Returns:
Key: The key configuration and settings
Raises:
google.api_core.exceptions.NotFound: If the key doesn't exist
google.api_core.exceptions.PermissionDenied: If insufficient permissions
"""Updates the configuration of an existing reCAPTCHA key.
def update_key(
request: UpdateKeyRequest = None,
*,
key: Key = None,
update_mask: FieldMask = None,
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
metadata: Sequence[Tuple[str, str]] = ()
) -> Key:
"""
Updates the specified key.
Args:
request: The request object for updating a key
key: Required. The key to update with new settings
update_mask: Optional. Field mask specifying which fields to update
retry: Retry configuration for the request
timeout: Timeout for the request in seconds
metadata: Additional metadata for the request
Returns:
Key: The updated key configuration
Raises:
google.api_core.exceptions.NotFound: If the key doesn't exist
google.api_core.exceptions.InvalidArgument: If update parameters are invalid
google.api_core.exceptions.PermissionDenied: If insufficient permissions
"""Permanently deletes a reCAPTCHA key.
def delete_key(
request: DeleteKeyRequest = None,
*,
name: str = None,
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
metadata: Sequence[Tuple[str, str]] = ()
) -> None:
"""
Deletes the specified key.
Args:
request: The request object for deleting a key
name: Required. The name of the key in format 'projects/{project}/keys/{key}'
retry: Retry configuration for the request
timeout: Timeout for the request in seconds
metadata: Additional metadata for the request
Raises:
google.api_core.exceptions.NotFound: If the key doesn't exist
google.api_core.exceptions.PermissionDenied: If insufficient permissions
google.api_core.exceptions.FailedPrecondition: If key is still in use
"""Migrates a key from reCAPTCHA v2 or v3 to reCAPTCHA Enterprise.
def migrate_key(
request: MigrateKeyRequest = None,
*,
name: str = None,
skip_billing_check: bool = None,
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
metadata: Sequence[Tuple[str, str]] = ()
) -> Key:
"""
Migrates an existing key from reCAPTCHA to reCAPTCHA Enterprise.
Args:
request: The request object for migrating a key
name: Required. The name of the key in format 'projects/{project}/keys/{key}'
skip_billing_check: Optional. Skip billing account check
retry: Retry configuration for the request
timeout: Timeout for the request in seconds
metadata: Additional metadata for the request
Returns:
Key: The migrated key configuration
Raises:
google.api_core.exceptions.NotFound: If the key doesn't exist
google.api_core.exceptions.FailedPrecondition: If migration requirements not met
google.api_core.exceptions.PermissionDenied: If insufficient permissions
"""Retrieves the secret key for a legacy reCAPTCHA key during migration.
def retrieve_legacy_secret_key(
request: RetrieveLegacySecretKeyRequest = None,
*,
key: str = None,
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
metadata: Sequence[Tuple[str, str]] = ()
) -> RetrieveLegacySecretKeyResponse:
"""
Get the secret key string for a legacy key.
Args:
request: The request object for retrieving secret key
key: Required. The public key name in format 'projects/{project}/keys/{key}'
retry: Retry configuration for the request
timeout: Timeout for the request in seconds
metadata: Additional metadata for the request
Returns:
RetrieveLegacySecretKeyResponse: Contains the legacy secret key
Raises:
google.api_core.exceptions.NotFound: If the key doesn't exist
google.api_core.exceptions.PermissionDenied: If insufficient permissions
google.api_core.exceptions.FailedPrecondition: If key is not legacy
"""class CreateKeyRequest:
"""Request message for creating a key."""
parent: str # Required. Project name in format 'projects/{project}'
key: Key # Required. Key configurationclass Key:
"""reCAPTCHA key configuration."""
name: str # Output only. Resource name
display_name: str # Human-readable display name
web_settings: WebKeySettings # Web platform settings
android_settings: AndroidKeySettings # Android platform settings
ios_settings: IOSKeySettings # iOS platform settings
labels: Dict[str, str] # Key-value labels
create_time: Timestamp # Output only. Creation time
testing_options: TestingOptions # Testing configuration
waf_settings: WafSettings # WAF integration settingsclass WebKeySettings:
"""Settings for web-based keys."""
allow_all_domains: bool # Allow all domains
allowed_domains: List[str] # Specific allowed domains
allow_amp_traffic: bool # Allow AMP traffic
integration_type: IntegrationType # Score vs checkbox integration
challenge_security_preference: ChallengeSecurityPreference # Security vs usability
class IntegrationType(Enum):
"""Web integration types."""
INTEGRATION_TYPE_UNSPECIFIED = 0
SCORE = 1 # Invisible reCAPTCHA with score
CHECKBOX = 2 # Traditional checkbox reCAPTCHA
INVISIBLE = 3 # Invisible reCAPTCHA
class ChallengeSecurityPreference(Enum):
"""Challenge security preferences."""
CHALLENGE_SECURITY_PREFERENCE_UNSPECIFIED = 0
USABILITY = 1 # Prefer user experience
BALANCE = 2 # Balance security and usability
SECURITY = 3 # Prefer security
class AndroidKeySettings:
"""Settings for Android app keys."""
allow_all_package_names: bool # Allow all package names
allowed_package_names: List[str] # Specific allowed package names
support_non_google_app_store_distribution: bool # Support non-Play Store apps
class IOSKeySettings:
"""Settings for iOS app keys."""
allow_all_bundle_ids: bool # Allow all bundle IDs
allowed_bundle_ids: List[str] # Specific allowed bundle IDs
apple_developer_id: AppleDeveloperId # Apple developer verification
class ExpressKeySettings:
"""Settings for reCAPTCHA Express keys."""
# Express settings for streamlined reCAPTCHA implementation
class AppleDeveloperId:
"""Apple developer ID for iOS key verification."""
private_key: str # Apple private key
key_id: str # Apple key ID
team_id: str # Apple team IDclass TestingOptions:
"""Testing configuration for development."""
testing_score: float # Fixed score for testing (0.0-1.0)
testing_challenge: TestingChallenge # Testing challenge behavior
class TestingChallenge(Enum):
"""Testing challenge options."""
TESTING_CHALLENGE_UNSPECIFIED = 0
NOCAPTCHA = 1 # No challenge
UNSOLVABLE_CHALLENGE = 2 # Unsolvable challenge
class WafSettings:
"""Web Application Firewall settings."""
waf_service: WafService # WAF service integration
waf_feature_set: WafFeatureSet # WAF feature set
class WafService(Enum):
"""WAF service providers."""
WAF_SERVICE_UNSPECIFIED = 0
CA = 1 # CA App Synthetic Monitor
FASTLY = 3 # Fastly
class WafFeatureSet(Enum):
"""WAF feature sets."""
WAF_FEATURE_SET_UNSPECIFIED = 0
CHALLENGE_PAGE = 1 # Challenge page
SESSION_TOKEN = 2 # Session token
ACTION_TOKEN = 3 # Action token
EXPRESS = 4 # Express modeclass ListKeysRequest:
"""Request message for listing keys."""
parent: str # Required. Project name
page_size: int # Optional. Maximum results per page
page_token: str # Optional. Pagination token
class ListKeysResponse:
"""Response message for listing keys."""
keys: List[Key] # The list of keys
next_page_token: str # Token for next page of results
class GetKeyRequest:
"""Request message for getting a key."""
name: str # Required. Key name
class UpdateKeyRequest:
"""Request message for updating a key."""
key: Key # Required. Key with updated values
update_mask: FieldMask # Optional. Fields to update
class DeleteKeyRequest:
"""Request message for deleting a key."""
name: str # Required. Key name
class MigrateKeyRequest:
"""Request message for migrating a key."""
name: str # Required. Key name
skip_billing_check: bool # Optional. Skip billing verification
class RetrieveLegacySecretKeyRequest:
"""Request message for retrieving legacy secret key."""
key: str # Required. Public key name
class RetrieveLegacySecretKeyResponse:
"""Response message containing legacy secret key."""
legacy_secret_key: str # The legacy secret key stringweb_settings = WebKeySettings(
allowed_domains=["example.com", "*.example.com"],
allow_amp_traffic=True,
integration_type=WebKeySettings.IntegrationType.SCORE,
challenge_security_preference=WebKeySettings.ChallengeSecurityPreference.BALANCE
)
key = Key(
display_name="Production Web Key",
web_settings=web_settings,
labels={"environment": "prod", "domain": "example.com"}
)android_settings = AndroidKeySettings(
allowed_package_names=["com.example.myapp"],
support_non_google_app_store_distribution=False
)
key = Key(
display_name="Android App Key",
android_settings=android_settings,
labels={"platform": "android", "version": "1.0"}
)apple_dev_id = AppleDeveloperId(
private_key="-----BEGIN PRIVATE KEY-----\n...",
key_id="ABC123DEF4",
team_id="DEF123ABC4"
)
ios_settings = IOSKeySettings(
allowed_bundle_ids=["com.example.myapp"],
apple_developer_id=apple_dev_id
)
key = Key(
display_name="iOS App Key",
ios_settings=ios_settings,
labels={"platform": "ios"}
)testing_options = TestingOptions(
testing_score=0.8, # Fixed score for testing
testing_challenge=TestingOptions.TestingChallenge.NOCAPTCHA
)
key = Key(
display_name="Development Key",
web_settings=web_settings,
testing_options=testing_options,
labels={"environment": "development"}
)# First, retrieve the legacy secret key
legacy_request = recaptchaenterprise.RetrieveLegacySecretKeyRequest(
key="projects/your-project/keys/your-legacy-key"
)
legacy_response = client.retrieve_legacy_secret_key(request=legacy_request)
print(f"Legacy secret key: {legacy_response.legacy_secret_key}")
# Then migrate the key
migrate_request = recaptchaenterprise.MigrateKeyRequest(
name="projects/your-project/keys/your-legacy-key",
skip_billing_check=False
)
migrated_key = client.migrate_key(request=migrate_request)
print(f"Migrated key: {migrated_key.name}")from google.api_core import exceptions
try:
key = client.create_key(request=request)
except exceptions.AlreadyExists as e:
print(f"Key with this display name already exists: {e}")
except exceptions.InvalidArgument as e:
print(f"Invalid key configuration: {e}")
except exceptions.FailedPrecondition as e:
print(f"Prerequisites not met (billing, API enablement): {e}")
try:
client.delete_key(name=key_name)
except exceptions.NotFound as e:
print(f"Key not found: {e}")
except exceptions.FailedPrecondition as e:
print(f"Key still in use, cannot delete: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-google-cloud-recaptcha-enterprise