Home > front end >  How to construct lambda payload to invoke another lambda?
How to construct lambda payload to invoke another lambda?

Time:11-12

I have a lambda proxy function (A) working along with API Gateway that I use to store some data in a remote database. I have another lambda function (B) that processes some data and I wish to reuse A to save data in the database.

I am therefore invoking A from B with a payload. I am able to invoke from B only if I convert this payload from a dictionary to a json it seems. Function A works fine when working along with API Gateway but when I invoke it from B I get an error when I do:

body = json.loads(event['body']) # [ERROR] TypeError: the JSON object must be str, bytes or bytearray, not dict

Let's say this is the code I use in B to invoke A:

def lambda_handler(event, context):

lambda_payload = {
        'headers': {},
        'response': False,
        'queryStringParameters': {},
        'body': { 'user_id' : 2, 'payload' : {'name': "James", 'age': 35}}
    }
    
lambda_client.invoke(FunctionName='A', 
                     InvocationType='RequestResponse',
                     Payload=json.dumps(lambda_payload))

And the following is function A:

def lambda_handler(event, context):   
    
    body = json.loads(event['body'])
...

I would prefer not having to change A but do the changes in B if possible. But if there is no other way I will handle it in A of course. How could I solve this? I am confused with the event type.

CodePudding user response:

If Payload contains the data to be shared from function A to function B.

In A at the time you invoke function B : it's a string - result of the json.dumps() function.

So in B when you process Payload - as it is a string - you can't access to a body index as it were a dict.

I'm afraid you'll have to do minor changes on A and B as the interface between both ends has to be modified.

You can do the following.

In B send the body part as a string :

lambda_client.invoke(FunctionName='A', 
    InvocationType='RequestResponse',
    Payload=json.dumps(lambda_payload["body"]))

In A just use the string.

def lambda_handler(event, context):
    # body = event

CodePudding user response:

Not to modify function A but only function B I did this before invoking:

lambda_payload['body'] = json.dumps(lambda_payload['body'])

lambda_client.invoke(FunctionName='A', 
                         InvocationType='RequestResponse',
                         Payload=json.dumps(lambda_payload))
```
  • Related