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

Amazon SNS: Publish a UTF-8 Message to a Standard Topic

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.

Publishes one text message to a standard topic, with a fixed valid email Subject. Subject must have fewer than 100 characters and no line breaks or control characters. The sample validates a nonempty body and a 256 KiB UTF-8 byte ceiling; it does not set MessageStructure or message attributes. The topic may impose a lower configured limit.

The current topic MaximumMessageSize attribute supports up to 1 MiB, with restrictions on subscription count and supported protocols for values above 256 KiB. The default remains 256 KiB, and message attributes also count toward the limit. This sample's conservative ceiling is not a claim that every SNS topic is limited to 256 KiB. FIFO publishing needs MessageGroupId and appropriate deduplication handling; it is a separate example. A successful response confirms acceptance, not individual delivery or filtering results.

Required IAM action: sns:Publish. 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.

AWS Publish reference

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;
topicArn: PWideChar;
topic: HCkStringBuilder;
arnPrefix: HCkStringBuilder;
subject: PWideChar;
message: PWideChar;
messageBytes: HCkBinData;
connection: HCkSocket;
responseXml: PWideChar;
stringMatch4: Boolean;
stringMatch5: Boolean;
stringMatch6: 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;
subject := 'Test message from Amazon SNS';
message := 'This is a test message from Amazon SNS.';
//  Check bytes, not characters. This sample chooses a 256 KiB body ceiling.
messageBytes := CkBinData_Create();
success := CkBinData_AppendString(messageBytes,message,'utf-8');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not encode message as UTF-8.');
    Exit;
  end;
if ((CkBinData_getNumBytes(messageBytes) = 0) or (CkBinData_getNumBytes(messageBytes) > 262144)) then
  begin
    Memo1.Lines.Add('Use a nonempty message of at most 262144 UTF-8 bytes for this sample.');
    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 previous parameters.
//  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
success := CkRest_AddQueryParam(rest,'Action','Publish');
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,'Subject',subject);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Subject.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Message',message);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set 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,'PublishResponse',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);
value := CkXml__getChildContent(xml,'PublishResult|MessageId');
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 PublishResult|MessageId.');
    Exit;
  end;
Memo1.Lines.Add('Message ID: ' + value);
Memo1.Lines.Add('Topic message accepted by SNS; delivery is not confirmed.');

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(messageBytes);
CkSocket_Dispose(connection);