AWS SDK を使用して Amazon SNS トピックを一覧表示する - AWSSDK コードサンプル

AWSDocAWS SDKGitHub サンプルリポジトリには、さらに多くの SDK サンプルがあります

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWS SDK を使用して Amazon SNS トピックを一覧表示する

次のコード例は、Amazon SNS トピックを一覧表示する方法を示しています。

.NET
AWS SDK for .NET
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// Lists the Amazon Simple Notification Service (Amazon SNS) /// topics for the current account. The code was written using the /// AWS SDK for .NET 3.7 and .NET Core 5.0. /// </summary> public class ListSNSTopics { public static async Task Main() { IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); await GetTopicListAsync(client); } /// <summary> /// Retrieves the list of Amazon SNS topics in groups of up to 100 /// topics. /// </summary> /// <param name="client">The initialized Amazon SNS client object used /// to retrieve the list of topics.</param> public static async Task GetTopicListAsync(IAmazonSimpleNotificationService client) { // If there are more than 100 Amazon SNS topics, the call to // ListTopicsAsync will return a value to pass to the // method to retrieve the next 100 (or less) topics. string nextToken = string.Empty; do { var response = await client.ListTopicsAsync(nextToken); DisplayTopicsList(response.Topics); nextToken = response.NextToken; } while (!string.IsNullOrEmpty(nextToken)); } /// <summary> /// Displays the list of Amazon SNS Topic ARNs. /// </summary> /// <param name="topicList">The list of Topic ARNs.</param> public static void DisplayTopicsList(List<Topic> topicList) { foreach (var topic in topicList) { Console.WriteLine($"{topic.TopicArn}"); } } }
  • API の詳細については、AWS SDK for .NETAPI ListTopicsリファレンスのを参照してください

C++
SDK for C++
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

//! Retrieve a list of Amazon Simple Notification Service (Amazon SNS) topics. /*! \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::listTopics(const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::String nextToken; // Next token is used to handle a paginated response. bool result = true; do { Aws::SNS::Model::ListTopicsRequest request; if (!nextToken.empty()) { request.SetNextToken(nextToken); } const Aws::SNS::Model::ListTopicsOutcome outcome = snsClient.ListTopics( request); if (outcome.IsSuccess()) { std::cout << "Topics list:" << std::endl; for (auto const &topic: outcome.GetResult().GetTopics()) { std::cout << " * " << topic.GetTopicArn() << std::endl; } } else { std::cerr << "Error listing topics " << outcome.GetError().GetMessage() << std::endl; result = false; break; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); return result; }
  • API の詳細については、AWS SDK for C++API ListTopicsリファレンスのを参照してください

Go
SDK for Go V2
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" ) // SNSListTopicsAPI defines the interface for the ListTopics function. // We use this interface to test the function using a mocked service. type SNSListTopicsAPI interface { ListTopics(ctx context.Context, params *sns.ListTopicsInput, optFns ...func(*sns.Options)) (*sns.ListTopicsOutput, error) } // GetTopics retrieves information about the Amazon Simple Notification Service (Amazon SNS) topics // Inputs: // c is the context of the method call, which includes the Region // api is the interface that defines the method call // input defines the input arguments to the service call. // Output: // If success, a ListTopicsOutput object containing the result of the service call and nil // Otherwise, nil and an error from the call to ListTopics func GetTopics(c context.Context, api SNSListTopicsAPI, input *sns.ListTopicsInput) (*sns.ListTopicsOutput, error) { return api.ListTopics(c, input) } func main() { cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := sns.NewFromConfig(cfg) input := &sns.ListTopicsInput{} results, err := GetTopics(context.TODO(), client, input) if err != nil { fmt.Println("Got an error retrieving information about the SNS topics:") fmt.Println(err) return } for _, t := range results.Topics { fmt.Println(*t.TopicArn) } }
  • API の詳細については、AWS SDK for GoAPI ListTopicsリファレンスのを参照してください

Java
SDK for Java 2.x
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

public static void listSNSTopics(SnsClient snsClient) { try { ListTopicsRequest request = ListTopicsRequest.builder() .build(); ListTopicsResponse result = snsClient.listTopics(request); System.out.println("Status was " + result.sdkHttpResponse().statusCode() + "\n\nTopics\n\n" + result.topics()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • API の詳細については、AWS SDK for Java 2.xAPI ListTopicsリファレンスのを参照してください

JavaScript
SDK forJavaScript v3)
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

別のモジュールでクライアントを作成し、エクスポートします。

import { SNSClient } from "@aws-sdk/client-sns"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SNS service object. const snsClient = new SNSClient({ region: REGION }); export { snsClient };

SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。

// Import required AWS SDK clients and commands for Node.js import {ListTopicsCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; const run = async () => { try { const data = await snsClient.send(new ListTopicsCommand({})); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScriptAPI ListTopicsリファレンスのを参照してください

Kotlin
SDK for Kotlin
注記

これはプレビューリリースの機能に関するプレリリースドキュメントです。このドキュメントは変更される可能性があります。

注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

suspend fun listSNSTopics() { SnsClient { region = "us-east-1" }.use { snsClient -> val response = snsClient.listTopics(ListTopicsRequest { }) response.topics?.forEach { topic -> println("The topic ARN is ${topic.topicArn}") } } }
  • API の詳細については、「AWSSDK for Kotlin API リファレンス」を参照してくださいListTopics

PHP
SDK for PHP
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * Returns a list of the requester's topics from your AWS SNS account in the region specified. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); try { $result = $SnSclient->listTopics([ ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
  • API の詳細については、AWS SDK for PHPAPI ListTopicsリファレンスのを参照してください

Python
SDK for Python (Boto3)
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def list_topics(self): """ Lists topics for the current account. :return: An iterator that yields the topics. """ try: topics_iter = self.sns_resource.topics.all() logger.info("Got topics.") except ClientError: logger.exception("Couldn't get topics.") raise else: return topics_iter
  • API の詳細については、「AWSSDK for Python (Boto3) API リファレンス」のを参照してくださいListTopics

Ruby
SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

require "aws-sdk-sns" # v2: require 'aws-sdk' def list_topics?(sns_client) sns_client.topics.each do |topic| puts topic.arn rescue StandardError => e puts "Error while listing the topics: #{e.message}" end end def run_me region = "REGION" sns_client = Aws::SNS::Resource.new(region: region) puts "Listing the topics." if list_topics?(sns_client) else puts "The bucket was not created. Stopping program." exit 1 end end run_me if $PROGRAM_NAME == __FILE__
  • 詳細については、AWS SDK for Ruby デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for RubyAPI ListTopicsリファレンスのを参照してください

Rust
SDK for Rust
注記

これはプレビューリリースの SDK に関するドキュメントです。SDK は変更される場合があり、本稼働環境では使用しないでください。

注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

async fn show_topics(client: &Client) -> Result<(), Error> { let resp = client.list_topics().send().await?; println!("Topic ARNs:"); for topic in resp.topics().unwrap_or_default() { println!("{}", topic.topic_arn().unwrap_or_default()); } Ok(()) }
  • API の詳細については、AWSSDK for Rust API リファレンスの「発行」を参照してくださいListTopics

SAP ABAP
SDK for SAP ABAP
注記

これはデベロッパープレビューリリースの SDK に関するドキュメントです。SDK は変更される場合があるため、本稼働環境での使用はお勧めできません。

注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

TRY. oo_result = lo_sns->listtopics( ). " oo_result is returned for testing purposes. " DATA(lt_topics) = oo_result->get_topics( ). MESSAGE 'Retrieved list of topics.' TYPE 'I'. CATCH /aws1/cx_rt_generic. MESSAGE 'Unable to list topics.' TYPE 'E'. ENDTRY.
  • API の詳細については、「ListTopicsSDK for SAP ABAP API リファレンス」の「AWSSDK for SAP ABAP API リファレンス」の