I am trying to create ReCaptcha assessment using their REST API in my backend server.
From reading the documentation, I understand that the request body contains an instance of Assesment, but when I try to send a request, I receive the following error:
TypeError: Object of type Assessment is not JSON serializable
My code:
import requests
from google.cloud import recaptchaenterprise_v1
from google.cloud.recaptchaenterprise_v1 import Assessment
def create_assessment(project_id: str, recaptcha_site_key: str, token: str, recaptcha_action: str, apiKey:str):
# Create event object
event = recaptchaenterprise_v1.Event()
event.site_key = recaptcha_site_key
event.token = token
# Create assesment object
assessment = recaptchaenterprise_v1.Assessment()
assessment.event = event
# Set project name
project_name = "projects/"+project_id
response = requests.post(url="https://recaptchaenterprise.googleapis.com/v1/"+project_name+"/assessments?key="+apiKey, json=assessment)
return response
I tried to convert the assesment
to JSON using dumps()
, but I had no success.
I've also tried to write it as "skinny JSON" like so:
assessment = {
'event': {
'token': token,
'siteKey': recaptcha_site_key,
'expectedAction': 'LOGIN'
}
}
Even though I receive status code 200, it indicates that my request is MALFORMED, probably because I don't include some recaptchaenterprise_v1
objects that should be on the assesment
.
Try to use the CreateAssessmentRequest
to create the request instead, like so:
client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()
project_name = "projects/"+project_id
# Build the assessment request.
request = recaptchaenterprise_v1.CreateAssessmentRequest()
request.assessment = assessment
request.parent = project_name
response = client.create_assessment(request)
You can find a more complete code sample in GCP's documentation.