Lambdas and Serverless Applications
Cloud services have become more granular with time. We have now reached that point where we can build serverless components in the cloud
Function as a service is a piece of code (scripted or compiled) that can be deployed and executed in the cloud. Each function must have a ReSTful endpoint associated with it so it can be reached.
AWS Lambdas are a really cool way of creating reusable pieces of code that can be deployed into the cloud and executed from anywhere. They can be permissioned so as to ensure that only trusted parties can access them.
In this example, the lambda function is written in Javascript
exports.handler = async (event) => {
// TODO implement
const result = event.key1 + '->Hello from Lambda!';
const response = {
statusCode: 200,
body: JSON.stringify(result),
};
return response;
};
The event parameter contains the payload (parameters that need to be passed into the function.
You must use the exports.handler object
The code must be written in an index.js file
After you have created the lambda, you associate with it a Restful endpoint. This can then be called from any javascript client-side code.
In AWS console search for Lambda
Select Create Function
Enter the function name “sum”
Select “Create Function” on the lower right of screen
Modify the code
Paste the following code into the script file
exports.handler = async (event) => { // TODO implement const result = event.key1 + " says hello" const response = { statusCode: 200, body: JSON.stringify(result), }; return response; };
Select “Deploy”
Now select “Test”
Assign an event name and edit the “Key1” value
Scroll down and select Save
Select “Test” again, the test should now run
You should now see an execution result
Select “Configuration” and then “Add Trigger”
Select “API Gateway”
Select all the items shown
The Configuration page has been updated
Search for API Gateway
Your API should exist inidcating that it was created by AWS Lambda
Select the API Name
Make sure the Resources option is selected and expand tree as shown
Select Actions/Create Method
In the dropdown select POST
Select the tick
Start typing the name of the Lambda function, it should appear in the list, select it
Then select Save
Select Test
Enter this JSON into the “Request Body” field
{ "key1": "Selvyn", "key2": "value2", "key3": "value3" }
Scroll down and press Test
You will a response from the Lambda
You have created, tested, and deployed a Lambda into the cloud, it is now accessible to external pieces of code