Google Cloud reCAPTCHA Enterprise API client library for protecting websites and applications from fraud
npx @tessl/cli install tessl/pypi-google-cloud-recaptcha-enterprise@1.28.0Google Cloud reCAPTCHA Enterprise provides advanced protection for websites and applications against fraudulent activities including scraping, credential stuffing, automated account creation, and other malicious interactions. This enterprise-grade solution offers comprehensive fraud detection, assessment analysis, and configurable security policies with detailed metrics and analytics.
pip install google-cloud-recaptcha-enterprisefrom google.cloud import recaptchaenterpriseFor direct v1 API access:
from google.cloud import recaptchaenterprise_v1For specific client classes:
from google.cloud.recaptchaenterprise import RecaptchaEnterpriseServiceClient
from google.cloud.recaptchaenterprise import RecaptchaEnterpriseServiceAsyncClientfrom google.cloud import recaptchaenterprise
from google.cloud.recaptchaenterprise_v1.types import Assessment, Event
# Initialize the client
client = recaptchaenterprise.RecaptchaEnterpriseServiceClient()
# Create an assessment to analyze user interaction
project_path = f"projects/{project_id}"
# Create event details for assessment
event = Event(
site_key=site_key,
user_agent="Mozilla/5.0...",
user_ip_address="192.168.1.1",
expected_action="login"
)
# Create assessment request
assessment = Assessment(event=event)
request = recaptchaenterprise.CreateAssessmentRequest(
parent=project_path,
assessment=assessment
)
# Execute assessment
response = client.create_assessment(request=request)
# Analyze results
if response.risk_analysis.score > 0.5:
print("User interaction appears legitimate")
# Allow action
else:
print("Potential fraud detected")
# Block or challenge userThe reCAPTCHA Enterprise API follows Google Cloud's standard client library patterns with several key components:
RecaptchaEnterpriseServiceClient) and asynchronous (RecaptchaEnterpriseServiceAsyncClient) interfacesThe client handles authentication, retries, and error management automatically while providing fine-grained control over security policies and threat responses.
Core fraud detection functionality that analyzes user interactions and provides risk scores, token validation, and detailed threat analysis including account defender assessments and fraud prevention signals.
def create_assessment(request: CreateAssessmentRequest) -> Assessment: ...
def annotate_assessment(request: AnnotateAssessmentRequest) -> AnnotateAssessmentResponse: ...Comprehensive management of reCAPTCHA keys for different platforms (web, Android, iOS) including creation, configuration, updates, deletion, and migration from legacy reCAPTCHA versions.
def create_key(request: CreateKeyRequest) -> Key: ...
def list_keys(request: ListKeysRequest) -> ListKeysResponse: ...
def get_key(request: GetKeyRequest) -> Key: ...
def update_key(request: UpdateKeyRequest) -> Key: ...
def delete_key(request: DeleteKeyRequest) -> None: ...
def migrate_key(request: MigrateKeyRequest) -> Key: ...
def retrieve_legacy_secret_key(request: RetrieveLegacySecretKeyRequest) -> RetrieveLegacySecretKeyResponse: ...Advanced security rules that automatically respond to detected threats with configurable actions including allow, block, substitute, and redirect responses based on risk analysis and custom conditions.
def create_firewall_policy(request: CreateFirewallPolicyRequest) -> FirewallPolicy: ...
def list_firewall_policies(request: ListFirewallPoliciesRequest) -> ListFirewallPoliciesResponse: ...
def get_firewall_policy(request: GetFirewallPolicyRequest) -> FirewallPolicy: ...
def update_firewall_policy(request: UpdateFirewallPolicyRequest) -> FirewallPolicy: ...
def delete_firewall_policy(request: DeleteFirewallPolicyRequest) -> None: ...
def reorder_firewall_policies(request: ReorderFirewallPoliciesRequest) -> ReorderFirewallPoliciesResponse: ...Management of IP address overrides for testing and development environments, allowing specific IP addresses to be treated differently during reCAPTCHA assessments.
def add_ip_override(request: AddIpOverrideRequest) -> AddIpOverrideResponse: ...
def remove_ip_override(request: RemoveIpOverrideRequest) -> RemoveIpOverrideResponse: ...
def list_ip_overrides(request: ListIpOverridesRequest) -> ListIpOverridesResponse: ...Advanced account protection features including related account group analysis, membership tracking, and search capabilities for detecting coordinated fraud attempts and abuse patterns.
def list_related_account_groups(request: ListRelatedAccountGroupsRequest) -> ListRelatedAccountGroupsResponse: ...
def list_related_account_group_memberships(request: ListRelatedAccountGroupMembershipsRequest) -> ListRelatedAccountGroupMembershipsResponse: ...
def search_related_account_group_memberships(request: SearchRelatedAccountGroupMembershipsRequest) -> SearchRelatedAccountGroupMembershipsResponse: ...Comprehensive reporting and analytics for monitoring reCAPTCHA usage, effectiveness, performance metrics, score distributions, and challenge completion rates.
def get_metrics(request: GetMetricsRequest) -> Metrics: ...class Assessment:
"""Assessment of user interaction for fraud detection."""
name: str
event: Event
risk_analysis: RiskAnalysis
token_properties: TokenProperties
account_defender_assessment: AccountDefenderAssessment
fraud_prevention_assessment: FraudPreventionAssessment
phone_fraud_assessment: PhoneFraudAssessment
firewall_policy_assessment: FirewallPolicyAssessment
class Event:
"""User event details for assessment."""
token: str
site_key: str
user_agent: str
user_ip_address: str
expected_action: str
hashed_account_id: bytes
express: bool
requested_uri: str
waf_token_assessment: bool
ja3: str
headers: List[str]
firewall_policy_evaluation: bool
class RiskAnalysis:
"""Risk analysis results from assessment."""
score: float
reasons: List[str]
extended_verdict: ExtendedVerdict
class TokenProperties:
"""Properties of the reCAPTCHA token."""
valid: bool
invalid_reason: str
hostname: str
android_package_name: str
ios_bundle_id: str
action: str
create_time: Timestampclass Key:
"""reCAPTCHA key configuration."""
name: str
display_name: str
web_settings: WebKeySettings
android_settings: AndroidKeySettings
ios_settings: IOSKeySettings
labels: Dict[str, str]
create_time: Timestamp
testing_options: TestingOptions
waf_settings: WafSettings
class WebKeySettings:
"""Settings for web-based keys."""
allow_all_domains: bool
allowed_domains: List[str]
allow_amp_traffic: bool
integration_type: str
challenge_security_preference: str
class AndroidKeySettings:
"""Settings for Android app keys."""
allow_all_package_names: bool
allowed_package_names: List[str]
support_non_google_app_store_distribution: bool
class IOSKeySettings:
"""Settings for iOS app keys."""
allow_all_bundle_ids: bool
allowed_bundle_ids: List[str]
apple_developer_id: AppleDeveloperIdclass RecaptchaEnterpriseServiceClient:
"""Synchronous client for reCAPTCHA Enterprise API operations."""
def __init__(self, *, credentials=None, transport=None, client_options=None, client_info=None): ...
def create_assessment(self, request=None, **kwargs) -> Assessment: ...
def annotate_assessment(self, request=None, **kwargs) -> AnnotateAssessmentResponse: ...
# ... all other synchronous API methods
class RecaptchaEnterpriseServiceAsyncClient:
"""Asynchronous client for reCAPTCHA Enterprise API operations."""
def __init__(self, *, credentials=None, transport=None, client_options=None, client_info=None): ...
async def create_assessment(self, request=None, **kwargs) -> Assessment: ...
async def annotate_assessment(self, request=None, **kwargs) -> AnnotateAssessmentResponse: ...
# ... all other asynchronous API methodsclass FirewallPolicy:
"""Firewall policy configuration."""
name: str
description: str
path: str
condition: str
actions: List[FirewallAction]
class FirewallAction:
"""Action to take when firewall conditions match."""
allow: AllowAction
block: BlockAction
substitute: SubstituteAction
redirect: RedirectAction
set_header: SetHeaderActionclass Timestamp:
"""Google protobuf timestamp type for representing time."""
seconds: int # Seconds since Unix epoch
nanos: int # Nanoseconds within the second
class FieldMask:
"""Google protobuf field mask for specifying fields to update."""
paths: List[str] # Field paths in dot notation (e.g., "display_name", "web_settings.allowed_domains")The client supports standard Google Cloud authentication patterns:
# Using Application Default Credentials
client = recaptchaenterprise.RecaptchaEnterpriseServiceClient()
# Using service account key file
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
"/path/to/service-account-key.json"
)
client = recaptchaenterprise.RecaptchaEnterpriseServiceClient(credentials=credentials)
# Custom endpoint configuration
client = recaptchaenterprise.RecaptchaEnterpriseServiceClient(
client_options={"api_endpoint": "https://custom-endpoint.googleapis.com"}
)The library integrates with Google API Core for comprehensive error handling:
from google.api_core import exceptions
try:
response = client.create_assessment(request=request)
except exceptions.GoogleAPICallError as e:
print(f"API call failed: {e}")
except exceptions.InvalidArgument as e:
print(f"Invalid request parameters: {e}")
except exceptions.PermissionDenied as e:
print(f"Insufficient permissions: {e}")Common exceptions include:
InvalidArgument: Malformed request parametersPermissionDenied: Insufficient IAM permissionsNotFound: Requested resource doesn't existAlreadyExists: Resource creation conflictsResourceExhausted: Rate limits or quotas exceeded