Google Cloud reCAPTCHA Enterprise API client library
The `google-cloud-recaptcha-enterprise` client library provides Python access to the Google Cloud reCAPTCHA Enterprise API. reCAPTCHA Enterprise protects websites and mobile applications from fraudulent activity, spam, and abuse by using advanced risk analysis and machine learning to distinguish between legitimate users and bots. The library is actively maintained as part of the `google-cloud-python` monorepo and is currently at version 1.31.0, with ongoing releases for features and bug fixes across the Google Cloud client libraries.
Warnings
- breaking All classic reCAPTCHA keys must be migrated to a Google Cloud project by the end of 2025. Failure to migrate will result in keys becoming invalid and the service being unavailable.
- gotcha When creating API keys for backend reCAPTCHA Enterprise verification, avoid restricting the key by HTTP referrers. Such restrictions will silently block server-side requests, leading to verification failures.
- gotcha The first 10,000 reCAPTCHA Enterprise assessments per month are free. Exceeding this quota without enabled billing will cause `create_assessment` requests to fail.
- gotcha The `BROWSER_ERROR` token response indicates a client-side network failure or timeout, not a backend issue.
- deprecated Support for Python versions older than 3.9 has been dropped by various Google Cloud Python libraries in recent releases (e.g., pandas-gbq and bigquery-magics in the provided GitHub releases). While the `google-cloud-recaptcha-enterprise` PyPI metadata currently specifies `>=3.9`, older Python versions may lead to compatibility issues with other ecosystem libraries or future updates.
Install
-
pip install google-cloud-recaptcha-enterprise
Imports
- RecaptchaEnterpriseServiceClient
from google.cloud import recaptchaenterprise_v1 client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()
- types
from google.cloud.recaptchaenterprise_v1 import types
Quickstart
import os
from google.cloud import recaptchaenterprise_v1
from google.cloud.recaptchaenterprise_v1 import types
def create_assessment_sample(
project_id: str,
site_key: str,
token: str,
action: str,
user_ip: str = None,
user_agent: str = None,
) -> None:
"""Creates an assessment to analyze the risk of a UI action.
Args:
project_id: Your Google Cloud project ID.
site_key: The reCAPTCHA key associated with the site or app.
token: The user's response token for which you want to receive a reCAPTCHA score.
action: The user-initiated action that you specified for action in the grecaptcha.enterprise.execute() call.
user_ip: (Optional) The IP address of the user sending a request to your backend.
user_agent: (Optional) The user agent in the request from the user's device.
"""
client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()
event = types.Event()
event.site_key = site_key
event.token = token
event.expected_action = action
if user_ip:
event.user_ip_address = user_ip
if user_agent:
event.user_agent = user_agent
assessment = types.Assessment()
assessment.event = event
project_name = client.project_path(project_id)
try:
response = client.create_assessment(parent=project_name, assessment=assessment)
# Check if the token is valid.
if not response.token_properties.valid:
print(
"The create_assessment() call failed because the token was invalid with the following reason: "
f"{response.token_properties.invalid_reason}"
)
return
# Check if the expected action was executed.
if response.token_properties.action == action:
# Get the risk score and the reason(s).
# For more information on interpreting the assessment,
# see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
print(f"The reCAPTCHA score for this token is: {response.risk_analysis.score}")
for reason in response.risk_analysis.reasons:
print(f" Reason: {reason.name}")
else:
print(
"The action attribute in your reCAPTCHA tag does not match the action you are expecting to score."
f"Expected: {action}, Actual: {response.token_properties.action}"
)
except Exception as e:
print(f"Error creating assessment: {e}")
# Example Usage (replace with your actual project_id, site_key, and token)
if __name__ == "__main__":
project_id = os.environ.get('GOOGLE_CLOUD_PROJECT_ID', 'your-project-id')
# The site key generated for your reCAPTCHA Enterprise site/app
site_key = os.environ.get('RECAPTCHA_ENTERPRISE_SITE_KEY', 'your-site-key')
# The token obtained from the client-side reCAPTCHA execution
token = os.environ.get('RECAPTCHA_ENTERPRISE_TOKEN', 'your-recaptcha-token')
action = 'login'
user_ip = '192.0.2.1' # Example IP, use actual user's IP
user_agent = 'Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.5481.65 Mobile Safari/537.36'
if project_id == 'your-project-id' or site_key == 'your-site-key' or token == 'your-recaptcha-token':
print("Please set GOOGLE_CLOUD_PROJECT_ID, RECAPTCHA_ENTERPRISE_SITE_KEY, and RECAPTCHA_ENTERPRISE_TOKEN environment variables or replace placeholders in the script.")
else:
create_assessment_sample(project_id, site_key, token, action, user_ip, user_agent)