1

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.

Pexers
  • 953
  • 1
  • 7
  • 20
Nitcha
  • 45
  • 4

1 Answers1

1

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.

Pexers
  • 953
  • 1
  • 7
  • 20
  • Thanks, I followed GCP documentation and used service account for authentication... But I now have another issue - I always get 0 score and the error "The CreateAssessment call failed because the token was invalid for for the following reasons: InvalidReason.MALFORMED" I used the write project_id, site_key and token (but not sure what to write on the action variable) – Nitcha Dec 11 '22 at 15:59
  • 1
    This means that the token you're using is invalid, or has expired. I can't help you much more giving the information you provided. If you found my answer helpful, please consider marking it as 'Accepted', thank you! :) – Pexers Dec 11 '22 at 16:21