Explore the future of cloud computing with Innostax's guide on Serverless Framework Deployment using AWS Lambda.
The Serverless Framework stands as a robust instrument, streamlining the intricate chore of deploying and orchestrating serverless applications on diverse cloud platforms, among which Amazon Web Services (AWS) is notable. In this guide, our goal is to provide you with a comprehensive walkthrough of harnessing the Serverless Framework’s capabilities. We’ll demonstrate how to effortlessly deploy a basic JavaScript function onto AWS Lambda, make it accessible through API Gateway, and institute monitoring through AWS CloudWatch.This knowledge can prove invaluable, whether you are in the field of custom financial software development, healthcare software development, cross-platform mobile app development, software testing services, or any other domain where modern and efficient cloud-native applications are essential. By mastering the Serverless Framework, you’ll have a powerful tool at your disposal to create and deploy innovative solutions that cater to the evolving demands of your industry.
The aim of this guide is to furnish you with a comprehensive, step-by-step tutorial on the deployment of a serverless JavaScript function within AWS, facilitated by the Serverless Framework. Whether you’re exploring serverless computing for the first time or looking to enhance your current skill set, this tutorial aims to provide you with the following capabilities:
serverless.yml
file.By the conclusion of this article, you’ll have a firm grasp of harnessing the Serverless Framework’s capabilities to efficiently deploy and oversee serverless applications on the AWS platform. Furthermore, you’ll gain hands-on experience in deploying serverless functions and exposing them through API endpoints, laying the foundation for the development and scalability of serverless applications within your projects.
To follow along with this tutorial, you’ll need the following:
You’ll need to set the AWS credentials for the AWS CLI if you have not done that already. You’ll be using it along with the Serverless Framework to deploy the resources on AWS.
You can create the AWS credentials file by entering the following command in the terminal:
1 2 3 4 5 6 7 8 9 10 11 |
cat <<EOF > ~/.aws/credentials [default] aws_access_key_id = <REPLACE_WITH_YOUR_SECRET_KEY> aws_secret_access_key = <REPLACE_WITH_YOUR_ACCESS_KEY> EOF cat <<EOF > ~/.aws/config [default] region = eu-west-1 output = json EOF |
The Serverless Framework utilizes the IAM role to deploy resources on AWS. Enter the following command to create the role:
1 2 3 4 5 6 7 8 9 10 11 12 |
aws iam create-role --role-name serverlessLabs --assume-role-policy-document '{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }' |
This policy enables the role to be utilized by the AWS Lambda service.
Enter the following command to attach the AWSLambdaBasicExecutionRole policy to the role:
1 |
aws iam attach-role-policy --role-name serverlessLabs --policy-arn arn:aws:iam::aws:policy/AWSLambda_FullAccess |
To confirm the successful creation of the role, you can execute the following command to retrieve information about the IAM role:
1 |
aws iam get-role --role-name serverlessLabs |
Here’s what the information should look like:
The Serverless Framework is utilized to deploy this project, which consists of a straightforward JavaScript function deployed to AWS Lambda, API Gateway, and CloudWatch.
An HTTP GET request triggers the function, and it returns a basic string. The deployment of the function is in the eu-west-1 region.
First, install Serverless Framework using npm:
1 2 |
mkdir node-crud cd node-crud |
Next, install a serverless package project using the npm serverless command and then follow the prompt:
1 2 |
npm install -g serverless npm i prisma |
Run below command in project directory
1 |
npx prisma init |
This command does two things:
1 2 3 4 5 6 |
prisma/schema.prisma datasource db { provider = "postgresql" url = env("DATABASE_URL") } |
1 2 |
.env DATABASE_URL="postgresql://<username>:<password>@<hosted dbURL>:5432/mydb?schema=public" |
1 2 3 4 5 6 7 8 |
prisma/schema.prisma model Users { id String @id @default(uuid()) name String? @db.VarChar(255) email String? @db.VarChar(255) } |
1 2 3 4 |
Run commands npx prisma format npx prisma generate npx migrate dev |
Create handler.js file in root directory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
const { PrismaClient } = require("@prisma/client"); const prisma = new PrismaClient(); module.exports.create = async (event) => { try { const { body } = event; const { name, email } = JSON.parse(body); const newUser = await prisma.Users.create({ data: { name, email }, }); return { statusCode: 200, body: JSON.stringify(newUser), }; } catch (error) { return { statusCode: 500, body: JSON.stringify({ error: "Failed to create user: " + error.message, }), }; } }; module.exports.read = async () => { try { const users = await prisma.Users.findMany(); return { statusCode: 200, body: JSON.stringify(users) }; } catch (error) { return { statusCode: 500, body: JSON.stringify({ error: "Failed to fetch users: " + error.message, }), }; } }; module.exports.update = async (event) => { try { const { id } = event.pathParameters; const { body } = event; const { name, email } = JSON.parse(body); const updatedUser = await prisma.Users.update({ where: { id: parseInt(id), }, data: { name, email, }, }); return { statusCode: 200, body: JSON.stringify(updatedUser), }; } catch (error) { return { statusCode: 500, body: JSON.stringify({ error: "Failed to update user: " + error.message, }), }; } }; module.exports.delete = async (event) => { try { const { id } = event.pathParameters; const deletedUser = await prisma.Users.delete({ where: { id: parseInt(id) }, }); return { statusCode: 200, body: JSON.stringify({ message: "User deleted successfully", deletedUser, }), }; } catch (error) { return { statusCode: 500, body: JSON.stringify({ error: "Failed to delete user: " + error.message, }), }; } }; |
Folder structure
To start with the configuration, open the serverless.yaml file and delete all of its content and paste the following YAML code to define the microservice you will deploy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
service: postgres-crud-api provider: name: aws runtime: nodejs18.x functions: create: handler: handler.create events: - http: path: create method: post read: handler: handler.read events: - http: path: read method: get update: handler: handler.update events: - http: path: update/{id} method: put delete: handler: handler.delete events: - http: path: delete/{id} method: delete |
provider defines the AWS provider for your service. It specifies various configuration settings for AWS Lambda functions and other AWS resources.
You can use the command below to deploy the microservice on AWS:After a while, the deployment will be completed and you can see information like the endpoint, hosted on API Gateway, to trigger the function you just deployed.
1 |
sls deploy |
Applications
Functions
Resources
From the deployment, you have a single function named firstFunction, and a single HTTP GET endpoint.
You can call the function by using the GET endpoint, which is generated in the terminal after deploying it, in your browser.
The image above shows the functionality created in the deployed function running in the browser.
command.
Read
Create
Update
Delete
Serverless computing represents a dynamic paradigm for crafting and launching cloud-native applications. Throughout this guide, we’ve dived into the vast potential of serverless computing and illustrated the process of constructing and deploying serverless applications using the Serverless Framework and AWS.
You’ve embarked on your serverless journey, commencing with the setup of your development environment and progressing to the deployment of a fundamental JavaScript function, powered by AWS Lambda. Along this path, we’ve imparted knowledge about monitoring and logging through AWS CloudWatch.
Web Development Services in the United States