Serverless framework with AWS – Example
Serverless is the architectural style in which the applications relies heavily on Backend as a Service(Baas) and Function 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 code using the services provided by Cloud, for example AWS Lambda.
What is Serverless framework?
With the Serverless architecture being defined, what is that Serverless framework?
Serverless framework is the tool which helps to build serverless applications and to deploy and manage it effectively. In short, we can focus on our application with out worrying about infrastructure.
Serverless framework with AWS
In this post, let’s see a simple example of using Serverless framework with AWS as Cloud service provider.
Before start using the Serverless framework we need the following tools available.
- AWS account
- AWS CLI and configuring the Credentials
- NodeJS
- Serverless framework
After having the necessary tools, let’s start writing the application.
The source code for this application is available here. The 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 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 the configurations in YAML. So in serverless framework, we can define the resources needed for our application as a configuration. Then the framework will automate the resource creation using CloudFormation internally.
Below listing shows the configuration for our application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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 have the sections for defining the framework version, Cloud service provider, runtime environment, the Lambda function details and it’s event triggers.
Lambda function
Now we can start writing our Lambda function which will execute when the request is received from API gateway. Basically it’s a place to write our business logic for the request received from browser client.
In the serverless.yml, if you notice the line handler: backend/index.handler
which indicates that the framework is going to expect a index.js
file inside a folder named backend
. In the index.js file, there should be a function named handler
exported as module.
Below listing shows our code for Lambda function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
'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 ); } |
Deploy the application
To deploy the application, go to the project folder which contains the serverless.yml file. Then open the command prompt.
Issue the command sls deploy
. Alternatively you can give 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 a event trigger for 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 on following this example.
If you notice the functions 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 cloud formation console, you can view the stack created by serverless framework internally. In the Events, you can also see the entries of resource creation such as Lambda function, API gateway, IAM roles.
A simple client
We are almost done. Now to test our application, we need a simple client which will run on browser and invoke the API gateway.
Below listing shows our index.html
file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
<!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 will get when configuring the API gateway.
Test 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 below screen rendered.
Click on the Get Welcome Message
button. You should get the welcome message and the welcome image displayed as below.
Clean up the resources
With serverless framework, it’s very simple to cleanup 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 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 advantage of serverless framework. Because it means the creation , deployment and management of resources are automated.
What’s next? We can start building the applications using serverless architectures and automate the resource management using serverless framework.
Thank you for reading this post. If you have any questions, please share it in the comments section.
Download source code : aws-serverless-example.zip
1 Comment
Subramanian · November 5, 2017 at 5:06 pm
Keep going machi ☺️
Love your dedication 👌