Reputation: 49
I have to respond to https request with Json body in AWS Lambda API. So, I need to read first the body request and get some data and then to retreive values from external sourse(api) based on those data ans send response back.
I started with this:
exports.handler = async (event) => {
const id_ses = event.queryResult.outputContexts[0].name;
console.log(id_ses);
const res = {
statusCode: 200,
body: JSON.stringify(data),
};
console.log(res);
return res;
};
//var response = { .... json response
When I don't read request body i can send response.. but if i try to get data from the request body, I can't response after it means if I put this two lines
const id_ses = event.queryResult.outputContexts[0].name;
console.log(id_ses);
I can not output response to the requested side outside from Lambda... although I have good result in test console...
Any knowledge or some link where I can see sample would be nice....
Upvotes: 1
Views: 4814
Reputation: 5496
You can use a structure like the below to get started:
In the following code, I use two functions as Handler and the sendToApi
function.
In the handler function, it gets the request from AWS Lambda and reads the body, and pass the name parameter inside the JSON body to the sendToApi
function. Then, the sendToApi
function sends a new request to the external API and retrieves the values, and return it to the handler function via `result variable. Then, the handler serves the response.
module.exports.handler = async(event) => {
const req = JSON.parse(event.body);
const data = {
name: req.name
}
const result = sendToApi(data);
return {
statusCode: 200,
body: JSON.stringify(result),
};
}
const sendToApi = (data) => {
return new Promise((resolve, reject) => {
let dataString = "";
const options = {
hostname: "example.com",
path: "/api/v1",
method: "POST",
headers: {
"Content-Type": "application/json",
},
};
const req = https.get(options, (res) => {
res.on("data", (chunk) => {
dataString += chunk;
});
res.on("end", (chunk) => {
dataString = JSON.parse(dataString);
resolve(dataString);
});
res.on("error", (e) => {
console.error(e);
reject(false);
});
});
req.write(querystring.stringify(data));
req.end();
});
};
For further reading : https://medium.com/better-programming/aws-tutorial-about-node-js-lambda-external-https-requests-logging-and-analyzing-data-e73137fd534c
Upvotes: 1