AWS Serverless Node Rest API using lambda function, api gateway and serverless framework | CrewCode Solutions

AWS Serverless Node Rest API using lambda function, api gateway and serverless framework

banner
banner
banner

AWS Serverless Node Rest API using lambda function, api gateway and serverless framework

In this blog, I will guide you through the process of creating a serverless API using Node.js, AWS Lambda, and API Gateway, all managed effortlessly with the Serverless Framework.We’ll cover everything from setting up your project to deploying your API in AWS. By the end of this tutorial, you’ll have a fully functional API that’s scalable, cost-efficient, and requires no server management.

Step 1 Install Node Js, NPM and Serverless framework

Install Node.js and npm. Install the Serverless Framework

npm install -g serverless

Configure AWS credentials:

aws configure

Step 2 Create a New Serverless Project

npx serverless

The command will create serverless node, express api project for you along with the serverless.yml file

page

page

Step 3 Define Your Serverless Configuration

Customize the serverless.yml with the api according to your needs, all the api will be defined under functions->api->handler in this handler.handler handler is the name of the file and handler after dot is the name of the lambda function inside handler

serverless.yml file

# "org" ensures this Service is used with the correct Serverless Framework Access Key.
org: crewcode
# "app" enables Serverless Framework Dashboard features and sharing them with other Services.
app: node-api
# "service" is the name of this project. This will also be added to your AWS resource names.
service: node-api

provider:
  name: aws
  runtime: nodejs20.x

functions:
  api:
    handler: handler.handler
    events:
      - httpApi: "*"

handler.js file

const serverless = require("serverless-http");
const express = require("express");
const app = express();

app.get("/", (req, res, next) => {
  return res.status(200).json({
    message: "Hello from root!",
  });
});

app.get("/hello", (req, res, next) => {
  return res.status(200).json({
    message: "Hello from path!",
  });
});

app.use((req, res, next) => {
  return res.status(404).json({
    error: "Not Found",
  });
});

exports.handler = serverless(app);

Step 4 Deploy the application to AWS:

npx serverless deploy