sumanth shetty
sumanth shetty

Reputation: 2181

error: string indices must be integers, while unpacking request.body object from API Gateway request for a lambda function

I am trying my hands-on with API gateway as a trigger to lambda function using python as run time.

here is by python code:

import json

def lambda_handler(event, context):
    num1, num2 = event['body'][0]['num1'], event['body'][0]['num2']

    return {
        'statusCode' :200,
        'body': json.dumps({
           'num1' : num1,
           'num2' : num2,
           'result' : num1 + num2
        })
    }

Here is the error that I am getting when checking the cloud watch logs.

string indices must be integers: TypeError
Traceback (most recent call last):
  File "/var/task/add.py", line 4, in lambda_handler
    num1, num2 = event['body'][0]['num1'], event['body'][0]['num2']
TypeError: string indices must be integers

str 

Here is my Postman request:

enter image description here

Would like to mention I also tried:

num1, num2 = event['body']['num1'], event['body']['num2']

Gave the same error.

I know I am missing something while unpacking them, but not able to point it out.

could anyone help me out of this?

Upvotes: 1

Views: 494

Answers (1)

Marcin
Marcin

Reputation: 238827

Based on the comments.

There were two issues:

  1. event['body'] was string, not json. It was solved using json.loads(event['body']).
  2. A spelling mistake in ststudCode. It should be statusCode.

Upvotes: 1

Related Questions