Manuel Santi
Manuel Santi

Reputation: 1132

Python error formatting an AWS lambda request

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

Upvotes: 2

Views: 1085

Answers (2)

Mark B
Mark B

Reputation: 201008

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))

Upvotes: 1

mweiss1
mweiss1

Reputation: 61

If you want to pass a JSON object as a string, you can use json.dumps(payload) as described in https://docs.python.org/3/library/json.html.

Upvotes: 2

Related Questions