Max
Max

Reputation: 115

AWS boto3 invoke lambda returns None payload

I'm not quite sure why this piece of code fails, please I'd be happy to hear your thoughts. I've used examples from boto3 and its works in general, but I'd get an AttributeError all of a sudden in some cases. Please explain what I am doing wrong because if a payload is None, I will get a JSON decoding error but not a None object.

Here is a simplified version of a code that causes the exception.

import boto3
import json

client = boto3.client('lambda', region_name='...')
res = client.invoke(
    FunctionName='func',
    InvocationType='RequestResponse',
    Payload=json.dumps({'param': 123})
)
payload = json.loads(res["Payload"].read().decode('utf-8'))
for k in payload.keys():
    print(f'{k} = {payload[k]}')

The error

----
[ERROR] AttributeError: 'NoneType' object has no attribute 'keys'
Traceback (most recent call last):
.....

Upvotes: 1

Views: 1930

Answers (1)

Coin Graham
Coin Graham

Reputation: 1584

Just replicated your issue in my environment by creating a lambda that doesn't return anything and calling it using boto3. The "null" object passes through the json loads without error but doesn't have any keys since it's not a dictionary.

def lambda_handler(event, context):
    pass

I created my code just like yours and got the same error. Weirdly, I was able to get the json error by attempting to print out the streaming body with this line

print(res["Payload"].read().decode('utf-8'))

before loading it. I have no idea why this happens.

Edit: Looks like once you read from the StreamingBody object it's empty from then on. https://botocore.amazonaws.com/v1/documentation/api/latest/reference/response.html#botocore.response.StreamingBody. My recommendation is to read the data from the streaming body and check for "null" and process as normal.

Upvotes: 1

Related Questions