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.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// This example shows how to use Amazon Simple Notification Service /// (Amazon SNS) to add a new Amazon SNS topic. The example was created /// using the AWS SDK for .NET version 3.7 and .NET Core 5.0. /// </summary> public class CreateSNSTopic { public static async Task Main() { string topicName = "ExampleSNSTopic"; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); var topicArn = await CreateSNSTopicAsync(client, topicName); Console.WriteLine($"New topic ARN: {topicArn}"); } /// <summary> /// Creates a new SNS topic using the supplied topic name. /// </summary> /// <param name="client">The initialized SNS client object used to /// create the new topic.</param> /// <param name="topicName">A string representing the topic name.</param> /// <returns>The Amazon Resource Name (ARN) of the created topic.</returns> public static async Task<string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName) { var request = new CreateTopicRequest { Name = topicName, }; var response = await client.CreateTopicAsync(request); return response.TopicArn; } }
  • API の詳細については、AWS SDK for .NETAPI CreateTopicリファレンスのを参照してください

C++
SDK for C++
注記

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

//! Create an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param topicName: An Amazon SNS topic name. \param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::createTopic(const Aws::String &topicName, Aws::String &topicARNResult, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::CreateTopicRequest request; request.SetName(topicName); const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request); if (outcome.IsSuccess()) { topicARNResult = outcome.GetResult().GetTopicArn(); std::cout << "Successfully created an Amazon SNS topic " << topicName << " with topic ARN '" << topicARNResult << "'." << std::endl; } else { std::cerr << "Error creating topic " << topicName << ":" << outcome.GetError().GetMessage() << std::endl; topicARNResult.clear(); } return outcome.IsSuccess(); }
  • API の詳細については、AWS SDK for C++API CreateTopicリファレンスのを参照してください

Go
SDK for Go V2
注記

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

package main import ( "context" "flag" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" ) // SNSCreateTopicAPI defines the interface for the CreateTopic function. // We use this interface to test the function using a mocked service. type SNSCreateTopicAPI interface { CreateTopic(ctx context.Context, params *sns.CreateTopicInput, optFns ...func(*sns.Options)) (*sns.CreateTopicOutput, error) } // MakeTopic creates an Amazon Simple Notification Service (Amazon SNS) topic. // Inputs: // c is the context of the method call, which includes the AWS Region. // api is the interface that defines the method call. // input defines the input arguments to the service call. // Output: // If success, a CreateTopicOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to CreateTopic. func MakeTopic(c context.Context, api SNSCreateTopicAPI, input *sns.CreateTopicInput) (*sns.CreateTopicOutput, error) { return api.CreateTopic(c, input) } func main() { topic := flag.String("t", "", "The name of the topic") flag.Parse() if *topic == "" { fmt.Println("You must supply the name of the topic") fmt.Println("-t TOPIC") return } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := sns.NewFromConfig(cfg) input := &sns.CreateTopicInput{ Name: topic, } results, err := MakeTopic(context.TODO(), client, input) if err != nil { fmt.Println(err.Error()) return } fmt.Println(*results.TopicArn) }
  • API の詳細については、AWS SDK for GoAPI CreateTopicリファレンスのを参照してください

Java
SDK for Java 2.x
注記

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

public static String createSNSTopic(SnsClient snsClient, String topicName ) { CreateTopicResponse result = null; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; }
  • API の詳細については、AWS SDK for Java 2.xAPI CreateTopicリファレンスのを参照してください

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 {CreateTopicCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters const params = { Name: "TOPIC_NAME" }; //TOPIC_NAME const run = async () => { try { const data = await snsClient.send(new CreateTopicCommand(params)); 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 CreateTopicリファレンスのを参照してください

Kotlin
SDK for Kotlin
注記

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

注記

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

suspend fun createSNSTopic(topicName: String): String { val request = CreateTopicRequest { name = topicName } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.createTopic(request) return result.topicArn.toString() } }
  • API の詳細については、「AWSSDK for Kotlin API リファレンス」を参照してくださいCreateTopic

PHP
SDK for PHP
注記

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

require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * Create a Simple Notification Service topics in your AWS account at the requested region. * * 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' ]); $topicname = 'myTopic'; try { $result = $SnSclient->createTopic([ 'Name' => $topicname, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
  • 詳細については、AWS SDK for PHP デベロッパーガイドを参照してください。

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

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 create_topic(self, name): """ Creates a notification topic. :param name: The name of the topic to create. :return: The newly created topic. """ try: topic = self.sns_resource.create_topic(Name=name) logger.info("Created topic %s with ARN %s.", name, topic.arn) except ClientError: logger.exception("Couldn't create topic %s.", name) raise else: return topic
  • API の詳細については、「AWSSDK for Python (Boto3) API リファレンス」のを参照してくださいCreateTopic

Ruby
SDK for Ruby
注記

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

require "aws-sdk-sns" # v2: require 'aws-sdk' def topic_created?(sns_client, topic_name) sns_client.create_topic(name: topic_name) rescue StandardError => e puts "Error while creating the topic named '#{topic_name}': #{e.message}" end # Full example call: def run_me topic_name = "TOPIC_NAME" region = "REGION" sns_client = Aws::SNS::Client.new(region: region) puts "Creating the topic '#{topic_name}'..." if topic_created?(sns_client, topic_name) puts "The topic was created." else puts "The topic was not created. Stopping program." exit 1 end end run_me if $PROGRAM_NAME == __FILE__
  • 詳細については、AWS SDK for Ruby デベロッパーガイドを参照してください。

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

Rust
SDK for Rust
注記

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

注記

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

async fn make_topic(client: &Client, topic_name: &str) -> Result<(), Error> { let resp = client.create_topic().name(topic_name).send().await?; println!( "Created topic with ARN: {}", resp.topic_arn().unwrap_or_default() ); Ok(()) }
  • API の詳細については、AWSSDK for Rust API リファレンスの「発行」を参照してくださいCreateTopic

SAP ABAP
SDK for SAP ABAP
注記

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

注記

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

TRY. oo_result = lo_sns->createtopic( iv_name = iv_topic_name ). " oo_result is returned for testing purposes. " MESSAGE 'SNS topic created' TYPE 'I'. CATCH /aws1/cx_snstopiclimitexcdex. MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'. ENDTRY.
  • API の詳細については、「CreateTopicSDK for SAP ABAP API リファレンス」の「AWSSDK for SAP ABAP API リファレンス」の