I am trying to build an API using API Gateway, Lambda, and RDS. So you type in the URL and get the specific rows from RDS back in a JSON format.
So this is what I would like to achieve.
- /production/myfootballapi?table=football -> all rows in the table should be returned (not working)
- /production/myfootballapi?table=football&id=2 -> only the id 2 row should be returned (only this case works)
The main problem that I am having is that I currently can't show all rows because I always have to define the id otherwise an error occurs.
My API Gateway Body Mapping Template:
{
"table" : "$input.params('table')",
"id" : $input.params('id')
}
My Lambda function
var mysql = require('mysql2');
var config = require('./config.json');
var pool = mysql.createPool({
host : config.dbhost,
user : config.dbuser,
password : config.dbpassword,
database : config.dbname,
});
exports.handler = (event, context, callback) => {
//prevent timeout from waiting event loop
context.callbackWaitsForEmptyEventLoop = false;
pool.getConnection(function(err, connection) {
if (err) throw err;
// Use the connection
var table = event.table;
var id = event.id;
// This if-function is just a try to solve this problem but it doesn't work
if (id !== null) {
var sql = "SELECT * FROM ?? WHERE id = ?";
var inserts = [table, id];
} else {
var sql = "SELECT * FROM ?";
var inserts = table;
}
sql = mysql.format(sql, inserts);
connection.query(sql, function (error, results, fields) {
// And done with the connection.
connection.release();
// Handle error after the release.
if (error) callback(error);
else callback(null,results);
});
});
};
If you need further information, please leave a comment.
THANKS!






tableandid, or you only provide one in the first case.