+1 732 991 0534 | info@musewerx.com
Creating a simple Lambda function for Serverless CRUD (Create, Read, Update, Delete) operations using an RDS Aurora database. In this example, we'll use Lambda function URL as an API Gateway. The programming language used will be Python for create crud functionalities and the boto3 library for database interactions.
Set Up RDS Aurora Database
Create an RDS AWS Aurora database in the AWS Management Console. Note down the database endpoint, username, password, and database name.
Create a Lambda Function
Add Environment Variables
- In your Lambda function configuration, scroll down to the "Environment variables" section.
- Add the following environment variables:
- DB_HOST: Your RDS Aurora database endpoint
- DB_USER: Your database username
- DB_PASSWORD: Your database password
- DB_NAME: Your database name
Code the Lambda Function:
In the Lambda function editor, write the Python code for CRUD operations. Below is a basic example of CRUD:
import json
import os
import boto3
import pymysql
import sys
import logging
#Get environment variables
db_host = os.environ['DB_HOST']
db_user = os.environ['DB_USER']
db_password = os.environ['DB_PASSWORD']
db_name = os.environ['DB_NAME']
myport = 3306
logger = logging.getLogger()
logger.setLevel(logging.INFO)
try:
conn = pymysql.connect(host=db_host, user=db_user, passwd=db_password, db=db_name,
port=myport,)
except pymysql.MySQLError as e:
logger.error("ERROR: Unexpected error: Could not connect to MySQL instance.")
logger.error(e)
sys.exit()
logger.info("SUCCESS: Connection to RDS MySQL instance succeeded")
def insertData(data):
body = json.loads(data['body'])
with conn.cursor() as cur:
cur.execute("INSERT INTO users (id, name) VALUES (%s, %s)", (body['id'], body['name']))
conn.commit()
return ("Message : record inserted successfully")
def getDetail():
with conn.cursor() as cur:
cur.execute("SELECT * FROM users")
items = cur.fetchall()
return items
def updateData(data):
body = json.loads(data['body'])
with conn.cursor() as cur:
cur.execute("UPDATE users SET name = %s WHERE id = %s", (body['name'], body['id']))
conn.commit()
return ('Message : record updated successfully')
def deleteData(data):
body = json.loads(data['body'])
with conn.cursor() as cur:
cur.execute("DELETE FROM users WHERE id = %s", (body['id'],))
conn.commit()
return ('Message : record deleted successfully')
def lambda_handler(event, context):
httpMethod = event['requestContext']['http']
if httpMethod['method'] == 'GET':
# Implement your read operation
data=getDetail()
return data
elif httpMethod['method'] == 'POST':
# Implement your create operation
record=insertData(event)
return record
elif httpMethod['method'] == 'PUT':
# Implement your update operation
result=updateData(event)
return result
elif httpMethod['method'] == 'DELETE':
# Implement your delete operation
result=deleteData(event)
return result
Deploy the Lambda Function
- Click on "Deploy" button to deploy your Lambda function.
Test the Lambda Function in Postman
- In the Lambda function details, note the function URL
- Open Postman and create a new request.
- Set the request method (GET, POST, PUT, DELETE) and enter the function URL.
- Add any required headers and request body.
- Send the request and check the response.
Monitor and Troubleshoot
- Use Cloud Watch Logs to monitor and troubleshoot your Lambda function.
Now you have a basic setup for a Lambda function performing serverless CRUD operations on an RDS Aurora database. Customize the code based on your specific requirements and database schema.
So, are you ready to make the change?
Contact us today for a free consultation and discover how our solutions can benefit your business.