Step 2: Create Lambda and API Gateway (Nodejs) — AWS Serverless to RDS MySQL

HK_IT_ER
5 min readSep 2, 2018

--

Create Lambda

Click “Create function”
We selected the “Author from scratch” and you can follow the setting.
The lambda is created.

NodeJS Code

The online editor of the lambda cannot use the “npm install” and therefore we need to write code in our computer and then upload to the lambda.

Step 1: Create package.json

npm init

The package.json for your reference.

{
"name": "test2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}

Step 2: Install the “mysql” library for connecting the MySQL

npm install --save mysql

Step 3: Create Database in index.js

const mysql = require('mysql');const con = mysql.createConnection({
host : process.env.RDS_HOSTNAME,
user : process.env.RDS_USERNAME,
password : process.env.RDS_PASSWORD,
port : process.env.RDS_PORT
});
exports.handler = async (event) => {
con.query("CREATE DATABASE mysqllab", function (err, result) {
if (err) throw err;
console.log("Database created");
});
return "Database Created"
};

Step 4: Zip all the node_modules, index.js and package.json

Upload the zip file
Save the zip file
The library and source code are uploaded.
Add the Environment Variables and Save

The RDS_HOSTNAME got from the RDS details section.

The MySQL Hostname
Configure the Network Section and Save
Error occurs after configuration of the VPC network.
Your Lambda Role “service-role/mysql_lab”
Go to your role in IAM
Change the IAM Role

Change the existing role from “AWSLambdaEdgeExecutionRole” to “AWSLambdaVPCAccessExecutionRole”

Go Back Lambda and Save again

Change the RDS MySQL Security Group

Go the RDS Security Group

You can find your security group in the MySQL details section.

Edit the Inbound Rules Source to “sg-fa8db185”

“sg-fa8db185” can from the Network section in the lambda.

Test the Lambda Function
The database is created

Create Table in the Database

Using the same Lambda to create table — MESSAGE and change the following source code to create the table in online editor.

const mysql = require('mysql');const con = mysql.createConnection({
host : process.env.RDS_HOSTNAME,
user : process.env.RDS_USERNAME,
password : process.env.RDS_PASSWORD,
port : process.env.RDS_PORT,
database : process.env.RDS_DATABASE
});
exports.handler = async (event) => {
const sql = "CREATE TABLE MESSAGE (message VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
return "Table Created"
};
Add the Database Configuration and Save
Test the Lambda and the table is created.

Insert Record into Table “MESSAGE”

Change to the following source code to insert the record.

const mysql = require('mysql');const con = mysql.createConnection({
host : process.env.RDS_HOSTNAME,
user : process.env.RDS_USERNAME,
password : process.env.RDS_PASSWORD,
port : process.env.RDS_PORT,
database : process.env.RDS_DATABASE
});
exports.handler = (event, context, callback) => {
// allows for using callbacks as finish/error-handlers
context.callbackWaitsForEmptyEventLoop = false;
const sql = "INSERT INTO MESSAGE (message) VALUES ('I am MySQL')";
con.query(sql, (err, res) => {
if (err) {
throw err
}
callback(null, '1 records inserted.');
})
};
Test the Lambda and the Record is inserted

Query the Record

Change to the following source code to query the record.

const mysql = require('mysql');const con = mysql.createConnection({
host : process.env.RDS_HOSTNAME,
user : process.env.RDS_USERNAME,
password : process.env.RDS_PASSWORD,
port : process.env.RDS_PORT,
database : process.env.RDS_DATABASE
});
exports.handler = (event, context, callback) => {
// allows for using callbacks as finish/error-handlers
context.callbackWaitsForEmptyEventLoop = false;
const sql = "select * from MESSAGE";
con.query(sql, function (err, result) {
if (err) throw err;
callback(null, result)
});
};
The Lambda can query the MySQL

Create API Gateway

Create API
Settings on the API
Create Method
Create GET Method
Fill the Lambda Function Name
Permission will add (API Gateway to Lambda)
Deploy API
The Settings of the Deployment
The API endpoint is created
The result is shown

You can give me the response for support if you completed the lab or ask me questions when you face any difficulty.

Review how to create RDS MySQL in the AWS

Step 1: Create RDS MySQL — AWS Serverless to MySQL

--

--