Setting up simple Amazon API Gateway in minutes : (Part 1 of 2)

In this post we will see how we can quickly and easily setup a basic API gateway to publish our data to external systems. So let’s start without further ado: “Setting up simple Amazon API Gateway”: If you need to learn about AWS lambda a bit more in details, please follow the link : https://aws.amazon.com/lambda/

About the database Setup:

We will not talk about the setup of the database here as, that’s a separate topic and we are hear to setup an API, so assuming we already have a MySQL database server somewhere and it’s accessible via internet. The ports are open and you have a user name and password to access the database. For this post we will assume the below details as the database credentials:

Database host : 120.00.0.1

User Name: dbuser

Password : dbpassword

The below screenshot is from the database where we have some lead data to be published from a table.

Database table

Lambda function:

To create a lambda function, login to your AWS account and under All services search for Lambda and click on it. That should take you to the lambda home page. You will see a create function button. Click to start creating a function.

create function

In the below window select Auto from scratch, give a function name e.g test , select the latest runtime for node JS. Leave defaults for most of the other settings for this post. You can always play around with these later.

function window

Once these are done you will land on the designer page where you can see index.js. This is where you will write your code (node.js) .

nodejs index.js

Go ahead ,remove this code and paste the below code,

var mysql = require('mysql');
const username = 'dbuser'; //process.env.databaseUser;
const password = 'dbpassword'; //process.env.databasePassword;
const host = '120.00.0.1'; //process.env.databaseHost;
console.log('Loading function');
exports.handler = (event, context, callback) => {
    var connection = mysql.createConnection({
        host: host,
        user: username,
        password: password,
        database: 'DBNAME'
    });

    var query = event.queryStringParameters.query;
    connection.connect();
    console.log('Connected!!');
    var responseresults;
    connection.query(query, function(error, results, fields) {
        if (error) throw error;
        console.log("Ran query: " + query);
        responseresults = results;
    });

    return new Promise((resolve, reject) => {
        connection.end(err => {
            if (err)
                return reject(err);
            const response = {
                statusCode: 200,
                body: JSON.stringify(responseresults),
            };
            resolve(response);
        });
    });
};

The above code will connect to database and just execute a query that was passed from the API call.

You screen should look like the below screen:

updated screen

To execute the code block and test how it responds to call, let’s create a test configuration . Click on the “configure test event” and create a test config as below screen. This is basically a test API call made to the lambda function and the function should get executed to run the code in it.

configure test window.

Once this is saved, you can click on the “Test” button and the code should respond to this call and you will see a execution result. Notice that you got an error. The reason of the error is also mentioned in the log. In this case we are getting the error due to the missing node_modules required to run the MySQL connection. (See below section to fix this error :Creating the code that works).

{
  "errorType": "Runtime.ImportModuleError",
  "errorMessage": "Error: Cannot find module 'mysql'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
  "trace": [
    "Runtime.ImportModuleError: Error: Cannot find module 'mysql'",
    "Require stack:",
    "- /var/task/index.js",
    "- /var/runtime/UserFunction.js",
    "- /var/runtime/index.js",
    "    at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
    "    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
    "    at Object.<anonymous> (/var/runtime/index.js:43:30)",
    "    at Module._compile (internal/modules/cjs/loader.js:1015:30)",
    "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)",
    "    at Module.load (internal/modules/cjs/loader.js:879:32)",
    "    at Function.Module._load (internal/modules/cjs/loader.js:724:14)",
    "    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)",
    "    at internal/main/run_main_module.js:17:47"
  ]
}

Creating the code that works:

First open the command prompt on your local machine and type “npm install mysql –save” (NOTE: you should have node already installed on your machine to run this command ).

Once you have executed this you should see a node_modules folder under your user folder. There should be all files needed under this folder to execute the code and connect to the database.

node command

Something like this :

Copy this folder to the folder where you will create the node files. In my case I created a folder called “Lambda function”. So I will copy this folder to my “Lambda Function” folder. Also create a index.js file with the code we have at the top.

code folder
folder to be zipped

Zip the entire folder and upload this to the lambda function screen. TO upload this folder follow the steps below:

  1. Go to the lambda function page and go to the section where it says “Function code”.
  2. Click on “Action” button on the right of the page
  3. Click on “upload a zip file” and upload the file you created previously.

This will upload the node_modules and this should fix the earlier error you were getting. Now you can go ahead and click on the Test button at the top of this page. If everything is okay you will get some results. But in some cases you might get below error:

{
“errorMessage”: “2020-12-18T18:11:18.692Z fc072095-9d51-4e58-afc2-507f Task timed out after 3.00 seconds”
}

To resolve this error go to the “Basic settings” on the function page and increase the time out higher values. The values can go upto 15 min. If this issue is resolved you should see a response like the below screenshot:

Success AWS Lambda execution log

This screen gives a lot of information about the resources used.

Conclusion

At this point we will stop as the database it setup and connected via the lambda function. Anyone who has access to this function can call the function and get the data that is needed. This is the first step of the process and we will talk about the next step in the next part of the post. Keep reading and sharing ……


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *