Serverless Framework With AWS
The Serverless framework offers you some freedom when working on apps. See how to use it to create, deploy, and manage resources on your AWS cloud.
Join the DZone community and get the full member experience.
Join For FreeServerless is the architectural style in which applications rely heavily on Backend as a Service (BaaS) and Functions as a Service (FaaS). In BaaS, the third-party remote application services are integrated tightly into the client side of apps — for example, Firebase. Whereas in FaaS, the server side logic is written as functions using the services provided by a cloud — for example, AWS Lambda.
What Is the Serverless Framework?
With serverless architecture being defined, what is the Serverless framework?
Serverless is a tool that helps build, deploy, and manage serverless applications. In short, we can focus on our application without worrying about infrastructure.
Serverless Framework With AWS
In this post, let's work with a simple example of Serverless with AWS as our cloud service provider.
Before we start using the Serverless framework, we need the following tools.
- AWS account
- AWS CLI to configure the credentials
- Node.js
- Serverless framework
After having the necessary tools, let's start writing the application.
The source code for this application is available here. A download link is also provided at the end of this post.
Serverless Application
In this simple serverless example application, we are going to hit the API Gateway from the HTML page. The API gateway will then trigger the Lambda function, which will return the response. Then, we will handle the response and display the output in the HTML page.
Yes. Probably the simplest example possible. And we are going to use the serverless framework to create the resources needed for this application.
serverless.yml
The serverless framework supports writing configurations in YAML. So, we can define the resources needed for our application as a configuration. Then, the framework will automate resource creation using CloudFormation internally.
The listing below shows the configuration for our application:
service: aws-serverless
frameworkVersion: ">=1.8.0 <2.0.0"
provider:
name: aws
runtime: nodejs4.3
versionFunctions: false
functions:
main:
handler: backend/index.handler
environment:
USER_NAME: GuestUser
events:
- http:
path: /
method: get
cors: true
The serverless.yml file has sections for defining the framework version, cloud service provider, runtime environment, our Lambda function's details, and it's event triggers.
Lambda Function
Now we can start writing our Lambda function, which will execute when a request is received from API Gateway. Basically, it's a place to write our business logic for the request received from the browser client.
In the serverless.yml, if you notice the line handler: backend/index.handler
, that indicates that the framework is going to expect an index.js
file inside a folder named backend
. In the index.js file, there should be a function named handler
exported as a module.
The following listing shows our code for our Lambda function:
'use strict';
const user_name = process.env['USER_NAME'];
module.exports.handler = (event, context, callback) => {
console.log(JSON.stringify(event));
console.log('Input User Name Value : ' + user_name);
const welcomeMsg = `Hello ${user_name},
Welcome to Serverless Architectures. It's AWSome!`;
const response = { 'message': welcomeMsg };
const respified = {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify(response)
}
callback(
null,
respified
);
}
Deploying the Application
To deploy the application, go to the project folder that contains the serverless.yml file. Then open the command prompt.
Issue the command sls deploy
. Alternatively, you can use serverless deploy
— both will do the same action of deploying the resources.
The resources are now created and deployed into the AWS Cloud. The framework outputs the API Gateway endpoint in the console. This is because we have mentioned API Gateway as an event trigger for the Lambda function in the configuration file. Make a note of the endpoint URL, which we will use in our example shortly.
Note: The API Gateway URL listed above in the image might not be available for you for testing. However, you can configure the one for you by following this example.
If you notice the function's name in the console, it's aws-serverless-dev-main
.
aws-serverless
is the service name mentioned in configuration. dev
is the default staging name for our application. We can configure other names such as prod, pre-prod
.
main
is the function name configured in serverless.yml.
In the CloudFormation console, you can view the stack created by Serverless internally. In Events, you can also see the entries of resource creation, such as the Lambda function, API Gateway, and IAM roles.
A Simple Client
We are almost done. Now to test our application, we need a simple client that will run on a browser and invoke the API Gateway.
The following listing shows our index.html
file.
<!DOCTYPE html>
<html>
<head>
<title>Serverless framework</title>
<style>
.text-style {
color: maroon;
}
#welcome-img{
display: none;
}
</style>
</head>
<body>
<div class="container" role="main" align="center">
<h1>Serverless framework with AWS - Example</h1>
<div>
<form class="col-md-4" id="features" action="">
<p>
<h2>
<span id="welcome-message" class="text-style">Click the below button to get welcome message</span>
<h2>
</p>
<p>
<button type="button" id="welcomeMessageButton" onclick= "getWelcomeMessage()" class="btn btn-info">Get Welcome Message</button>
<button type="button" id="resetButton" onclick="resetMessage()" class="btn btn-info">Reset</button>
</p>
<p>
<img id="welcome-img" src="https://static.rayfocus.com/wp-content/uploads/2017/11/04200430/serverless.png">
</p>
</form>
</div>
</div>
<script type="text/javascript">
function getWelcomeMessage(){
invokeAPI(function(data){
document.getElementById('welcome-message').innerHTML = data;
document.getElementById('welcome-img').style.display = 'block';
});
}
function invokeAPI(callback){
var endpointURL = 'YOUR_API_GATEWAY_URL';
fetch(endpointURL, {
method: 'get',
mode: 'cors',
headers: new Headers({
'Accept': 'application/json'
})
}).then(response => {
console.log('response untouched', response);
if(response.status === 200){
response.json().then(respified => {
console.log('JSON response', respified)
callback(respified.message);
}).catch(err => {
console.log('Error parsing the respone as JSON.', err);
callback(err);
});
}
else{
throw `Invalid response received with status code ${response.status}`;
}
}).catch(err => {
console.log('Error invoking API gateway endpoint.',err);
callback(err);
})
}
function resetMessage(){
var defaultWelcomeMessage = 'Click the below button to get welcome message';
document.getElementById('welcome-message').innerHTML = defaultWelcomeMessage;
document.getElementById('welcome-img').style.display = 'none';
}
</script>
</body>
</html>
Note: Replace the YOUR_API_GATEWAY_URL
string with the URL that you get when configuring the API Gateway.
Testing the Application
Finally, it's all done. Now we can test our application. Open the index.html in a web browser. You should see the following screen rendered.
Click on the Get Welcome Message
button. You should get the welcome message and the welcome image displayed below.
Clean Up the Resources
With Serverless, it's very simple to clean up the resources we have created for the application. Just issue the command sls remove
. The CloudFormation stack will be deleted, and you are all done cleaning up.
Conclusion
We have seen a simple example of using the Serverless framework. While developing this application, we haven't used the AWS management console to get the things done. That is one of the key advantages of the Serverless framework. Because it means the creation, deployment, and management of resources are automated.
What's next? We can start building applications using serverless architectures and automate resource management using the Serverless framework.
Thank you for reading this post. If you have any questions, please share them in the comments section.
Download the source code: aws-serverless-example.zip
Opinions expressed by DZone contributors are their own.
Comments