Serverless with AWS API Gateway using AWS Lambda

Today we will learn how we can deploy a Node.js application to AWS Lambda with the help of Serverless Framework. We will combine AWS API Gateway with AWS Lambda, which will work as the entry point of the Lambda function.

AWS Lambda is a pay-per-use serverless service. You just deploy your code to AWS, and they handle the rest. It scales the node server automatically and has no downtime. AWS Lambda can be said as, Function as a Service. You deploy the code, and it gets invoked when called, processes, and returns.

Prerequisites:

  1. AWS account
  2. Node.js and npm
  3. Serverless Framework

1. Install and Configure the Serverless Framework -

npm install -g serverles

sudo sls config credentials --provider aws --key PUBLIC_KEY --secret SECRET_KEY

Make sure to add your IAM User’s public and secret key instead of the PUBLIC_KEY and SECRET_KEY.

2. boilerplate code -

We will create a new folder and will add some code in it. Go to your terminal and run the commands below.

<code><code>sudo mkdir sls-nodejs-app && cd sls-nodejs-app

Now run the create command to generate some starter code. This is called a serverless service.

sudo sls create -t aws-nodejs -n sls-nodejs-app

Only one more step before opening a code editor.

3. Installing dependencies -

You need to install a few modules using following commands.

npm init -y

npm install --save express serverless-http

4. Code -

You’ll see three files. Rename the handler.js to app.js just to make it simpler for us. Write whatever code you need to write in app.js file, just like a simple express app. Delete all the starter code and paste this code into the app.js. I am adding an express router with the following code:

Example:

const express = require('express');
const sls = require('serverless-http');
const app = express();
app.get('/test', (req, res, next) => {
   res.status(200).json('Hello World! This is test.')
})
module.exports.server = sls(app)

A simple express app.js page is ready. You can include simple routes in this.

Delete all the boilerplate code and paste this in serverless.yml file.

# serverless.yml

service: sls-nodejs-app

provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: us-east-2

functions:
  app:
    handler: app.server # giving the reference the file and exported method.
    events: # used for triggering the lambda functions
      - http: # Default AWS API Gateway HTTP event trigger
          path: /
          method: ANY
          cors: true
      - http: # for the proxy of the routes to the Express router
          path: /{proxy+}
          method: ANY
          cors: true

Following part of the code in above file is used to start the AWS API Gateway as a front door of Lambda function:

events: # used for triggering the Lambda functions
  - http: # Default AWS API Gateway HTTP event trigger
      path: /
      method: ANY
      cors: true

Ready to deploy!

Now run one simple command your app will be deployed!

sudo sls deploy

You will see a response like the following on your terminal:

Serverless: Packaging service…<br> Serverless: Excluding development dependencies…<br> Serverless: Uploading CloudFormation file to S3…<br> Serverless: Uploading artefacts…<br> Serverless: Uploading service .zip file to S3 (2.9 MB)…<br> Serverless: Validating template…<br> Serverless: Updating Stack…<br> Serverless: Checking Stack update progress…<br> …………..<br> Serverless: Stack update finished…<br> Service Information<br> service: sls-nodejs-app<br> stage: dev<br> region: us-east-2<br> stack: sls-nodejs-app-dev<br> api keys:<br> None<br> endpoints:<br> ANY - https://gar8wwcs5eab.execute-api.us-east-2.amazonaws.com/dev/<br> ANY - https://gar8wwcs5eab.execute-api.us-east-2.amazonaws.com/dev/{proxy+}<br> functions:<br> app: sls-nodejs-app-dev-app<br> layers:<br> None<br> Serverless: Removing old service artifacts from S3…

You can use the following route in the browser or Postman to see the result:
https://gar8wwcs5eab.execute-api.us-east-2.amazonaws.com/dev/test

The app is deployed. If it is required to make changes in the code just re-deploy it after making the changes by using the above command.

You can see the newly created Lambda function here -
https://us-east-2.console.aws.amazon.com/lambda/home

And for the API Gateway, you can see it here-
https://us-east-2.console.aws.amazon.com/apigateway/home

That’s it, Lambda function is ready to use!
Lambda is awesome when it is combined with HTTP event triggers such as AWS API Gateway.

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype