'AWS Lambda: Basic Python Rest API to add 2 numbers and return their sum

I'm trying to understand, how to create a REST API using AWS Lambda and Python. For this, I'm creating a simple Lambda function that will accept 2 numbers from the user and return the sum of these numbers.

Code of my Lambda function:

import json

def lambda_handler(event, context):
    # TODO implement
    try:
        #User Input:n1 & n2
        _query = event['queryStringParameters']
        _n1 = int(_query['n1'])
        print(_n1)
        _n2 = int(_query['n2'])
        print(_n2)
        del(_query)
    
        #Response Body
        _body = {
            'n1': _n1,
            'n2': _n2,
            'sum': _n1+_n2
        }
        
        print(_body)
    
        #Response Header
        _header = {
            'Content-Type': 'application/json'
        }
        
        print(_header)
    
        #Response
        _response = {
            'statusCode': 200,
            'headers': json.dumps(_header),
            'body': json.dumps(_body)
        }
        
        print(_response)
        
        return _response
    except Exception as e:
        print(e)

This Lambda function is connected to AWS API Gateway to allow public access. I have not configured any authentication mechanism for API Gateway.

I'm trying to call this API from another python program.

Source code of calling program:

from requests import get

try:
    _url = 'URL_of_the_lambda_function'
    _params = {
        'n1':1,
        'n2':2
    }

    r = get(
        url=_url,
        params=_params
    )

    data = r.json()


    print(data)
except Exception as e:
    print(e)

This program is getting executed on the terminal with the help of VS Code. When I'm trying to run the program, I'm getting

{'message': 'Internal server error'}

Can anyone please help me to understand, what is the mistake with my code?

[N.B.: As suggested fellow community members:

  1. I have converted header to dictionary.
  2. I have added try/catch block to both(lambda and calling function)
  3. I have tried to print every header, response and body objects ]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source