Sample code for 30+ languages & platforms
Delphi DLL 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 Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
stringCompare: HCkStringBuilder;
credentials: HCkJsonObject;
stringMatch1: Boolean;
stringMatch2: Boolean;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
stringMatch3: Boolean;
xml: HCkXml;
value: PWideChar;
responseXml: PWideChar;
topicArn: PWideChar;
topic: HCkStringBuilder;
arnPrefix: HCkStringBuilder;
firstMessage: PWideChar;
secondMessage: PWideChar;
payloadBytes: HCkBinData;
connection: HCkSocket;
stringMatch4: Boolean;
stringMatch5: Boolean;
outcomes: HCkHashtable;
batchIndex: Integer;
failedCount: Integer;
stringMatch6: Boolean;
entryId: PWideChar;
stringMatch7: Boolean;
stringMatch8: Boolean;
stringMatch9: Boolean;
stringMatch10: Boolean;
entryId: PWideChar;
stringMatch11: Boolean;
stringMatch12: Boolean;
stringMatch13: Boolean;
stringMatch14: Boolean;
stringMatch15: Boolean;
stringMatch16: Boolean;

begin
success := False;

stringCompare := CkStringBuilder_Create();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Private credentials; do not put this file in public web content or source control.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/sns.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private SNS credentials.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'access_key'));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (stringMatch1 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'secret_key'));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (stringMatch2 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'sns.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'sns');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
CkRest_putVerboseLogging(rest,False);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not configure AWS signing.');
    Exit;
  end;
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'session_token'));
    stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) or (stringMatch3 = True)) then
      begin
        Memo1.Lines.Add('session_token must be a nonempty string when supplied.');
        Exit;
      end;
  end;
xml := CkXml_Create();
CkXml_putStrict(xml,True);

topicArn := 'arn:aws:sns:us-west-2:123456789012:chilkat-standard-example';
topic := CkStringBuilder_Create();
CkStringBuilder_Append(topic,topicArn);
arnPrefix := CkStringBuilder_Create();
CkStringBuilder_Append(arnPrefix,'arn:aws:sns:');
CkStringBuilder_Append(arnPrefix,region);
CkStringBuilder_Append(arnPrefix,':');
if (CkStringBuilder_StartsWith(topic,CkStringBuilder__getAsString(arnPrefix),True) <> True) then
  begin
    Memo1.Lines.Add('Select an SNS topic ARN in the configured region and commercial AWS partition.');
    Exit;
  end;
if (CkStringBuilder_EndsWith(topic,'.fifo',True) = True) then
  begin
    Memo1.Lines.Add('This example uses a standard topic. FIFO publishing needs group/deduplication handling.');
    Exit;
  end;
firstMessage := 'Order 123 created.';
secondMessage := 'Order 124 created.';
payloadBytes := CkBinData_Create();
success := CkBinData_AppendString(payloadBytes,firstMessage,'utf-8');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not encode payload.');
    Exit;
  end;
success := CkBinData_AppendString(payloadBytes,secondMessage,'utf-8');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not encode payload.');
    Exit;
  end;
if ((CkBinData_getNumBytes(payloadBytes) = 0) or (CkBinData_getNumBytes(payloadBytes) > 262144)) then
  begin
    Memo1.Lines.Add('This example requires a nonempty payload within 256 KiB; the topic may impose a lower limit.');
    Exit;
  end;
//  Explicit certificate verification; keep this Socket alive while Rest uses it.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach TLS connection.');
    Exit;
  end;
success := CkRest_ClearAllQueryParams(rest);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not clear parameters from the previous request.');
    Exit;
  end;
//  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 := CkRest_AddQueryParam(rest,'Action','PublishBatch');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Action.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Version','2010-03-31');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Version.');
    Exit;
  end;
//  Include temporary credentials in the signed form body on every request.
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set X-Amz-Security-Token.');
        Exit;
      end;
  end;
success := CkRest_AddQueryParam(rest,'TopicArn',topicArn);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set TopicArn.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'PublishBatchRequestEntries.member.1.Id','entry-1');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set PublishBatchRequestEntries.member.1.Id.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'PublishBatchRequestEntries.member.1.Message',firstMessage);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set PublishBatchRequestEntries.member.1.Message.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'PublishBatchRequestEntries.member.2.Id','entry-2');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set PublishBatchRequestEntries.member.2.Id.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'PublishBatchRequestEntries.member.2.Message',secondMessage);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set PublishBatchRequestEntries.member.2.Message.');
    Exit;
  end;
responseXml := CkRest__fullRequestFormUrlEncoded(rest,'POST','/');
if (CkRest_getLastMethodSuccess(rest) <> True) then
  begin
    Memo1.Lines.Add('Request did not complete. Its outcome may be uncertain; reconcile before retrying.');
    Exit;
  end;
success := CkXml_LoadXml(xml,responseXml);
if (CkRest_getResponseStatusCode(rest) <> 200) then
  begin
    Memo1.Lines.Add('SNS HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
    if (success = True) then
      begin
        value := CkXml__getChildContent(xml,'Error|Code');
        if (CkXml_getLastMethodSuccess(xml) = True) then
          begin
            Memo1.Lines.Add('AWS error code: ' + value);
          end;
        value := CkXml__getChildContent(xml,'RequestId');
        if (CkXml_getLastMethodSuccess(xml) = True) then
          begin
            Memo1.Lines.Add('AWS request ID: ' + value);
          end;
      end;
    //  Full messages, headers, and signing diagnostics may contain private data.
    Exit;
  end;
if (success <> True) then
  begin
    Memo1.Lines.Add('Expected a well-formed XML response.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(xml));
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'PublishBatchResponse',True);
if (stringMatch4 <> True) then
  begin
    Memo1.Lines.Add('Unexpected SNS response element.');
    Exit;
  end;
value := CkXml__getChildContent(xml,'ResponseMetadata|RequestId');
CkStringBuilder_SetString(stringCompare,value);
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch5 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
    Exit;
  end;
Memo1.Lines.Add('AWS request ID: ' + value);
outcomes := CkHashtable_Create();
batchIndex := 0;
failedCount := 0;
batchIndex := 0;
while (batchIndex < CkXml_NumChildrenAt(xml,'PublishBatchResult|Successful')) do
  begin
    CkXml_putI(xml,batchIndex);
    value := CkXml__getChildContent(xml,'PublishBatchResult|Successful|member[i]|Id');
    CkStringBuilder_SetString(stringCompare,value);
    stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch6 = True)) then
      begin
        Memo1.Lines.Add('Missing or empty PublishBatchResult|Successful|member[i]|Id.');
        Exit;
      end;
    entryId := value;
    CkStringBuilder_SetString(stringCompare,entryId);
    stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'entry-1',True);
    CkStringBuilder_SetString(stringCompare,entryId);
    stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'entry-2',True);
    if ((stringMatch7 <> True) and (stringMatch8 <> True)) then
      begin
        Memo1.Lines.Add('Unknown batch result ID; outcome requires reconciliation.');
        Exit;
      end;
    if (CkHashtable_Contains(outcomes,entryId) = True) then
      begin
        Memo1.Lines.Add('Duplicate batch result ID; outcome requires reconciliation.');
        Exit;
      end;
    success := CkHashtable_AddStr(outcomes,entryId,'seen');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not track batch result.');
        Exit;
      end;
    value := CkXml__getChildContent(xml,'PublishBatchResult|Successful|member[i]|MessageId');
    CkStringBuilder_SetString(stringCompare,value);
    stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch9 = True)) then
      begin
        Memo1.Lines.Add('Missing or empty PublishBatchResult|Successful|member[i]|MessageId.');
        Exit;
      end;
    Memo1.Lines.Add('Successful entry: ' + entryId + ' / ' + value);
    batchIndex := batchIndex + 1;
  end;

batchIndex := 0;
while (batchIndex < CkXml_NumChildrenAt(xml,'PublishBatchResult|Failed')) do
  begin
    CkXml_putI(xml,batchIndex);
    value := CkXml__getChildContent(xml,'PublishBatchResult|Failed|member[i]|Id');
    CkStringBuilder_SetString(stringCompare,value);
    stringMatch10 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch10 = True)) then
      begin
        Memo1.Lines.Add('Missing or empty PublishBatchResult|Failed|member[i]|Id.');
        Exit;
      end;
    entryId := value;
    CkStringBuilder_SetString(stringCompare,entryId);
    stringMatch11 := CkStringBuilder_ContentsEqual(stringCompare,'entry-1',True);
    CkStringBuilder_SetString(stringCompare,entryId);
    stringMatch12 := CkStringBuilder_ContentsEqual(stringCompare,'entry-2',True);
    if ((stringMatch11 <> True) and (stringMatch12 <> True)) then
      begin
        Memo1.Lines.Add('Unknown batch result ID; outcome requires reconciliation.');
        Exit;
      end;
    if (CkHashtable_Contains(outcomes,entryId) = True) then
      begin
        Memo1.Lines.Add('Duplicate batch result ID; outcome requires reconciliation.');
        Exit;
      end;
    success := CkHashtable_AddStr(outcomes,entryId,'seen');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not track batch result.');
        Exit;
      end;
    value := CkXml__getChildContent(xml,'PublishBatchResult|Failed|member[i]|Code');
    CkStringBuilder_SetString(stringCompare,value);
    stringMatch13 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch13 = True)) then
      begin
        Memo1.Lines.Add('Missing or empty PublishBatchResult|Failed|member[i]|Code.');
        Exit;
      end;
    Memo1.Lines.Add('Failed entry: ' + entryId + ' / ' + value);
    value := CkXml__getChildContent(xml,'PublishBatchResult|Failed|member[i]|SenderFault');
    CkStringBuilder_SetString(stringCompare,value);
    stringMatch14 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch14 = True)) then
      begin
        Memo1.Lines.Add('Missing or empty PublishBatchResult|Failed|member[i]|SenderFault.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,value);
    stringMatch15 := CkStringBuilder_ContentsEqual(stringCompare,'true',True);
    CkStringBuilder_SetString(stringCompare,value);
    stringMatch16 := CkStringBuilder_ContentsEqual(stringCompare,'false',True);
    if ((stringMatch15 <> True) and (stringMatch16 <> True)) then
      begin
        Memo1.Lines.Add('Invalid SenderFault value.');
        Exit;
      end;
    Memo1.Lines.Add('Sender fault: ' + value);
    failedCount := failedCount + 1;
    batchIndex := batchIndex + 1;
  end;

if ((CkHashtable_Contains(outcomes,'entry-1') <> True) or (CkHashtable_Contains(outcomes,'entry-2') <> True)) then
  begin
    Memo1.Lines.Add('Missing batch outcomes; reconcile before retrying.');
    Exit;
  end;
Memo1.Lines.Add('Failed entries: ' + IntToStr(failedCount));
Memo1.Lines.Add('Example completed.');

CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(topic);
CkStringBuilder_Dispose(arnPrefix);
CkBinData_Dispose(payloadBytes);
CkSocket_Dispose(connection);
CkHashtable_Dispose(outcomes);