Amazon SNS: List All Topics with Pagination
See more Amazon SNS Examples
Uses the current Amazon SNS Query API (Version=2010-03-31) through Chilkat.Rest and AuthAws, with HTTPS, Signature Version 4, and service sns. The API version date remains current. Action and input parameters are URL-encoded into a POST body, avoiding message text and recipient addresses in the URL. Set the actual region once; other AWS partitions need their documented endpoint suffix and ARN partition.
Load private qa_data/aws/sns.json with nonempty string fields access_key, secret_key, and session_token when using temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles, obtain credentials, or refresh them automatically. The session token is included in the signed form body on every request. A Socket explicitly enables TLS certificate verification before passing the connection to Rest.
Checks setup calls, transport completion, HTTP status, XML parsing, result root, and required fields. Normal output includes identifiers, not full messages or headers. Keep detailed diagnostics private. For retryable failures, use bounded backoff with jitter in the application; these examples do not automatically retry writes. A Publish timeout can leave an accepted message and retrying a standard-topic/SMS publish can duplicate it. A returned MessageId confirms SNS acceptance, not subscriber or handset delivery.
Enumerates the requester's topics in one region, following NextToken through all pages, including empty pages with a continuation token. ListTopics returns at most 100 topics per page and has no MaxResults parameter. The example rebuilds the form parameters after each POST, detects repeated tokens, and reports incomplete enumeration at 10,000 pages. Absence or an empty NextToken ends the listing. Tokens are opaque and results are not an atomic snapshot.
Required IAM action: sns:ListTopics. Grant only the intended resource access; direct SMS does not have a topic ARN resource. Topic policies and KMS key access can also affect requests.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
let stringCompare = CkoStringBuilder()!
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Private credentials; do not put this file in public web content or source control.
let credentials = CkoJsonObject()!
credentials.strict = true
success = credentials.loadFile(path: "qa_data/aws/sns.json")
if success != true {
print("Could not load private SNS credentials.")
return
}
stringCompare.setString(value: credentials.string(of: "access_key"))
var stringMatch1: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
if (credentials.jsonType(of: "access_key").intValue != 1) || (stringMatch1 == true) {
print("Missing or invalid access_key.")
return
}
stringCompare.setString(value: credentials.string(of: "secret_key"))
var stringMatch2: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
if (credentials.jsonType(of: "secret_key").intValue != 1) || (stringMatch2 == true) {
print("Missing or invalid secret_key.")
return
}
var region: String? = "us-west-2"
let endpoint = CkoStringBuilder()!
endpoint.append(value: "sns.")
endpoint.append(value: region)
endpoint.append(value: ".amazonaws.com")
let aws = CkoAuthAws()!
aws.accessKey = credentials.string(of: "access_key")
aws.secretKey = credentials.string(of: "secret_key")
aws.region = region
aws.serviceName = "sns"
aws.signatureVersion = 4
let rest = CkoRest()!
rest.connectTimeoutMs = 20000
rest.idleTimeoutMs = 60000
rest.verboseLogging = false
success = rest.setAuthAws(authProvider: aws)
if success != true {
print("Could not configure AWS signing.")
return
}
if credentials.hasMember(jsonPath: "session_token") == true {
stringCompare.setString(value: credentials.string(of: "session_token"))
var stringMatch3: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
if (credentials.jsonType(of: "session_token").intValue != 1) || (stringMatch3 == true) {
print("session_token must be a nonempty string when supplied.")
return
}
}
let xml = CkoXml()!
xml.strict = true
var value: String?
// Explicit certificate verification; keep this Socket alive while Rest uses it.
let connection = CkoSocket()!
connection.requireSslCertVerify = true
connection.maxReadIdleMs = 60000
connection.maxSendIdleMs = 60000
success = connection.connect(hostname: endpoint.getAsString(), port: 443, ssl: true, maxWaitMs: 20000)
if success != true {
print("TLS connection failed; inspect diagnostics privately.")
return
}
success = rest.useConnection(connection: connection, autoReconnect: true)
if success != true {
print("Could not attach TLS connection.")
return
}
let seenTokens = CkoHashtable()!
var nextToken: String? = ""
var more: Bool = true
var page: Int = 0
while (more == true) {
if page == 10000 {
print("Page bound reached; topic enumeration is incomplete.")
return
}
page = page + 1
success = rest.clearAllQueryParams()
if success != true {
print("Could not clear parameters from the previous request.")
return
}
// Build a fresh form for each request; do not retain previous parameters.
// AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
success = rest.addQueryParam(name: "Action", value: "ListTopics")
if success != true {
print("Could not set Action.")
return
}
success = rest.addQueryParam(name: "Version", value: "2010-03-31")
if success != true {
print("Could not set Version.")
return
}
// Include temporary credentials in the signed form body on every request.
if credentials.hasMember(jsonPath: "session_token") == true {
success = rest.addQueryParam(name: "X-Amz-Security-Token", value: credentials.string(of: "session_token"))
if success != true {
print("Could not set X-Amz-Security-Token.")
return
}
}
stringCompare.setString(value: nextToken)
var stringMatch4: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
if stringMatch4 != true {
success = rest.addQueryParam(name: "NextToken", value: nextToken)
if success != true {
print("Could not set NextToken.")
return
}
}
var responseXml: String? = rest.fullRequestFormUrlEncoded(httpVerb: "POST", uriPath: "/")
if rest.lastMethodSuccess != true {
print("Request did not complete. Inspect diagnostics privately.")
return
}
success = xml.load(xmlData: responseXml)
if rest.responseStatusCode.intValue != 200 {
print("SNS HTTP status: \(rest.responseStatusCode.intValue)")
if success == true {
value = xml.getChildContent(tagPath: "Error|Code")
if xml.lastMethodSuccess == true {
print("AWS error code: \(value!)")
}
value = xml.getChildContent(tagPath: "RequestId")
if xml.lastMethodSuccess == true {
print("AWS request ID: \(value!)")
}
}
// Full messages, headers, and signing diagnostics may contain private data.
return
}
if success != true {
print("Expected a well-formed XML response.")
return
}
stringCompare.setString(value: xml.tag)
var stringMatch5: Bool = stringCompare.contentsEqual(str: "ListTopicsResponse", caseSensitive: true)
if stringMatch5 != true {
print("Unexpected SNS response element.")
return
}
value = xml.getChildContent(tagPath: "ResponseMetadata|RequestId")
stringCompare.setString(value: value)
var stringMatch6: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
if (xml.lastMethodSuccess != true) || (stringMatch6 == true) {
print("Missing or empty ResponseMetadata|RequestId.")
return
}
print("AWS request ID: \(value!)")
if xml.hasChild(withTag: "ListTopicsResult") != true {
print("Missing ListTopicsResult.")
return
}
var i: Int = 0
while (i < xml.numChildren(at: "ListTopicsResult|Topics").intValue) {
xml.i = i
value = xml.getChildContent(tagPath: "ListTopicsResult|Topics|member[i]|TopicArn")
stringCompare.setString(value: value)
var stringMatch7: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
if (xml.lastMethodSuccess != true) || (stringMatch7 == true) {
print("Missing or empty ListTopicsResult|Topics|member[i]|TopicArn.")
return
}
print("Topic ARN: \(value!)")
i = i + 1
}
nextToken = xml.getChildContent(tagPath: "ListTopicsResult|NextToken")
if xml.lastMethodSuccess != true {
nextToken = ""
}
more = false
stringCompare.setString(value: nextToken)
var stringMatch8: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
if stringMatch8 != true {
if seenTokens.contains(key: nextToken) == true {
print("Repeated pagination token; topic enumeration is incomplete.")
return
}
success = seenTokens.addStr(key: nextToken, value: "seen")
if success != true {
print("Could not track pagination.")
return
}
more = true
}
}
print("Topic enumeration complete.")
}