Python error formatting an AWS lambda request

Viewed 757

I have to call using boto3 an AWS lambda. I do:

client = boto3.client("lambda")

dtime1 = str(datetime.datetime.now())
#After some computations
dtime2 = str(datetime.datetime.now())

elapsed =  time.time() - start_time

payload = {"key_id":"1",
        "data_start":dtime1,
        "data_stop":dtime2,
        "elapsed_t": int(elapsed)}

r = client.invoke(
            FunctionName='mylambda',
            InvocationType='RequestResponse',
            Payload=bytes(str(payload), 'utf-8')
        )

print(r.read())

but when i run it an error occur:

"An error occurred (InvalidRequestContentException) when calling the Invoke operation: Could not parse request body into json: Unexpected character (''' (code 39)): was expecting double-quote to start field name\n at [Source: [B@4cb02e4e; line: 1, column: 3]"

How can I resolve my issue?

Thanks in advance

2 Answers

All the official documentation I've seen on passing a payload in a Lambda invocation has been missing or incorrect. This is what has worked for me:

# Construct a dict object
payload = {"key": "value"}

# Invoke the Lambda function, passing the payload
lambda_client.invoke(FunctionName='myFunctionName',
                     InvocationType='RequestResponse',
                     Payload=json.dumps(payload))
Related