Issue
I have below code for AWS lambda for GET data from DB:
def lambda_handler(event, context):
'''
This function is lambda handler function.
This function connects to DB using environment variables and
execute SQL query.
'''
logging.info(f"Fetching DB connection details.")
try:
# Load env file
load_dotenv()
# Create the connection object
conn = mysql.connector.connect(
user=os.getenv('USER_NAME'),
password=get_db_password(os.getenv('RDS_HOST')),
host=os.getenv('RDS_HOST'),
database=os.getenv('DB_NAME'),
port=os.getenv('PORT'))
# Create a cursor
cursor = conn.cursor()
query = "SELECT * from <table_1>; "
result = execute_query(cursor, query)
result_list = result["workflow_last_execution_time"].tolist()
if not result_list:
return {
'statusCode': 404,
'body': json.dumps('No date time returned from DB')
}
return {
'statusCode': 200,
'body': json.dumps(result_list)
}
except Exception as error:
logging.error("An unexpected error occurred: {}".format(error))
return {
'statusCode': 500, # Internal Server Error
'body': json.dumps('An error occurred: {}'.format(str(error)))
}
finally:
close_connection(cursor, conn)
But I am not sure how do I modify the code for POST method for INSERT query? I am no-voice in AWS lambda. So, kindly suggest. I couldn't find any such article that could help me.
Solution
There is an example in Python in the AWS Code Examples library that includes GET and POST requests using API Gateway. You can clone this repository and follow the README instructions to run it yourself.
It deploys a test database:
py library_demo.py deploy_database
And a REST API
py library_demo.py deploy_rest
However, if you want to do this without API Gateway, you can now use Lambda Endpoints directly, as described here.
Using this method, you should be able to get the action something like this, and determine if it is GET or POST. You may need to check the 'Use Lambda Proxy Integration' option to get these objects.
context = event.get("requestContext")
request = context.get("http")
method = request.get("method")
Answered By - rlhagerm
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.