Create a Serverless backend with AWS Lambda Function, Amazon API Gateway and Serverless framework
Published: 2021-11-23 22:30:28

---
title: Create a Serverless backend with AWS Lambda Function, Amazon API Gateway and Serverless framework
published: true
description: Serverless backend may also be called Backend as a Service (Baas) and Function as a Service(Faas).
tags: 
cover_image: https://miro.medium.com/max/528/1*nlyFQ6_S2z7tooasrCWQHA.png
---

Serverless backend may also be called Backend as a Service (Baas) and Function as a Service(Faas).

According to Wikipedia, **Serverless computing** is a cloud computing execution model in which the cloud provider allocates machine resources on-demand, taking care of the servers on behalf of their customers.

### Pros of a Serverless architecture

1. Serverless is inherently scalable, it will be able to handle an unusually high number of requests.

1. Low cost and more efficient because you only pay when your Serverless function is running

1. Easy to deploy and update

1. No server management is required

### Cons of a Serverless architecture

1. Serverless is not built for long-running processing, it has a time frame. For instance, AWS Lambda timeout after 15 minutes.

1. It is difficult to debug because you will be dependent on your providers for debugging and monitoring tools

1. Long-running processing could be more costly on serverless compared to a dedicated server

1. It may take some time for your serverless backend to handle that first function request, so, you might need to keep it in a running state.

I will be creating a Serverless backend endpoint that returns information about the client’s OS information with the following tools:

* **Serverless framework** — a more general-purpose tool for deploying and managing **serverless** application

* **AWS Lambda** — a serverless compute service that lets you run code without provisioning or managing servers, creating workload-aware cluster scaling logic, maintaining event integrations, or managing runtimes

* **API Gateway** — a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale

* **Nodejs** — a JavaScript runtime built on Chrome’s V8 JavaScript engine

### To get started:

* You must already have [Nodejs](https://nodejs.org/en/download/) installed on your local machine,

* you also have an [AWS account](https://aws.amazon.com/resources/create-account/),

* you also have to create an [IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html#id_users_create_console) with programmatic access but for the sake of this article, I’ll be using the root user,

* copy the access key id and secret access key from your [AWS console](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html)

*Install [Serverless](https://www.serverless.com/) framework globally using npm*

    npm install -g serverless

*Configure serverless AWS credentials*

    serverless config credentials --provider aws --key AKJAPB7TR3*** --secret ****F4WA1JfG1sx9+7/+kKg/a

Replace the key and secret you copied from your AWS console. You can use serverless with different providers like Azure, AWS, GCP etc.

*Create a serverless project using the Serverless AWS Nodejs template*

    serverless create --template aws-nodejs --path clientOs

The above command will create a folder called *clientOs *and inside this folder, you’ll see the following files/folders:

* .serverless folder (*This folder contains generated CloudFormation file and zipped bundle*, *the folder gets regenerated every time you run* **serverless deploy**

* .gitignore file

* handler.js file

* serverless.yml file ( *This file contains serverless deployment configuration*)

handler.js
```
'use strict';
const os = require('os');

module.exports.getOsInfo = async (event) => {
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        osName: os.hostname(),
        osPlatform: os.platform(),
        osCPU: os.cpus(),
        // 1mb = 1048576
        osMemory: os.totalmem() / 1048576,
      },
      null,
      2
    ),
  };
};

```

I updated the *handler.js* to get client’s operating system information. All I did was to import *os* from Nodejs library and call different methods like hostname(), platform() etc.

serverless.yml
```
service: clientos

provider:
  name: aws
  runtime: nodejs12.x

functions:
  getOsInfo:
    handler: handler.getOsInfo
```

I also updated the *serverless.yml* with the new function we just created. I added *getOsInfo* function.

*Test the function locally*

    sls invoke local -f getOsInfo

*Deploy the function to AWS*

    sls deploy

You can login into your AWS console, search for Lambda, under functions, you’ll see your newly deployed function

### **Amazon API Gateway**

[Amazon API Gateway](https://aws.amazon.com/api-gateway/) is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale. APIs act as the “front door” for applications to access data, business logic, or functionality from your backend services. Using API Gateway, you can create RESTful APIs and WebSocket APIs that enable real-time two-way communication applications. API Gateway supports containerized and serverless workloads, as well as web applications.

I am going to create an API endpoint for the *getOsInfo* function using AmazonAPI Gateway. It’s quite easy with serverless framework, all you need to do is to add some lines of code in serverless.yml and deploy

 ```
events:
  - http:
      path: client/os
      method: get
```

We add events with the type http, then the route and the API method which is get.

```
service: clientos

provider:
  name: aws
  runtime: nodejs12.x

functions:
  getOsInfo:
    handler: handler.getOsInfo
    events:
      - http:
         path: client/os
         method: get
```

Your updated serverless.yml should look like this.

Deploy the function to AWS

    sls deploy

Check your console, you should see something like this

    endpoints:
      GET - [https://shs8k2mrea.execute-api.us-east-1.amazonaws.com/dev/](https://shs8k2ryia.execute-api.us-east-1.amazonaws.com/dev/say/hello)client/os

You can copy the URL and test it on your browser or Postman or whichever tool you prefer.

### Summary

1. We learnt the definition of Serverless computing

1. We learnt the pros and cons of Serverless

1. We learnt how to create a serverless backend with API using serverless framework, AWS Lambda, Amazon API Gateway and Nodjes

1. We learnt how to test functions locally

1. We learnt how to deploy functions

In my next article, I'll be showing you how to deploy your serverless applications using cloudFormation templates