Monday, November 20, 2017

Rest API using AWS Lamda, Serverless and Nodejs


1) AWS Lamda - If you are not aware of lamda function, please visit the following link.

2) Serverless Framework - I am using serverless to deploy my aws infrastructure. Please visit the following article to setup the serverless in your local box.
You don't need to create any project though.


If you have configured serverless for aws successfully then verify the installations by typing the command in the terminal. Your version number may not match mine.

$node -v
$sls -v
$aws --version
aws-cli/1.11.127 Python/3.6.2 Darwin/17.2.0 botocore/1.5.90
$cat ~/.aws/credentials 

I have already created the sample nodejs lamda project with serverless. Please find the following  github link.

Checkout the code.

git clone

handler.js : (lamda code goes here)

'use strict';

module.exports.helloWorld = (event, context, callback) => {
  const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*', // Required for CORS support to work
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,

  callback(null, response);


# Welcome to serverless. Read the docs

# Serverless.yml is the configuration the CLI
# uses to deploy your code to your provider of choice

# The `service` block is the name of the service
service: serverless-hello-world

# The `provider` block defines where your service will be deployed
  name: aws
  runtime: nodejs6.10

# The `functions` block defines what code to deploy
    handler: handler.helloWorld
    # The `events` block defines how to trigger the handler.helloWorld code
      - http:
          path: hello-world
          method: get
          cors: true

To define a rest endpoint we have to mention the method (get or post) and path inside events -> http.
cors: true will enable the cross.

To know more about it please visit the (

If you want to push the same code to your aws environment then run the following command.

$sls deploy

Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (967 B)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
Serverless: Stack update finished...
Service Information
service: serverless-hello-world
stage: dev
region: us-east-1
api keys:
  GET -
  helloWorld: serverless-hello-world-dev-helloWorld

- Go to the browser and enter the GET endpoint URL. Your's will be different than mine. Mine is for testing purpose. It wont be available for you.

- You can see the event object that lamda return as a response in the browser.

* For more information please visit the following link.

Create your first nodejs lamda function using serverless framework

AWS Lamda :

If you are not aware of lamda function, please visit the following link to know about it.

Serverless Framework :

Serverless framework is the toolkit for deploying and operating serverless architectures. The framework can manage deploying infrastructure and code to AWS, Google Cloud Platofrm, Microsoft Azure and IBM Openwhisk.
If you want to launch your first lamda function to cloud then this framework will definitely help you.

Serverless Setup for Lamda

1) Install nodejs: (Node.js v6.5.0 or later is required)

$node -v

2) Install serverless framework CLI.

npm install -g serverless

$serverless -v

3) Install AWS-CLI.

$aws --version
aws-cli/1.11.127 Python/3.6.2 Darwin/17.2.0 botocore/1.5.90

If you need any help to install AWS-CLI please refer the following article.

3) Create AWS Admin user and get the keys.

To manage the aws resource serverless needs AWS account credentials which has the required roles and permissions to manage the aws infrastructure. If you don't have a AWS account create a free one.

- Create an user having administrator access (which i think easy to test) and get the access key and secret key for that user.

Please follow the following article to know how to create aws user and how to add specific roles.

Don't worry about the name of the article. It gives you the information about how to add an aws user,  specific role and how to access the keys.

4) Configure credentials using aws-cli.

Go to the console and type

$ aws configure
AWS Access Key ID [****************]:
AWS Secret Access Key [****************]:
Default region name [None]:
Default output format [None]:

5) Create a nodejs project using npm

Go to the console, create folder called test-lamda, go inside and type "npm init". Follow the instructions.

6) Create a lamda function using serverless

Go to console, Inside your nodejs project folder type

$serverless create --template aws-nodejs

Serverless: Generating boilerplate...
 _______                             __
|   _   .-----.----.--.--.-----.----|  .-----.-----.-----.
|   |___|  -__|   _|  |  |  -__|   _|  |  -__|__ --|__ --|
|____   |_____|__|  \___/|_____|__| |__|_____|_____|_____|
|   |   |             The Serverless Application Framework
|       |                 , v1.18.1

Serverless: Successfully generated boilerplate for template: "aws-nodejs"

Serverless: NOTE: Please update the "service" property in serverless.yml with your service name

Please check the handler.js and serverless.yml file.

handler.js :

It has a single lamda function called "hello" which has 3 input parameters i)event ii) context iii)callback

event contains the req object that has information about path, httpMethod, headers etc.
This basic lamda function when invoked will create a response object and send it back.


This file has all the aws infrastructure details that serverless needs to configure when enabled. You can see only service and provider is enabled. You can enable any other features as per requirement

7) Deploy your lamda function to AWS

Go to console, Inside your nodejs project folder type.

$serverless deploy

Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
Serverless: Stack create finished...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (1.29 KB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
Serverless: Stack update finished...
Service Information
service: test-lamda-serverless
stage: dev
region: us-east-1
stack: test-lamda-serverless-dev
api keys:
  hello: test-lamda-serverless-dev-hello

8) Invoke your lamda function

$sls invoke --function hello
    "statusCode": 200,
    "body": "{\"message\":\"Go Serverless v1.0! Your function executed successfully!\",\"input\":{}}"


* sls is short form of serverless

9) Check the logs.

$sls logs -f hello -t

START RequestId: 3cc05fc9-cee9-11e8-a9ca-f960d9ae7ppp Version: $LATEST
END RequestId: 3cc05fc9-cee9-11e8-a9ca-f960d9ae7ppp

REPORT RequestId: 3cc05fc9-cee9-11e8-a9ca-f960d9ae7ppp  Duration: 0.83 ms       Billed Duration: 100 ms         Memory Size: 1024 MB    Max Memory Used: 20 MB

* f is short form of function, hello is the function name


1) nodejs v6.5.0 or later
2) npm install -g serverless
3) aws configure <Configure aws admin account access key and secret>
4) npm init
5) serverless create --template aws-nodejs
6) serverless deploy
7) sls invoke --function hello

* For more details on serverless framework for aws please visit following links:

What is AWS Lamda ?

AWS Lambda is a serverless compute service that runs the code in response to events.
For ex: When a image is uploaded to Amazon s3 bucket a lamda function can be triggered and resize the image and store it back. Lamda can respond to HTTP request via Amazon API Gateway. One can move their backend code that is being served from nodejs or any other app server to lamda.

Where lamda code runs ?

Lamda code runs on the server manages by AWS.
AWS automatically manages the underlying compute resources. It manages all the server management, provisioning, scaling, performance, security, monitoring, logging etc. So user does not need to worry about anything other than writing the code.

What is Serverless ?

You must have already got the answer by now. We don't need to provision any server while running our lamda code. That does not mean there is no server. Its there but we can not see it. Amazon will manage the server for us. We need to write the code, put it in lamda and AWS will take care of the rest. The server is kind of hidden from us so we call it serverless.

What is lamda function ?

The code we run on AWS Lambda is called a “Lambda function.” Once it is ready it is always available. These functions are stateless. They should ideally perform a unit of work. Each Lambda function runs in an isolated computing environment with its own resources. I would say these are nano service which can group together to create micro-service or itself can be called mico-service
AWS will invoke copy of as many lamda function as it needs to respond to incoming events. This way AWS manages scale and performance.

What are the languages that lamda supports ?

At this point we can write our code in nodejs, java, python and C#. Lamda has support for 3rd party libs and native libs.

How much we need to pay for the lamda service ?

We need to pay only for the compute time of the server. The server will not run for ever. It will be invoked only when there is an incoming event to the lamda.

For more information :

Sunday, November 19, 2017

How to start your Angular 4 project ?

What is Angular 4 ?

- AngularJS came on 2010 and Angular 2 came on mid 2016 with complete rewritten of framework in Typescript.
- Angular 4 is a version match not a upgrade to Angular 2.
- Angular 4 is just called Angular.

Create Angular 4 Project :

Setup :

1) node and npm should be installed. (

- If you already installed node and wants to update please check the following link. (Its for Mac)

$ node -v

2) Install angular CLI

$ npm install -g @angular/cli

$ ng -v
@angular/cli: 1.4.4
node: 6.11.3
os: darwin x64

Use angular CLI to create a new hello-world project

$ ng new hellow-world
installing ng
  create .editorconfig
  create tslint.json
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Successfully initialized git.
Project 'hellow-world' successfully created.

Install Visual Studio Code : (
Open the editor and type Shift + Command + P (from Mac)

Search for 'Path', and Install

Go inside the project folder and type "code ."
It will open the project folder in VS Code editor or you can open the project folder directly from editor.

Project folder structure will look like the below.

Serve the Angular Code

hellow-world $ ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
Date: 2017-09-07T15:35:06.229Z                                                          
Hash: c2e3ddcf0d5dd2646b8f
Time: 8944ms
chunk {inline} inline.bundle.js, (inline) 5.83 kB [entry] [rendered]
chunk {main} main.bundle.js, (main) 8.44 kB {vendor} [initial] [rendered]
chunk {polyfills} polyfills.bundle.js, (polyfills) 209 kB {inline} [initial] [rendered]
chunk {styles} styles.bundle.js, (styles) 11.3 kB {inline} [initial] [rendered]
chunk {vendor} vendor.bundle.js, (vendor) 2.27 MB [initial] [rendered]

webpack: Compiled successfully.

visit localhost:4200 in browser

Entry Point:

main.ts -> platformBrowserDynamic().bootstrapModule(AppModule);

Minor Modification :

- Go to app.component.ts and change,

export class AppComponent {
  title = 'My first Angular app';

- Check the command prompt : 

web pack which is integrated build tool with angular cli compiled and created few bundle.js files and browser being refreshed automatically with the new content.

Before you start writing code for your angular project, please get a basic understanding of typescript. If you are already familiar ignore the following article.