0
votes

I have just started working on AWS. I am building a system connection between lambda, RDS MYSQL Database and API gateway.

Created a lambda function in python which inserts the data into the MYSQL database and configured API gateway with the lambda function. and when I am testing the lambda function within lambda console, everything is working fine. but when I am trying to call API from postman, it results in "message": "Internal server error" and 502 bad gateway.

import pymysql
import sys
import logging
import json

logger = logging.getLogger()
logger.setLevel(logging.INFO)

try:
    conn = pymysql.connect(
        host='',
        port=int(3306),
        user="",
        passwd="",
        db="")
except:
    logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
    sys.exit()

logger.info("SUCCESS: Connection to RDS mysql instance succeeded")

cursor=conn.cursor()

def lambda_handler(event, context):
    print(event)
    
    http_method = event['httpMethod']
    
    if http_method == "GET":
        Serial_Number = int(event['queryStringParameters']['Serial_Number'])
        platform = int(event['queryStringParameters']['platform'])
        architecture = int(event['queryStringParameters']['architecture'])
        
    elif http_method == "POST":
        body = json.loads(event['body'])
        
        Serial_Number = body['Serial_Number']
        platform = body['platform']
        architecture = body['architecture']
        
    return{
        'statusCode' : 200,
        'headers': {'Content-Type': 'application/json'},
        'body' : json.dumps(Insertion(Serial_Number, platform, architecture)),
        'messageReason' : "Successfully updated Details"
    }
    
def Insertion(Serial_Number, platform, architecture):
    item_count = 0
    
    with conn.cursor() as cur:
        cur.execute("insert into system_data (Serial_Number, platform, architecture) values(%s, %s, %s)", (Serial_Number, platform, architecture))

        conn.commit()
        cur.execute("select * from system_data")
        
        for row in cur:
            item_count += 1
            logger.info(row)
    return "Added %d items to RDS MySQL table" %(item_count)

But when I am trying to call API with postman, I am getting "internal server error" in postman.

1

1 Answers

0
votes

Http status 502 in Api Gateway with Lambda Integration is related to a bad-formatted response from lambda. The valid structure of response is described in this guide https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format

This is why in lambda test console you get a 200 - OK response as it is a valid general json but testing from Api Gateway is not valid as is not the expected structure.

From your code, the problem is originated due to a non-valid field "messageReason" in response. Try removing this field and include it in headers or body