Connect AWS API Gateway with SNS Topic

A Step-by-Step Guide to Integrate SNS with AWS API Gateway

In this blog, we will discuss how to integrate SNS with AWS API Gateway as an AWS Service without AWS Lambda.

Introduction

In 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 Lambda

  • Simplicity: 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.

Prerequisites

To follow along with this tutorial, you will need

  • An AWS account.
  • Basic knowledge of AWS services.
  • Access to the AWS Management Console.

How to connect API Gateway with SNS – Step by Step Process

Step 1 – Set up an SNS Topic

  • Go 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 Topic
Create a SNS Topic at AWS Management Console
Create a SNS Topic at AWS Management Console
  • Add a subscription to the created topic. For this tutorial, we are using email as a destination.
Add subscription to the SNS Topic
Add subscription to the SNS Topic
add email protocol for SNS topic subscription
add email protocol for SNS topic subscription
  • After 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 confirmed
AWS SNS Topic’s subscription is confirmed
  • Note down the ARN (Amazon Resource Name) of the created topic. You will need it later.

Step 2: Create an IAM Execution Role

  • Create an IAM Execution Role at IAM Console with the below permissions:
    • Permission to SNS Publish Role
    • Access to API Gateway CloudWatch Logs

Step 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 Topic
Create AWS Api gateway REST API to connect SNS Topic

Step 4: Create a Resource for API with Query String Parameters

In 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 Resource
Add Resource to AWS API gateway
Add Resource to AWS API gateway
  • In the Method Request Configurations, add Query Parameters for the request
Add URL String Parameters to Method Request
Add URL String Parameters to Method Request
  • In the Integration Request configuration, select “AWS Service” as the Integration Type
  • Choose “Simple Notification Service (SNS)” as the AWS Service.
  • Select the appropriate AWS region and enter the SNS topic ARN from Step 1
integration request configurations for API gateway request to connect SNS
integration request configurations for API gateway request to connect SNS
  • Update the query string parameters in the integration request.
Add mapping query parameters at API gateway Integration request parameters
Add mapping query parameters at API gateway Integration request parameters
  • Deploy the API after making all changes above
  • Once you have deployed the API, test it by passing the appropriate query parameters.
    • message: the message you want to send
    • topic: arn of created SNS topic
Testing of API Gateway SNS Notification
Testing of API Gateway SNS Notification

This 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 gateway

Step 5: Create a Resource using Request Body

  • Attach 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 gateway
creating model for request body to get SNS message to be published to sns topic via API gateway
  • Add Model to the Request Method
Add Model to Model Request
Add Model to Model Request
  • In the Integration Request configuration, select “AWS Service” as the Integration Type
  • Choose “Simple Notification Service (SNS)” as the AWS Service.
  • Select the appropriate AWS region and enter the SNS topic ARN from Step 1
  • To 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 Topic
Integration Request for API Gateway to connect with SNS Topic
  • Add 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 Code
AWS API Gateway Mapping Template Code
  • Explanation 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 send
Testing of API to post SNS messages
Testing of API to post SNS messages

Best 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 

Conclusion

Congratulations! 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

AWS Community Builder | Software Architect @ Gigaforce | Serverless | Aspiring Entrepreneur | Quirky Introvert­čśé

Leave a Reply

Your email address will not be published. Required fields are marked *