Go Server less - Build a web App Notification using AWS Lambda, API Gateway and SNS
Hello everyone welcome to this Simple project session we are going to do a small project session that is going to give you a basic understanding of AWS API_Gateway, AWS Lambda, and AWS SNS and how to integrate them. Let's get started !!!
Project Requirement
Let's assume a case where we have a website where we offer some tech services and we want the customer/client to connect to us through a contact form where they will enter their Name, Email and a message. Now, the need is to retrieve the details entered by our customer to our Email address so that we can reach out to them. we have to create an API that fetches the details entered by our customer and sends it to our mail there are numerous ways to do this we can set up a backend server and run the backend API, or we can go for any opensource managed solutions the first way is an overkill for a small amount of work that we are doing and servers are chargeable, the second method looks fairly easy but these open source solutions always comes with certain limits and the objective of doing this project is to learn more about different AWS services and integrating them so what we are going to use is that we going to create an API to fetch the info from the front-end in AWS API_Gateway and then integrate it to lambda for it to trigger SNS to send the response to our Email.
Architecture
Here is the architecture of what we are going to do
AWS LAMBDA
AWS Lambda is a serverless way of performing small tasks so that a need for a server for a small task can be avoided. Any task that will run within 15 minutes can be hosted in a Lambda function and executed, So for our scenario, Lambda is the best service to use. What we are going to do is we are going to write a NodeJS code that processes the Response from the customer and process it and triggers the SNS topic which will send the response to us via Email
Setting Up Lambda Function
Open Lambda in AWS Console, and Create Function
I have named it Email_response, Runtime as Node.js 18, architecture as x86_64
Now Permissions, we have to create a role that allows Lambda to access API_Gateway and SNS and hit Create
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sns:Publish", "apigateway:Invoke" ], "Resource": "*" } ] }
Let's code the Function,
import { SNSClient, PublishCommand } from "@aws-sdk/client-sns";
const snsClient = new SNSClient({ region: "ap-south-1" });
export const handler = async (event) => {
try {
console.log('Received event:', event);
// Parse the event body (assuming it's in JSON format)
const requestBody = (event);
console.log(requestBody.name)
// Construct the message
const params = {
TopicArn: 'arn:aws:sns:ap-south-1:<Aws account NO.>:Email_response',
Message: `Name: ${requestBody.name}\nEmail: ${requestBody.email}\nMessage: ${requestBody.message}`,
};
console.log('Sending message:', params);
// Publish the message to the specified SNS topic
await snsClient.send(new PublishCommand(params));
console.log('Message sent successfully');
// Return a successful response
return {
statusCode: 200,
body: JSON.stringify({ message: 'Message sent successfully' }),
};
} catch (error) {
console.error('Error:', error);
// Return an error response
return {
statusCode: 500,
body: JSON.stringify({ message: 'Error sending message' }),
};
}
};
This is a simple nodeJS function that gets the response via API_Gateway pushes the response to SNS and triggers it. If you want to know how to create an SNS topic refer to this Document Introduction to AWS SNS: A Beginner’s Guide to Setting up Notification Services.,
- Add a trigger that will trigger this function, In our case the API_Gateway is going to be the trigger, Let's leave this aside and create our API and navigate to AWS_API Gateway
AWS API GATEWAY
AWS API Gateway is a fully managed service that enables developers to create, deploy, and manage APIs at scale. It acts as a front door to backend services, allowing seamless integration with AWS Lambda, AWS services, or other HTTP endpoints. With API Gateway, users can efficiently build secure and flexible APIs to connect applications and manage access control, monitoring, and throttling.
Click Create API in AWS_API Gateway Console, Select REST API Give its name as Email_response-API
Now, Select Method as POST under Actions.
Choose the integration type as Lambda Function
We have to call this API from our website so we need to set CORS Either you can enable it for your website domain or use () I have used () to allow origin from anywhere
Deploy this API and note its invoke URL 7d******h.execute-api.ap-south-1.amazonaws..., This URL will be used to call this API
Note: We have an open API that can be called with a link if you are passing sensitive information in this API you can add Authorizations to make your API calls more secure.
REACT JS FRONT END
We have successfully set up all the required back for this project, Let's create a Front End for the contact form If you are well versed in React JS you can do this React form easily yourself but since the main focus of this project session is to learn about the integration of AWS services you can fork or clone the front-end from my Github Click Here., after cloning
npm install
npm start
Now try entering your name and email, message the details you entered will be sent to the email that has the SNS subscription.
Congrats !! You have learnt how to integrate several services in SNS
If you have any doubts about this Project contact me through my Social handles
HAPPY CODING !!!