snsapi.png
profile picture Somya Sharma
5 min read Jan 20, 2022
aws
sns

How To Connect SNS to API Gateway

aws
sns

What is Amazon API Gateway?

Amazon API Gateway is a fully managed service that allows developers to create, publish, maintain, monitor, and secure APIs at any scale. API Gateway handles thousands of concurrent API calls. At its basic, it is a service that allows us to create backend endpoints that we later request through the frontend of the application.

Features of Amazon API Gateway

  • Fully managed service by Amazon
  • Pay-as-you-go service
  • Supports authorization and access control, throttling, monitoring, and API version management.
  • Support for RESTful APIs and WebSocket APIs.
  • Console for building and testing API.
  • Integration with different other AWS services.
howApiGatewayWorks.png

What is Amazon SNS?

Amazon SNS is a managed service that provides message delivery from publishers to subscribers (also known as producers and consumers). It is a one-to-many relationship service. It consists of Topic (a logical access point that acts as a communication channel) and Subscriptions (Consumers- AWS Lambda, AWS SQS, Email, etc.). Publishers communicate asynchronously with subscribers by sending messages to a topic.

Features of Amazon SNS

  • Supports application-to-application messaging, where subscribers can be AWS Lambda, AWS SQS, HTTP/S endpoints, etc.
  • Supports application-to-person notifications, where subscribers can be a user email address, mobile number.
  • Supports several strategies( delivery retry policy, dead letter queue) that work together to provide message durability.
  • Supports message filtering which allows subscribers to only get the notification when the message adheres to the filter policy.
  • Provides different SNS API or Actions that enables you to build distributed web-enabled applications.
howSNSworks.png

Use-Case for connecting API Gateway to SNS

Suppose you are working on an application where there is a need to send different messages to certain users asynchronously. You can create an endpoint that takes the message to send to the user. We can connect API Gateway to SNS for this implementation.

The architecture will look like the following.

SNSAPIGatewayUsecase.png

How to connect API Gateway with SNS

1- Create an SNS Topic with an email subscription

createSNSTopic.png

Select email protocol and add endpoint (user mail).

createSubscription.png

After the subscription is created the endpoint will receive a confirmation mail and the status will remain pending until the user confirmed the subscription.

subscriptionPendingStatus.png emailConfirmation.png snsSubscriptionConfirmed.png

Once the user accepted the subscription the status will change to confirmed

confirmedSubscriptionStatus.png

2- Create an IAM Role for the API with sns Publish permission

Create a new IAM role

createNewRole.png

Create a policy with SNS publish permission.

createNewPolicy.png

Attach the policy to the newly created IAM role.

attachPolicy.png

3- Create the Rest Api

Create a new rest api

createRestAPI.png

Attach a resource and method to the api

methodandResource.png

Update the Integration Request of the api. In the Action, I am using Publish (SNS Publish API) to send message to the topic.

apiIntegration.png

Add query parameters in the method request

apiMethod.png

Update the query string parameters in the integration request

queryStrings.png

4- Deploy the API

5- After deploying the api test it by passing appropriate query parameters.

  • message : the message you want to send
  • topic : arn of created sns topic
testAPI.png

The user will receive the notification

emailReceived.png

We can use the above API for our use case but the only problem is that we have to pass the sns topic arn in query parameter whenever we want to send the message. It is not ideal to share the resource physical ID. So we will use a different way to connect api to sns.

Connecting API to SNS using request template

All the resource creation will remain the same except the Rest API. The Rest API will be using the request template.

What is the request template

In API Gateway, an API’s method request can take a payload in a different format from the corresponding integration request payload, as required in the backend. API Gateway lets you use mapping templates to map the payload from a method request to the corresponding integration request and an integration response to the corresponding method response.

A mapping template is a script expressed in Velocity Template Language (VTL) and applied to the payload using JSONPath expressions.

Update the above Rest API

Create a modal for the incoming request

createModal.png

Add the modal in the method request and update the request validator to validate body

attachRequestValidator.png

In the Integration request change the action type to path and update the path according to your respective region of SNS Topic.

updatedIntegrationRequest.png

Add the Content-type header in the integration request.

updateQueryStrings.png

Add the mapping template where topic will contain the arn of your SNS Topic.

mappingTemplate.png

Here I am using modal to validate the incoming request and a request template to format the incoming request according to the publish API. While using this we don’t need the topic arn each time to call the API. This helps us in providing abstraction with the underline resource data.

Test the api by passing the appropriate request body.

  • message: the message you want to send
TestUpdatedAPI.png

The user will receive the notification

messageReceived.png

All done, You can start consuming the api.

The entire process can be pretty confusing while doing it for the first time, so here a repository with a sample SAM application creates all the required resources.

Application Modernization Icon

Innovate faster, and go farther with serverless-native application development. Explore limitless possibilities with AntStack's serverless solutions. Empowering your business to achieve your most audacious goals.

Talk to us

Author(s)

Tags

Your Digital Journey deserves a great story.

Build one with us.

Recommended Blogs

Cookies Icon

These cookies are used to collect information about how you interact with this website and allow us to remember you. We use this information in order to improve and customize your browsing experience and for analytics and metrics about our visitors on this website.

If you decline, your information won’t be tracked when you visit this website. A single cookie will be used in your browser to remember your preference not to be tracked.

Talk to us