How to Build your Serverless Cloud Application with S3 and Lambda Function

How to Build your Serverless Cloud Application with S3 and Lambda Function

Introduction

With an intuitive increase in Cloud computing, a wide array of industries have now transformed their Infrastructure facilities towards serverless architectures. Agile cloud-based application development is often inclined to marginalize infrastructure management facilities for swift testing and deployment.

Serverless frameworks approach towards product-driven leadership for developing modern applications with reduced Total Cost of Ownership (TCO), increased innovation and improved reliability.

Serverless Approach and its Benefits:

  • With no infrastructure to manage and the only focus on creating highly scalable deliverables, application development in cloud computing found its place in the modern era.
  • Serverless computing benefits its users by providing a “pay as you use” structure for utilizing their services.
  • The user only pays for the time he utilizes the cloud infrastructure for different services be it database management, infrastructure management, or cloud computing services.

Why Serverless Applications?

  • Serverless applications keep your business afloat where your developers only need to focus on delivering beautiful and highly engaging applications.
  • With a highly reliable infrastructure and data security complying with all the modern architectures, application development on serverless architecture provides you with maximum security while ensuring 100% uptime.
  • With serverless applications, your computing data security and infrastructure are managed by the cloud.
  • Now your developers can focus only on what’s important, “developing beautiful and highly engaging applications.

Building a Modern Application using AWS (Amazon Web Services)

This blog commissions the development of a serverless application by utilizing Amazon Web Services (AWS) Lambda, AWS Simple Storage Service (S3), and Amazon API Gateway.

Prerequisite services used cloud-based application development from AWS to build a serverless application

  • API Gateway – The S3 application will make an API call to the API Gateway whenever a form is submitted. This API call triggers a Lambda function which is associated with that particular API Gateway.
  • Lambda – Lambda function aids information delivery from a submitted form to an e-mail address by using AWS Simple Email Service (SES)
  • Simple Storage Service (S3) – S3 hosts static websites that include HTML files and assets like Cascading Style Sheets (CSS), JavaScript, and Images.

 S3 and Lambda Function

Quick Steps: To get started and Create an API Gateway

Step 1: Create your API endpoint for the application

To Create an API endpoint, open API Gateway and Click the Create New API Button. Carefully choose a name, description, and endpoint type for your API.

S3 and Lambada Configuration

Step 2: Create a Method like POST/PUT/GET

Select actions from the Resources menu and Click Create Method.

S3 and Lambada Configuration

Step 3: Select the “POST” as the method type that redirects to the POST Setup page

S3 and Lambada Configuration

Step 4: Select the Lambda Function you want to assign as the integration point of your new method type and Click on Save

S3 and Lambada Configuration

Step 5: Give permissions to API Gateway to invoke the assigned Lambda function

S3 and Lambada Configuration

Step 6: Deploy the API

Click on the Actions and Select Deploy API.

S3 and Lambada Configuration

Step 7: Generating Endpoint URL

Choose the New stage as the deployment stage and enter the stage name, stage description and Deployment description. Click Deploy.

S3 and Lambada Configuration

Step 8: The generated Endpoint URL is used as an API URL to call any method in the serverless application

S3 and Lambada Configuration

Step 9: Enabling CORS (Cross-Origin Request Blocked)

Click on the actions button and Select Enable CORS to avoid CORS headers error in an API call.

S3 and Lambada Configuration

In this section, we built the API that will allow your formerly static S3 website to call Lambda Functions. Let’s start creating a Lambda Function that will be used by API Gateway.

Creating a Lambda Function:

The lambda function simplifies your serverless approach with pay-per-consumed compute time. Runs code for practically any type of application or backend services without provisioning or managing servers.

Step 1: Create a Lambda Function

Choose the Hello-world template for a basic example.

S3 and Lambada Configuration

Step 2: Give a name to the Lambda function for your application

Add a Name and choose/create a role with the necessary Lambda permissions to access S3, API Gateway, SES, and other AWS Services
S3 and Lambada Configuration

Step 3: Create your New Lambda Function

A preconfigured Sample of Lambda Function code prompts on the screen that requires no edits. Click on the “Create Function” button.

Create Function

Step 4: Delete the existing code and replace it with the below-mentioned example codeCreate Lambda Function

Example Code:

var ses = new AWS.SES();var RECEIVERS = [‘you@example.com‘];
var SENDER = ‘you@example.com‘; // ensure ‘sender email’ is verified in your Amazon SESexports.handler = (event, context, callback) => {
console.log(‘Received event:’, event);
sendEmail(event, function (err, data) {
var response = {
“isBase64Encoded”: false,
“headers”: { ‘Content-Type’: ‘application/json’, ‘Access-Control-Allow-Origin’: ‘http://www.example.com’ },
“statusCode”: 200,
“body”: “{\”result\”: \”Success.\”}”
};
callback(err, response);
});
};function sendEmail (event, done) {
var data = JSON.parse(event.body);
var params = {
Destination: {
ToAddresses: RECEIVERS
},
Message: {
Body: {
Text: {
Data: ‘Name: ‘ + data.name + ‘\nEmail: ‘ + data.email + ‘\nMessage: ‘ + data.message,
Charset: ‘UTF-8′
}
},
Subject: {
Data: ‘Contact Form inquiry: ‘ + data.name,
Charset: ‘UTF-8′
}
},
Source: SENDER
}
ses.sendEmail(params, done);

*Replace email and domain fields accordingly

Step 5: Adding Trigger

Add Trigger to your Lambda Function by selecting API Gateway in newFormProcessor.

NewFormProcessor

Step 6: Select API

Click on “Configuration Required” and select an API from the existing APIs.
Configuration Required

Step 7: Configure Triggers

Configure triggers by selecting your latest deployment stage and Clicking add. Click on Save.

Configure Triggers

Update your S3 website with the example code to add its new dynamic functionality

Example code:

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js“></script>
<script type=”text/javascript”>
$(document).ready(function() { $(“#submit”).click(function(e) {
e.preventDefault();
var name = $(“#name”).val(),
email = $(“#email”).val(),
message = $(“#message”).val();
$.ajax({
type: “POST”,
url: ‘https://xxxxxxxx.execute-apiurl.us-east-1.amazonaws.com/Done‘, contentType: ‘application/json’,
data: JSON.stringify({
‘name': name,
‘email': email,
‘message': message
}),
success: function(res){
$(‘#form-response’).html(‘<div>Welcome to the queue! Your path will begin shortly…</div>’);},
error: function(){
$(‘#form-response’).html(‘<div>Something went wrong… We are working on it!</div>’); }}); }) });
</script>
<!–THIS IS WHERE DATA IS PULLED FROM S3 TO API TO LAMBDA TO SES–><div>
<input type=”text” id=”name” >
<label for=”name” class=”control-label”>Name</label>
</div>
<div>
<input type=”text” id=”email” >
<label for=”email” class=”control-label”>Email address</label> </div>
<div >
<textarea id=”message” name=”message” rows=”3″ placeholder=”Message”></textarea>
</div>
<div id=”form-response”></div>
<button id=”submit” type=”submit” style=”background-color:#28547C;”>Request Demo</button>

By using this example code, you can receive form submissions sent from your S3 application to your specified e-mail address.

Conclusion:

Serverless architecture is a native cloud platform that allows you to shift your infrastructure operations and management to a cloud service provider. Serverless architecture runs your code, provides cloud storage, enhances your database services, and provides you with secure APIs without worrying about any server clientele.

These applications will be highly in demand in the current trends due to their high availability and automated scaling. The details mentioned in this blog are a prefixed base for delivering serverless applications.

You can extend this base to make astounding serverless applications with S3 and Lambda as per your requirements.

In this blog, we gave you insight on how to build a serverless application with AWS lambda and S3. However, if we miss any perceptive of the phenomenon, we are open to your valuable feedback and comments.