A Step-by-Step Guide to Integrate SNS with AWS API Gateway Himanshu Gupta, June 12, 2023December 14, 2023 In this blog, we will discuss how to integrate SNS with AWS API Gateway as an AWS Service without AWS Lambda.IntroductionIn today’s digital era, real-time communication is vital for various applications and services. AWS API Gateway provides a robust and scalable solution for building and managing APIs.AWS API Gateway is a powerful service that allows you to create, publish, and manage APIs for your applications. One of the critical functionalities it provides is the ability to send notifications via Amazon Simple Notification Service (SNS).In this beginner’s guide, we’ll explore how you can send SNS notifications directly from AWS API Gateway without needing AWS Lambda. But before starting building, let’s examine the benefits of integrating AWS API Gateway with SNS Topic without AWS Lambda.Benefits of SNS Integration with AWS API Gateway without using AWS LambdaSimplicity: Sending notifications directly from API Gateway to SNS eliminates the need for an intermediate Lambda function, simplifying the architecture and reducing the complexity of your application.Cost Efficiency: By bypassing Lambda, you can reduce costs associated with function invocations and execution time, especially for applications with low notification volumes or short execution durations.Scalability: Both API Gateway and SNS are highly scalable AWS services, allowing you to handle many concurrent requests for sending notifications to a growing user base.Real-Time Communication: SNS provides fast and reliable communication channels, enabling you to send real-time notifications to users via SMS, email, or push notifications directly from API Gateway.Seamless Integration: API Gateway can act as a central hub for integrating different systems, and using SNS as the communication channel allows for seamless integration with other third-party services or platforms.Lightweight Applications: If you have simple or light applications, you can use API Gateway with SNS directly. This will give you a simple and efficient solution without requiring extra infrastructure, such as Lambda functions.Flexibility: By sending notifications from API Gateway to SNS, you can create customized logic and manage notification workflows directly within API Gateway. This allows you to tailor the process to meet the specific requirements of your application.Reduced Latency: Eliminating the Lambda function can reduce the overall latency involved in sending notifications, providing quicker delivery and improving the responsiveness of your application.PrerequisitesTo follow along with this tutorial, you will needAn AWS account.Basic knowledge of AWS services.Access to the AWS Management Console.How to connect API Gateway with SNS – Step by Step ProcessStep 1 – Set up an SNS TopicGo to the AWS Management Console and navigate to the Amazon SNS service.Create a new topic and provide a name and display name for your topic.Use Standard TopicCreate a SNS Topic at AWS Management ConsoleAdd a subscription to the created topic. For this tutorial, we are using email as a destination.Add subscription to the SNS Topicadd email protocol for SNS topic subscriptionAfter adding the subscription successfully, you will receive a confirmation email. Please check your email and confirm the subscription.Once you confirm your subscription, the subscription’s status will change to “Confirmed.”AWS SNS Topic’s subscription is confirmedNote down the ARN (Amazon Resource Name) of the created topic. You will need it later.Step 2: Create an IAM Execution RoleCreate an IAM Execution Role at IAM Console with the below permissions:Permission to SNS Publish RoleAccess to API Gateway CloudWatch LogsStep 3: Create a REST API Open the AWS Management Console and navigate to the API Gateway service.Create a new API or select an existing API to work with.Create AWS Api gateway REST API to connect SNS TopicStep 4: Create a Resource for API with Query String ParametersIn this step, we will develop a REST API that can receive messages to be published along with the AWS SNS Topic ARN passed as Query String Parameters.Attach a resource and method to the API to the created ResourceAdd Resource to AWS API gatewayIn the Method Request Configurations, add Query Parameters for the requestAdd URL String Parameters to Method RequestIn the Integration Request configuration, select “AWS Service” as the Integration TypeChoose “Simple Notification Service (SNS)” as the AWS Service.Select the appropriate AWS region and enter the SNS topic ARN from Step 1integration request configurations for API gateway request to connect SNSUpdate the query string parameters in the integration request.Add mapping query parameters at API gateway Integration request parametersDeploy the API after making all changes aboveOnce you have deployed the API, test it by passing the appropriate query parameters.message: the message you want to sendtopic: arn of created SNS topicTesting of API Gateway SNS NotificationThis method is less secure because it exposes your SNS Topic ARN to the public, which attackers could take advantage of.Next, we will utilize a Request Template to integrate SNS Topic with AWS API gatewayStep 5: Create a Resource using Request BodyAttach a resource and method to the API to the created Resource.To begin, select “Models” from the left menu panel and create a model for request mapping.creating model for request body to get SNS message to be published to sns topic via API gatewayAdd Model to the Request MethodAdd Model to Model RequestIn the Integration Request configuration, select “AWS Service” as the Integration TypeChoose “Simple Notification Service (SNS)” as the AWS Service.Select the appropriate AWS region and enter the SNS topic ARN from Step 1To update the path for your SNS Topic based on your region, change the action type to “path” in the Integration request.Integration Request for API Gateway to connect with SNS TopicAdd the Content-type header ‘application/x-www-form-urlencoded‘ in the integration request.Please include the mapping template of the ARN of your SNS Topic under the “topic” section.AWS API Gateway Mapping Template CodeExplanation of Request Mapping:#set($topic=”<TOPIC_ARN>”): This line assigns the ARN of the SNS topic to the $topic variable. Make sure to replace the ARN with the actual ARN of your SNS topic#set($msg = $input.path(‘$.message’)): This line extracts the value of the message field from the request payload and assigns it to the $msg variable. Adjust the JSON path ($.message) based on your payload structure.Action=Publish&TopicArn=$util.urlEncode($topic)&Message=$util.urlEncode($msg): The following text is the completed string that will be sent as the request body. It is formatted in the same way as the query string parameters utilized in the AWS SNS API.Action=Publish specifies the action to publish a message to the SNS topic.TopicArn=$util.urlEncode($topic) encodes the $topic variable value and sets it as the TopicArn parameter in the request.Message=$util.urlEncode($msg) encodes the $msg variable value and sets it as the Message parameter in the request.We are implementing a modal for validating incoming requests and a request template for formatting them to match the published API. This eliminates the need to provide the topic ARN every time the API is called, allowing for the abstraction of the resource data below.Deploy the API after making all changes above.Once you have deployed the API, test it by passing the appropriate Request Body parameters.message: the message you want to sendTesting of API to post SNS messagesBest Practices:Here are some recommended best practices for integrating SNS with AWS API Gateway.Use IAM Roles and Policies: Create IAM roles and policies with the least privilege principle to grant API Gateway permission to publish messages to SNS topics. Enable Access Logging: Enable access logging for your API Gateway to track and monitor SNS integration requests. Access logs provide valuable insights for troubleshooting, monitoring, and auditing purposes.Implement Authorization: Implement authorization mechanisms such as AWS Identity and Access Management (IAM) or Amazon Cognito to control access to your API Gateway and restrict API usage only to authorized users or entities.Implement Authentication: To ensure the security of your SNS integration, consider implementing authentication mechanisms such as API keys, AWS Signature Version 4, or OAuth 2.0 to authenticate API clients before they can access your API Gateway and trigger SNS notifications.Enable HTTPS: Configure your API Gateway to only accept HTTPS requests to ensure data integrity and prevent unauthorized interception or tampering of sensitive information.Implement Rate Limiting: Apply rate limiting to your API Gateway to prevent abuse, protect against DDoS attacks, and ensure fair usage of your SNS integration. This helps maintain the availability and performance of your API.Implement Error Handling: Properly handle errors and exceptions that can occur during ConclusionCongratulations! You have successfully integrated AWS API Gateway with SNS Topic to send SNS notifications without using AWS Lambda.This guide taught you how to configure the API Gateway integration with SNS using Query Parameters and Request Body and test the functionality.This approach provides a straightforward and efficient way to incorporate real-time notifications into your applications and services.When implementing SNS notifications in a production environment, it is essential to prioritize security and authentication measures. Additionally, one can tailor and improve the API Gateway configuration to meet specific needs.AWS API Gateway offers many capabilities beyond this tutorial, such as request/response transformation, authentication, and rate limiting. Exploring these features will allow you to unleash the full potential of AWS API Gateway in building robust and scalable APIs.References:Amazon API Gateway Developer Guide Please leave this field emptyStay Up-to-Date with Our Weekly Updates. We don’t spam! Read our privacy policy for more info.Check your inbox or spam folder to confirm your subscription.FacebookTweetPinLinkedInEmail AWS Cloud Cloud Computing amazonawsaws apigatewayAWS SNSsns