Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.6.0+

Amazon SNS: Publish a Batch and Handle Partial Failures

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.

Sends two uniquely identified messages (the API allows at most ten). Checks both Successful and Failed collections even on HTTP 200, rejects unknown/duplicate/missing result IDs, and reports SenderFault. No attributes are included; their sizes would also count against the combined limit. Retry only appropriate failed entries with bounded backoff, never the successful entries. A transport timeout or malformed response has uncertain outcomes and can cause duplicates on a standard topic.

Required IAM actions: sns:PublishBatch. Related SQS/KMS permissions are separate.

AWS references: PublishBatch

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  Private credentials; do not put this file in public web content or source control.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/sns.json")
If success <> True Then
    Log("Could not load private SNS credentials.")
    Return
End If

stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = True) Then
    Log("Missing or invalid access_key.")
    Return
End If

stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = True) Then
    Log("Missing or invalid secret_key.")
    Return
End If

Dim region As String = "us-west-2"
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("sns.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As ChilkatAuthAws
aws.Initialize
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "sns"
aws.SignatureVersion = 4
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
success = rest.SetAuthAws(aws)
If success <> True Then
    Log("Could not configure AWS signing.")
    Return
End If

If credentials.HasMember("session_token") = True Then
    stringCompare.SetString(credentials.StringOf("session_token"))
    Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
    If (credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = True) Then
        Log("session_token must be a nonempty string when supplied.")
        Return
    End If

End If

Dim xml As ChilkatXml
xml.Initialize
xml.Strict = True
Dim value As String
Dim responseXml As String
Dim topicArn As String = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example"
Dim topic As ChilkatStringBuilder
topic.Initialize
topic.Append(topicArn)
Dim arnPrefix As ChilkatStringBuilder
arnPrefix.Initialize
arnPrefix.Append("arn:aws:sns:")
arnPrefix.Append(region)
arnPrefix.Append(":")
If topic.StartsWith(arnPrefix.GetAsString, True) <> True Then
    Log("Select an SNS topic ARN in the configured region and commercial AWS partition.")
    Return
End If

If topic.EndsWith(".fifo", True) = True Then
    Log("This example uses a standard topic. FIFO publishing needs group/deduplication handling.")
    Return
End If

Dim firstMessage As String = "Order 123 created."
Dim secondMessage As String = "Order 124 created."
Dim payloadBytes As ChilkatBinData
payloadBytes.Initialize
success = payloadBytes.AppendString(firstMessage, "utf-8")
If success <> True Then
    Log("Could not encode payload.")
    Return
End If

success = payloadBytes.AppendString(secondMessage, "utf-8")
If success <> True Then
    Log("Could not encode payload.")
    Return
End If

If (payloadBytes.NumBytes = 0) Or (payloadBytes.NumBytes > 262144) Then
    Log("This example requires a nonempty payload within 256 KiB; the topic may impose a lower limit.")
    Return
End If

'  Explicit certificate verification; keep this Socket alive while Rest uses it.
Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
    Log("TLS connection failed; inspect diagnostics privately.")
    Return
End If

success = rest.UseConnection(connection, True)
If success <> True Then
    Log("Could not attach TLS connection.")
    Return
End If

success = rest.ClearAllQueryParams
If success <> True Then
    Log("Could not clear parameters from the previous request.")
    Return
End If

'  Build a fresh form for each request; do not retain parameters from a previous action.
'  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
success = rest.AddQueryParam("Action", "PublishBatch")
If success <> True Then
    Log("Could not set Action.")
    Return
End If

success = rest.AddQueryParam("Version", "2010-03-31")
If success <> True Then
    Log("Could not set Version.")
    Return
End If

'  Include temporary credentials in the signed form body on every request.
If credentials.HasMember("session_token") = True Then
    success = rest.AddQueryParam("X-Amz-Security-Token", credentials.StringOf("session_token"))
    If success <> True Then
        Log("Could not set X-Amz-Security-Token.")
        Return
    End If

End If

success = rest.AddQueryParam("TopicArn", topicArn)
If success <> True Then
    Log("Could not set TopicArn.")
    Return
End If

success = rest.AddQueryParam("PublishBatchRequestEntries.member.1.Id", "entry-1")
If success <> True Then
    Log("Could not set PublishBatchRequestEntries.member.1.Id.")
    Return
End If

success = rest.AddQueryParam("PublishBatchRequestEntries.member.1.Message", firstMessage)
If success <> True Then
    Log("Could not set PublishBatchRequestEntries.member.1.Message.")
    Return
End If

success = rest.AddQueryParam("PublishBatchRequestEntries.member.2.Id", "entry-2")
If success <> True Then
    Log("Could not set PublishBatchRequestEntries.member.2.Id.")
    Return
End If

success = rest.AddQueryParam("PublishBatchRequestEntries.member.2.Message", secondMessage)
If success <> True Then
    Log("Could not set PublishBatchRequestEntries.member.2.Message.")
    Return
End If

responseXml = rest.FullRequestFormUrlEncoded("POST", "/")
If rest.LastMethodSuccess <> True Then
    Log("Request did not complete. Its outcome may be uncertain; reconcile before retrying.")
    Return
End If

success = xml.LoadXml(responseXml)
If rest.ResponseStatusCode <> 200 Then
    Log("SNS HTTP status: " & rest.ResponseStatusCode)
    If success = True Then
        value = xml.GetChildContent("Error|Code")
        If xml.LastMethodSuccess = True Then
            Log("AWS error code: " & value)
        End If

        value = xml.GetChildContent("RequestId")
        If xml.LastMethodSuccess = True Then
            Log("AWS request ID: " & value)
        End If

    End If

    '  Full messages, headers, and signing diagnostics may contain private data.
    Return
End If

If success <> True Then
    Log("Expected a well-formed XML response.")
    Return
End If

stringCompare.SetString(xml.Tag)
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("PublishBatchResponse", True)
If stringMatch4 <> True Then
    Log("Unexpected SNS response element.")
    Return
End If

value = xml.GetChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch5 = True) Then
    Log("Missing or empty ResponseMetadata|RequestId.")
    Return
End If

Log("AWS request ID: " & value)
Dim outcomes As ChilkatHashtable
outcomes.Initialize
Dim batchIndex As Int = 0
Dim failedCount As Int = 0
batchIndex = 0
Do While (batchIndex < xml.NumChildrenAt("PublishBatchResult|Successful"))
    xml.I = batchIndex
    value = xml.GetChildContent("PublishBatchResult|Successful|member[i]|Id")
    stringCompare.SetString(value)
    Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("", True)
    If (xml.LastMethodSuccess <> True) Or (stringMatch6 = True) Then
        Log("Missing or empty PublishBatchResult|Successful|member[i]|Id.")
        Return
    End If

    Dim entryId As String = value
    stringCompare.SetString(entryId)
    Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("entry-1", True)
    stringCompare.SetString(entryId)
    Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("entry-2", True)
    If (stringMatch7 <> True) And (stringMatch8 <> True) Then
        Log("Unknown batch result ID; outcome requires reconciliation.")
        Return
    End If

    If outcomes.Contains(entryId) = True Then
        Log("Duplicate batch result ID; outcome requires reconciliation.")
        Return
    End If

    success = outcomes.AddStr(entryId, "seen")
    If success <> True Then
        Log("Could not track batch result.")
        Return
    End If

    value = xml.GetChildContent("PublishBatchResult|Successful|member[i]|MessageId")
    stringCompare.SetString(value)
    Dim stringMatch9 As Boolean = stringCompare.ContentsEqual("", True)
    If (xml.LastMethodSuccess <> True) Or (stringMatch9 = True) Then
        Log("Missing or empty PublishBatchResult|Successful|member[i]|MessageId.")
        Return
    End If

    Log("Successful entry: " & entryId & " / " & value)
    batchIndex = batchIndex + 1
Loop
batchIndex = 0
Do While (batchIndex < xml.NumChildrenAt("PublishBatchResult|Failed"))
    xml.I = batchIndex
    value = xml.GetChildContent("PublishBatchResult|Failed|member[i]|Id")
    stringCompare.SetString(value)
    Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("", True)
    If (xml.LastMethodSuccess <> True) Or (stringMatch10 = True) Then
        Log("Missing or empty PublishBatchResult|Failed|member[i]|Id.")
        Return
    End If

    Dim entryId As String = value
    stringCompare.SetString(entryId)
    Dim stringMatch11 As Boolean = stringCompare.ContentsEqual("entry-1", True)
    stringCompare.SetString(entryId)
    Dim stringMatch12 As Boolean = stringCompare.ContentsEqual("entry-2", True)
    If (stringMatch11 <> True) And (stringMatch12 <> True) Then
        Log("Unknown batch result ID; outcome requires reconciliation.")
        Return
    End If

    If outcomes.Contains(entryId) = True Then
        Log("Duplicate batch result ID; outcome requires reconciliation.")
        Return
    End If

    success = outcomes.AddStr(entryId, "seen")
    If success <> True Then
        Log("Could not track batch result.")
        Return
    End If

    value = xml.GetChildContent("PublishBatchResult|Failed|member[i]|Code")
    stringCompare.SetString(value)
    Dim stringMatch13 As Boolean = stringCompare.ContentsEqual("", True)
    If (xml.LastMethodSuccess <> True) Or (stringMatch13 = True) Then
        Log("Missing or empty PublishBatchResult|Failed|member[i]|Code.")
        Return
    End If

    Log("Failed entry: " & entryId & " / " & value)
    value = xml.GetChildContent("PublishBatchResult|Failed|member[i]|SenderFault")
    stringCompare.SetString(value)
    Dim stringMatch14 As Boolean = stringCompare.ContentsEqual("", True)
    If (xml.LastMethodSuccess <> True) Or (stringMatch14 = True) Then
        Log("Missing or empty PublishBatchResult|Failed|member[i]|SenderFault.")
        Return
    End If

    stringCompare.SetString(value)
    Dim stringMatch15 As Boolean = stringCompare.ContentsEqual("true", True)
    stringCompare.SetString(value)
    Dim stringMatch16 As Boolean = stringCompare.ContentsEqual("false", True)
    If (stringMatch15 <> True) And (stringMatch16 <> True) Then
        Log("Invalid SenderFault value.")
        Return
    End If

    Log("Sender fault: " & value)
    failedCount = failedCount + 1
    batchIndex = batchIndex + 1
Loop
If (outcomes.Contains("entry-1") <> True) Or (outcomes.Contains("entry-2") <> True) Then
    Log("Missing batch outcomes; reconcile before retrying.")
    Return
End If

Log("Failed entries: " & failedCount)
Log("Example completed.")