Amazon SNS API Guide
Use Chilkat.Rest with Amazon Simple Notification Service to manage topics and subscriptions, publish notifications, send SMS messages, and verify HTTPS deliveries. This guide connects 43 complete examples, from creating a standard topic to FIFO publishing, partial batch failures, and signed notification processing.
Choose a language to update all 43 example links below. Each link opens the complete example in that language. The guide text stays the same.
Before making requests
The examples require Chilkat 11.6.0 or later and an unlocked library. They use the commercial AWS partition and a regional endpoint such as sns.us-west-2.amazonaws.com. Set the region to match the topic or regional SMS account. Other AWS partitions require their own endpoint suffix and ARN partition. Replace the illustrative account IDs, topic and subscription ARNs, queue names, phone numbers, and local paths.
Read credentials from a private qa_data/aws/sns.json file with nonempty string fields access_key and secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. These examples read that file; they do not discover profiles, assume roles, or refresh credentials automatically. Keep it outside public web content and source control.
How these examples call SNS
| Step | Chilkat configuration |
|---|---|
| Sign API requests | Configure AuthAws with the credentials, region, service sns, and SignatureVersion=4; pass it to Rest.SetAuthAws. |
| Build a fresh POST form | Call ClearAllQueryParams, then add Action, Version=2010-03-31, the optional X-Amz-Security-Token, and operation parameters. FullRequestFormUrlEncoded("POST","/") sends these values in the signed body. |
| Verify transport and response | A Socket with certificate verification enabled supplies the TLS connection to Rest. Check transport completion, HTTP status, XML parsing, the expected response element, and required result fields. |
| Verify delivered notifications | Incoming SNS envelopes use a different signature scheme: Rsa verifies the delivery signature after Http securely retrieves the allowed signing certificate. This is separate from signing outgoing API requests. |
The API version date remains 2010-03-31. Parameter names and capitalization matter, including the lowercase names used by some SMS operations. Pass raw values to AddQueryParam; do not pre-encode a leading plus, Unicode text, JSON, or continuation token. Explicitly clear previous parameters before each request, especially when changing actions. See the SNS common parameters, Rest reference, and AuthAws reference.
Topics
A topic provides a named destination for publishers and distributes accepted messages to its subscriptions. Creating a topic with an already-owned name returns that topic's ARN; success does not prove that a new resource was created. Read its attributes before relying on existing configuration. The basic creation example creates a standard topic; FIFO creation is covered separately.
The listing example follows every NextToken, including after an empty page. It treats tokens as opaque, detects repetition, and reports incomplete enumeration if its page bound is reached. ListTopics returns up to 100 topics per response and has no MaxResults parameter. A changing inventory is not an atomic snapshot.
Subscriptions
Choose a protocol and its corresponding endpoint: an email address, an SMS phone number, an SQS queue ARN, or an HTTPS URL. The SQS endpoint is an ARN, not a queue URL. Its queue policy must separately permit SNS to send messages from the intended topic. Cross-account ownership can also affect confirmation and permissions.
Email and HTTPS subscriptions require endpoint confirmation. The examples use ReturnSubscriptionArn=false so a pending-confirmation result remains visible. An assigned ARN alone is not proof that delivery is active. For HTTPS, verify the confirmation envelope before using its token; then call ConfirmSubscription against a configured SNS endpoint. The confirmation example reads a received token from private sns_confirmation.json and requires authenticated unsubscribe. See Subscribe and ConfirmSubscription.
Use the regional or topic-specific paginated listing to find subscriptions. Pending entries are not usable confirmed subscription ARNs. GetSubscriptionAttributes reads the stored configuration; Unsubscribe removes the selected subscription. Protect endpoint addresses and policy details in diagnostic output.
- Subscribe an Email Address (Confirmation Required)
- Subscribe an SMS Phone Number to a Standard Topic
- Subscribe an SQS Queue to a Standard Topic
- List All Subscriptions in a Region with Pagination
- List All Subscriptions for a Topic with Pagination
- Read Subscription Attributes
- Confirm a Subscription with a Received Token
- Unsubscribe a Confirmed Subscription
Filtering and Delivery
Filter policies select which messages reach a subscription. With FilterPolicyScope=MessageAttributes, the example matches a String event attribute and a Number amount attribute. With MessageBody, it matches properties in the JSON body. Both examples select order-created events with an amount of at least 100. Scope and policy are separate writes; use a new or quiesced subscription when migrating. Readback confirms stored values, while propagation can take up to 15 minutes. See subscription filtering.
Raw delivery removes the SNS envelope for supported destinations. The raw-delivery example targets SQS; messages with more than ten attributes are discarded for a raw SQS subscription. The consumer receives the payload directly. A subscription RedrivePolicy instead sends undeliverable notifications to a compatible SQS dead-letter queue. Its queue policy and any KMS permissions must be configured separately. This is SNS delivery redrive, not consumer-side SQS redrive. See raw delivery and subscription attributes.
Publishing
Start with a UTF-8 message to a standard topic. The basic example checks bytes rather than characters and uses a fixed valid email Subject. The attribute example adds String, Number and Binary values, counting their names, types and values toward the payload limit. Binary values are base64-encoded for transport; their decoded bytes contribute to the size calculation.
The protocol-specific example sets MessageStructure=json. Its JSON object contains a string default and optional protocol-specific strings, including an SQS value that itself contains JSON. JsonObject handles the escaping. Message attributes are intended for the ordinary string-message form and are not included in that example. See Publish.
FIFO
The FIFO topic example uses a name ending in .fifo, enables FifoTopic, and chooses explicit deduplication IDs with FifoThroughputScope=MessageGroup. Use a compatible subscription topology and inspect attributes when reusing an existing topic.
Keep a stable MessageGroupId for each independently ordered stream. Assign a unique MessageDeduplicationId to each logical message and retain it when retrying that same message within the five-minute deduplication interval. The fixed IDs in the sample illustrate this relationship; replace them for new events. If content-based deduplication is enabled instead, SNS hashes the body without the attributes. A SequenceNumber is not proof of consumer completion. See FIFO deduplication.
Batches
PublishBatch sends up to ten messages to one topic. The example submits two uniquely identified entries and correlates every response by its entry ID. It rejects unknown, duplicate or missing result IDs and examines both the Successful and Failed collections even after HTTP 200. The combined message bodies and attributes must fit the topic's configured message-size limit. See PublishBatch.
Retry only appropriate failed entries, with bounded backoff and jitter; do not resend entries reported as successful. SenderFault helps distinguish request problems from failures that may be retryable. A transport failure or incomplete response leaves uncertain outcomes and requires reconciliation before retrying.
Configuration and Security
SetTopicAttributes changes one selected attribute. The encryption example configures a KMS key; publisher IAM permissions and the key policy must also permit its use. The policy example preserves existing statements and adds one S3 publisher constrained to a bucket and source account. It stops if its chosen statement ID already exists. Policy replacement has no conditional version check, so coordinate concurrent policy writers externally.
MaximumMessageSize defaults to 262,144 bytes and can be set from 1,024 to 1,048,576 bytes. Above 256 KiB, the topic must have no more than 100 subscriptions, all using SQS, Firehose or Lambda. The size example reads the current value before intentionally setting 512 KiB; it does not silently raise limits during publishing. The basic publish samples retain their own 256 KiB ceiling. See topic attributes.
TagResource adds or replaces selected tag values, ListTagsForResource reads the collection, and UntagResource removes selected keys. Other tags remain unchanged. Tags can affect access policies, so use deliberate keys and keep sensitive data out of their values.
SMS
A direct SMS publish uses PhoneNumber rather than TopicArn or TargetArn; it does not require a topic or subscription. The examples validate basic E.164 syntax and preserve the leading plus during form encoding. The Unicode example reads a checked UTF-8 file. Message encoding affects segmentation and cost, so its 1,600-character input bound is not a segment-count estimate. Both direct-send examples select the Transactional message type for their test content.
Check regional sandbox status and list verified or pending destinations before sending. Registering a sandbox number sends an OTP; the separate verification example reads the recipient's code from private sns_sms_otp.json, storing it as a string to preserve leading zeros. Removing a sandbox number does not unsubscribe it from topics or change its opt-out preferences. See SMS sandbox guidance.
The administration examples read SMS account settings, configure default message type and delivery logging, check opt-out status, and paginate opted-out and origination numbers. An opt-out check is not evidence of consent, and an origination inventory entry does not establish support for every destination country. Registration, spending capacity, region, and destination rules still affect sending. The settings example changes regional account defaults and needs a suitable logging role; it does not change MonthlySpendLimit. See SMS sending guidance and SMS attributes.
- Send an SMS Directly to an E.164 Phone Number
- Send Korean, Chinese, or Japanese SMS from a UTF-8 File
- Check Regional SMS Sandbox Status
- List All SMS Sandbox Destinations
- Register an SMS Sandbox Number and Send an OTP
- Verify an SMS Sandbox Number with Its Received OTP
- Remove an SMS Sandbox Destination
- Read SMS Account Settings
- Set SMS Delivery Logging and Default Message Type
- Check Whether a Phone Number Has Opted Out
- List All Opted-Out Phone Numbers
- List All SMS Origination Numbers
HTTPS Notifications
Subscribe an HTTPS endpoint you control, then verify its confirmation envelope before submitting the received token. The verifier handles Notification, SubscriptionConfirmation and UnsubscribeConfirmation. It pins the expected topic and regional certificate source, rejects unsafe certificate paths and redirects, checks certificate-chain signatures, trust and dates, and verifies the exact UTF-8 canonical string. Signature version 2 uses SHA-256; version 1 compatibility uses SHA-1. See SNS delivery signature verification.
The example reads a bounded batch of stored envelopes from sns_notifications.json, with a top-level messages array. Duplicate detection by TopicArn and MessageId lasts only within that batch. It does not host a web endpoint or perform business side effects. A production receiver needs request-size limits, a durable unique inbox key, transactional acceptance, and idempotent processing. Its illustrative timestamp window permits messages up to 24 hours old and five minutes of future clock skew; choose retention for the intended delivery and replay policy.
Provision approved certificate roots and required intermediates. The sample does not implement online certificate revocation or a general certificate-policy engine. Never follow SubscribeURL merely because it appears in an envelope, and confirm only subscriptions the application requested. The delivery-policy example configures HTTP/S retries and an average delivery rate; use an SNS DLQ separately for notifications that exhaust delivery attempts. See delivery retry policies.
Troubleshooting
| Symptom | What to check |
|---|---|
| Transport or TLS failure | Check endpoint, certificate trust, connectivity and timeouts. A completed write may have lost its response; reconcile before retrying. |
| Authorization or expired-token error | Check the credential lifetime, signing region, IAM permissions, topic policy, and any destination or KMS policy. Preserve the AWS request ID. |
| Throttling or service failure | Use bounded backoff with jitter where retry is appropriate. Preserve the same logical FIFO deduplication ID, and never retry an entire partially successful batch blindly. |
| Accepted message but no delivery | Check confirmation, filters and their propagation, queue/endpoint permissions, delivery logs, DLQs, and SMS readiness. MessageId alone is not a delivery receipt. |
| Invalid notification signature | Check the expected topic, allowed certificate URL, trusted chain, signature version, decoded JSON values, field order and exact LF separators. Do not process an unverified envelope. |
Keep full messages, tokens, request headers and detailed signing diagnostics private. The examples report HTTP status, error code and request identifiers without dumping message contents. The SNS API action reference covers additional capabilities beyond this collection, including mobile push and data protection policies.