In this tutorial, we will be covering the basics of AWS Lambda. AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS). It allows you to run code without provisioning or managing servers, yet ensuring high availability, security, and scalability.
By the end of this tutorial, you will learn:
Prerequisites:
Log in to your AWS Management Console and select Lambda from the Services menu.
Click the 'Create Function' button.
Choose 'Author from scratch' and provide a name for your function.
Choose Node.js as your runtime.
Click 'Create Function'.
In your Lambda function configuration, you will see an inline code editor. Here's an example of a basic Lambda function:
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
exports.handler
: This is the entry point of the Lambda function.async (event) => { ... }
: This is an asynchronous function that AWS Lambda calls when the function is invoked.const response = { ... }
: This is creating a response object.statusCode: 200
: HTTP status code indicating success.body: JSON.stringify('Hello from Lambda!')
: The response body.return response;
: The function returns the response object.You can trigger your function via an HTTP request using Amazon API Gateway. To set it up:
exports.handler = async (event) => {
const name = event.name ? event.name : "World";
const response = {
statusCode: 200,
body: JSON.stringify(`Hello, ${name}!`),
};
return response;
};
This function takes an input name
and returns a greeting. If no name is provided, it defaults to "World".
In this tutorial, we've covered the basics of AWS Lambda, including setting up a Lambda function, writing a simple function, and triggering it with an HTTP request.
The next step in learning AWS Lambda would be to explore more complex use cases, such as integrating with other AWS services (like S3 or DynamoDB), handling errors, and setting up proper monitoring and logging.
exports.handler = async (event) => {
const sum = event.number1 + event.number2;
const response = {
statusCode: 200,
body: JSON.stringify(`The sum is: ${sum}`),
};
return response;
};
You can trigger this function by passing an event object like this: { "number1": 10, "number2": 20 }
.
const AWS = require('aws-sdk');
const S3 = new AWS.S3();
exports.handler = async (event) => {
const params = { Bucket: 'my-bucket', Key: 'my-file.txt' };
const data = await S3.getObject(params).promise();
const fileContent = data.Body.toString();
const response = {
statusCode: 200,
body: JSON.stringify(`File content: ${fileContent}`),
};
return response;
};
Please replace 'my-bucket' and 'my-file.txt' with your actual bucket name and file. This function will return the content of the specified file.