Wednesday, 7 November, 2018 UTC


Summary

In this article I’m going to walk you through using the Serverless framework to setup your very first AWS Lambda function. Serverless architecture is a very powerful way to leverage functions as a service and remove server scaling concerns. It is also very cost effective as you are charged only when the function is executing. If any of that sounds interesting this is the article for you.
What We’ll Be Building
We’ll be building a Lambda function that returns the string “Hello World” when you make a request to it. The Lambda will be set up through an API Gateway which will provide us with an endpoint we can make a request to.
AWS Lambda lets you run code without provisioning or managing servers.
Amazon API Gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale.
Project setup
I’ll be assuming some familiarity with working from the CLI.

Pre-requisites

  • Node.js v6.5.0 or later
  • An AWS account (the free tier provides 1 million Lambda requests per month.)

Installing the Serverless Framework

Via Yarn:
$ yarn global add serverless 
Or via npm:
$ npm install -g serverless 

Setup Provider Credentials

The Serverless framework is provider-agnostic, as it supports most major cloud service providers. In this tutorial we’ll be leveraging AWS Lambda so we’ll need to provide the Serverless Framework with our AWS credentials. This will allow the framework to provision resources on our behalf within our AWS account.
Watch this short video which will walk you through provisioning the Serverless Framework with your AWS credentials.

Directory Setup

Let’s create a new directory to house the Serverless files we’ll be creating:
$ mkdir serverless-hello-world 
Infrastructure as Code
Serverless supports the infrastructure as code paradigm. This means that we’ll create code that tells AWS what services need to be setup in our stack to support our Lambda. This is great because we can easily setup and teardown our stack with a few simple commands.
Serverless leverages YAML for this. So we’ll need to create a serverless.yml file to tell Serverless what our Lambda function needs within the AWS environment. This should be created inside the root directory we created earlier.
Add the following to the file:
serverless.yml
service: serverless-hello-world # Name of our service within AWS frameworkVersion: '>=1.4.0 <2.0.0' provider: name: aws # Cloud service provider runtime: nodejs8.10 # Node.js Runtime stage: dev # Development ENV region: us-west-2 # AWS Region functions: hello: # Lambda function handler: index.hello # The handler for this function events: # Event that triggers this Lambda - http: # Creates API Gateway endpoint trigger path: /hello # Path for this endpoint method: get # HTTP method cors: # Everything this line and after is for CORS support origin: '*' headers: - Content-Type - X-Amz-Date - Authorization - X-Api-Key - X-Amz-Security-Token - X-Amz-User-Agent - X-Requested-With allowCredentials: false 
Take some time to review the annotations I provided within the file. This file contains everything that’s needed for Serverless to generate CloudFormation templates and deploy your Lambda stack to AWS.
Lambda Handler
Before we can do our first deploy and test out our Lambda function, we need to actually write our Lambda handler. If you noticed in the serverless.yml we had the line handler: index.hello. This tells Serverless to look for our handler code in a file called index.js in a module named hello.
That doesn’t exist yet, so let’s create it now:
index.js
// CORS response headers const responseHeaders = { 'Access-Control-Allow-Origin' : '*', 'Access-Control-Allow-Credentials' : false, 'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent,X-Requested-With', }; // Lambda handler const hello = (event, context, callback) => { response = { statusCode: 200, // Return HTTP 200 headers: responseHeaders, // For CORS support body: JSON.stringify({ message: 'Hello World' }), // Response body }; callback(null, response); }; module.exports = { hello, // index.hello }; 
This is a very basic handler but I’ll walk you through what it does. It listens for an HTTP event to trigger the Lambda handler. Once it does, an event and context object are passed to the handler. We won’t use them in this handler, but in many cases you would leverage data coming in from these objects (i.e. params, request info).
Here we just form a simple “Hello World” response in JSON format. Along with the JSON payload we add CORS headers and a HTTP status of 200. We then wrap that into our callback to return our response back out.
Deploy and Test
We can now easily deploy our code to AWS with a single command.
From your project root directory:
$ serverless deploy 
If the deploy was successful you should see something like the following in our command prompt:
Successful Deploy:
Serverless: Stack update finished... Service Information service: serverless-hello-world stage: dev region: us-west-2 stack: serverless-hello-world-dev api keys: None endpoints: GET - https://nh99ag777b.execute-api.us-west-2.amazonaws.com/dev/hello functions: hello: serverless-hello-world-dev-hello 
To test it is all working we can copy and paste the URL from the GET endpoint into our browser.
https://nh99ag777b.execute-api.us-west-2.amazonaws.com/dev/hello (Example URL)
You should see the following JSON returned when the page loads:
Successful Response:
{ message: "Hello World" } 
Teardown
Feel free to leave the Lambda up and running. You do have 1 million free requests each month with free tier. However, at some point you’re probably going to want to remove it from your AWS account.
To remove the entire stack you simply run the following from your project’s root directory:
$ serverless remove 
Conclusion
My hope with this article was to intrigue and entice you to explore the Serverless framework in more depth. The Hello World Lambda we wrote, deployed and tested in a matter of minutes should give you a sense of how quickly you can accomplish things using Serverless. I do hope to write some more advanced articles on Serverless in the near future.