Subscribe a Lambda function to receive notifications from an Amazon SNS topic using an Amazon SDK - Amazon Simple Notification Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Subscribe a Lambda function to receive notifications from an Amazon SNS topic using an Amazon SDK

The following code examples show how to subscribe a Lambda function so it receives notifications from an Amazon SNS topic.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples:

C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

//! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an AWS Lambda function. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param lambdaFunctionARN: The ARN for an AWS Lambda function. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeLambda(const Aws::String &topicARN, const Aws::String &lambdaFunctionARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("lambda"); request.SetEndpoint(lambdaFunctionARN); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • For API details, see Subscribe in Amazon SDK for C++ API Reference.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class SubscribeLambda { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <lambdaArn> Where: topicArn - The ARN of the topic to subscribe. lambdaArn - The ARN of an AWS Lambda function. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String lambdaArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnValue = subLambda(snsClient, topicArn, lambdaArn); System.out.println("Subscription ARN: " + arnValue); snsClient.close(); } public static String subLambda(SnsClient snsClient, String topicArn, String lambdaArn) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("lambda") .endpoint(lambdaArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); return result.subscriptionArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • For API details, see Subscribe in Amazon SDK for Java 2.x API Reference.

JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Create the client in a separate module and export it.

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

Import the SDK and client modules and call the API.

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function. */ export const subscribeLambda = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "lambda", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; };
Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

suspend fun subLambda(topicArnVal: String?, lambdaArn: String?) { val request = SubscribeRequest { protocol = "lambda" endpoint = lambdaArn returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) println(" The subscription Arn is ${result.subscriptionArn}") } }
  • For API details, see Subscribe in Amazon SDK for Kotlin API reference.

For a complete list of Amazon SDK developer guides and code examples, see Using Amazon SNS with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.