Setting up Serverless Framework

Feb 6th 2019 by Omar Reyes

Setting up Serverless Framework.

In this tutorial I will assume that you have an AWS account. If you don't, you can sign up for a free tier here: AWS Free Tier.

We will be using Serverless Framework to manage our Amazon Web Services.

The Serverless Framework helps you develop and deploy your AWS Lambda functions, along with the AWS infrastructure resources they require. It's a CLI that offers structure, automation and best practices out-of-the-box, allowing you to focus on building sophisticated, event-driven, serverless architectures, comprised of Functions and Events. - serverless.com

Install Serverless Framework
npm install -g serverless
Configure Serverless Framework with your AWS Credentials

Official AWS Tutorial on generating AWS Credentials

export AWS_ACCESS_KEY_ID=<your-key-here>
export AWS_SECRET_ACCESS_KEY=<your-secret-key-here>
Generate a new Serverless Framework project
mkdir scorpion-encounters && cd scorpion-encounters
sls create --template aws-nodejs --path back-end
Open the Serverless Framework project in your preferred IDE. I will be using VS Code.
cd back-end
code .
Edit serverless.yml file and set it to:
service: scorpion-encounters # NOTE: update this with your service name

provider:
  name: aws
  runtime: nodejs8.10

functions:
  getScorpion: # AWS Lambda function
    handler: handler.scorpion # Run scorpion function from handler.js
    events: # The Events that trigger this Function
      - http:
          path: scorpion
          method: get

serverless.yml tells Serverless Framework what AWS services to deploy. In our case we are deploying an API Gateway service with the endpoint of {get} /scorpion that will execute an AWS Lambda function when the endpoint is called.

Edit handler.js file and set it to:
'use strict';

module.exports.scorpion = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Encountered a scorpion!'
    }),
  };
};

This handler.js file contains one simple function called scorpion that will return a JSON response with a status code 200 to AWS Lambda.

Deploy your application
sls deploy

You should see the following in your terminal deployed list

cloudformation

If you visit the endpoint GET - https://dlsse10upf.execute-api.us-east-1.amazonaws.com/dev/scorpion your first API will successfully respond with:

{"message":"Encountered a scorpion!"}

As it sits AWS Lambda does not support ES6 but with Babel and Webpacks, we'll be able to have all of the ES6 features running on AWS Lambda.

Next tutorial: Scorpion Encounters 🦂 - Adding ES6 support to Serverless Framework

Share this post