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

Serverless Cloud Application

Introduction

With an intuitive increase in Cloud computing, wide array of industries have now transformed their Infrastructure facilities towards serverless architectures. Agile development frameworks are often inclined to marginalize infrastructure management facilities for swift testing and deploying. 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, serverless computing found its place in the modern era.
  • The 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 towards all the modern architectures, application development on serverless architecture provides you with maximum security while ensuring 100% uptime.
  • With serverless applications your compute, data, security, and infrastructure are managed by cloud.
  • Now your developers can focus only on what’s important, “developing beautiful and highly engaging applications”

Serverless architecture for Application Development using on AWS (Amazon Web Services):

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

Prerequisite services used from AWS to build a serverless application

  • API Gateway – 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 API Gateway

 

Step 1: Create your API endpoint for application

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

S3 and Lambada Configuration

Step 2: Create Method like POST/PUT/GET

Select actions from Resources menu and Click Create Method.

S3 and Lambada Configuration

Step 3: Select the “POST” as method type that redirects to 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 stage name, stage description and Deployment description. Click Deploy.

S3 and Lambada Configuration

Step 8: 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 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 Lambda Function that will be used by API Gateway.

Creating a Lambda Function:

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 Lambda function for your application.

Add 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 “Create Function” button.

Create Function

Step 4: Delete the existing code and replace it with the below-mentioned example code.

Create 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 Click 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>Replace the URL parameter with your API gateway endpoint

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, enhance your database services, and provide 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 requisites.

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 feedbacks and comments.

The following two tabs change content below.
Jigar Oza

Jigar Oza

Sr. Software Developer(Open-Source) at Dev Information Technology Ltd.
I am a senior software developer at DEV IT since last 3 years. I am passionate for learning latest & innovative technologies and make work easier and better. I am fond of coding, debugging and refactoring.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>