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

Amazon SNS: Filter a Subscription by Message Attributes

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.

Configures event=order-created and amount >=100 using MessageAttributes. Attribute filtering needs a String event attribute and Number amount attribute; body filtering needs corresponding JSON properties. Scope and policy are separate writes, not an atomic change. Use a new/quiesced subscription during migration. Changes can take up to 15 minutes to propagate. Final readback reports stored configuration, not proof that propagation is complete.

Required IAM actions: sns:SetSubscriptionAttributes, sns:GetSubscriptionAttributes. Related SQS/KMS permissions are separate.

AWS references: SetSubscriptionAttributes GetSubscriptionAttributes

Chilkat Node.js Downloads

Node.js
NODEJS_PRELUDE

function chilkatExample() {

    var success = false;

    var stringCompare = new chilkat.StringBuilder();
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Private credentials; do not put this file in public web content or source control.
    var credentials = new chilkat.JsonObject();
    credentials.Strict = true;
    success = credentials.LoadFile("qa_data/aws/sns.json");
    if (success !== true) {
        console.log("Could not load private SNS credentials.");
        return;
    }

    stringCompare.SetString(credentials.StringOf("access_key"));
    var stringMatch1 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("access_key") !== 1) || (stringMatch1 == true)) {
        console.log("Missing or invalid access_key.");
        return;
    }

    stringCompare.SetString(credentials.StringOf("secret_key"));
    var stringMatch2 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("secret_key") !== 1) || (stringMatch2 == true)) {
        console.log("Missing or invalid secret_key.");
        return;
    }

    var region = "us-west-2";
    var endpoint = new chilkat.StringBuilder();
    endpoint.Append("sns.");
    endpoint.Append(region);
    endpoint.Append(".amazonaws.com");
    var aws = new chilkat.AuthAws();
    aws.AccessKey = credentials.StringOf("access_key");
    aws.SecretKey = credentials.StringOf("secret_key");
    aws.Region = region;
    aws.ServiceName = "sns";
    aws.SignatureVersion = 4;
    var rest = new chilkat.Rest();
    rest.ConnectTimeoutMs = 20000;
    rest.IdleTimeoutMs = 60000;
    rest.VerboseLogging = false;
    success = rest.SetAuthAws(aws);
    if (success !== true) {
        console.log("Could not configure AWS signing.");
        return;
    }

    if (credentials.HasMember("session_token") == true) {
        stringCompare.SetString(credentials.StringOf("session_token"));
        var stringMatch3 = stringCompare.ContentsEqual("",true);
        if ((credentials.JsonTypeOf("session_token") !== 1) || (stringMatch3 == true)) {
            console.log("session_token must be a nonempty string when supplied.");
            return;
        }

    }

    var xml = new chilkat.Xml();
    xml.Strict = true;
    var value;
    var responseXml;
    var topicArn = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
    var topic = new chilkat.StringBuilder();
    topic.Append(topicArn);
    var arnPrefix = new chilkat.StringBuilder();
    arnPrefix.Append("arn:aws:sns:");
    arnPrefix.Append(region);
    arnPrefix.Append(":");
    if (topic.StartsWith(arnPrefix.GetAsString(),true) !== true) {
        console.log("Select an SNS topic ARN in the configured region and commercial AWS partition.");
        return;
    }

    //  Replace with the confirmed subscription ARN, never "pending confirmation".
    var subscriptionArn = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example:11111111-2222-3333-4444-555555555555";
    var subscription = new chilkat.StringBuilder();
    subscription.Append(subscriptionArn);
    var subscriptionPrefix = new chilkat.StringBuilder();
    subscriptionPrefix.Append(topicArn);
    subscriptionPrefix.Append(":");
    if ((subscription.StartsWith(subscriptionPrefix.GetAsString(),true) !== true) || (subscription.Length <= subscriptionPrefix.Length)) {
        console.log("Use a confirmed subscription ARN for the selected topic.");
        return;
    }

    var filter = new chilkat.JsonObject();
    filter.Strict = true;
    success = filter.Load("{\"event\":[\"order-created\"],\"amount\":[{\"numeric\":[\">=\",100]}]}");
    if (success !== true) {
        console.log("Could not construct JSON.");
        return;
    }

    //  Explicit certificate verification; keep this Socket alive while Rest uses it.
    var connection = new chilkat.Socket();
    connection.RequireSslCertVerify = true;
    connection.MaxReadIdleMs = 60000;
    connection.MaxSendIdleMs = 60000;
    success = connection.Connect(endpoint.GetAsString(),443,true,20000);
    if (success !== true) {
        console.log("TLS connection failed; inspect diagnostics privately.");
        return;
    }

    success = rest.UseConnection(connection,true);
    if (success !== true) {
        console.log("Could not attach TLS connection.");
        return;
    }

    success = rest.ClearAllQueryParams();
    if (success !== true) {
        console.log("Could not clear parameters from the previous request.");
        return;
    }

    //  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","SetSubscriptionAttributes");
    if (success !== true) {
        console.log("Could not set Action.");
        return;
    }

    success = rest.AddQueryParam("Version","2010-03-31");
    if (success !== true) {
        console.log("Could not set Version.");
        return;
    }

    //  Include temporary credentials in the signed form body on every request.
    if (credentials.HasMember("session_token") == true) {
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"));
        if (success !== true) {
            console.log("Could not set X-Amz-Security-Token.");
            return;
        }

    }

    success = rest.AddQueryParam("SubscriptionArn",subscriptionArn);
    if (success !== true) {
        console.log("Could not set SubscriptionArn.");
        return;
    }

    success = rest.AddQueryParam("AttributeName","FilterPolicyScope");
    if (success !== true) {
        console.log("Could not set AttributeName.");
        return;
    }

    success = rest.AddQueryParam("AttributeValue","MessageAttributes");
    if (success !== true) {
        console.log("Could not set AttributeValue.");
        return;
    }

    responseXml = rest.FullRequestFormUrlEncoded("POST","/");
    if (rest.LastMethodSuccess !== true) {
        console.log("Request did not complete. Its outcome may be uncertain; reconcile before retrying.");
        return;
    }

    success = xml.LoadXml(responseXml);
    if (rest.ResponseStatusCode !== 200) {
        console.log("SNS HTTP status: " + rest.ResponseStatusCode);
        if (success == true) {
            value = xml.GetChildContent("Error|Code");
            if (xml.LastMethodSuccess == true) {
                console.log("AWS error code: " + value);
            }

            value = xml.GetChildContent("RequestId");
            if (xml.LastMethodSuccess == true) {
                console.log("AWS request ID: " + value);
            }

        }

        //  Full messages, headers, and signing diagnostics may contain private data.
        return;
    }

    if (success !== true) {
        console.log("Expected a well-formed XML response.");
        return;
    }

    stringCompare.SetString(xml.Tag);
    var stringMatch4 = stringCompare.ContentsEqual("SetSubscriptionAttributesResponse",true);
    if (stringMatch4 !== true) {
        console.log("Unexpected SNS response element.");
        return;
    }

    value = xml.GetChildContent("ResponseMetadata|RequestId");
    stringCompare.SetString(value);
    var stringMatch5 = stringCompare.ContentsEqual("",true);
    if ((xml.LastMethodSuccess !== true) || (stringMatch5 == true)) {
        console.log("Missing or empty ResponseMetadata|RequestId.");
        return;
    }

    console.log("AWS request ID: " + value);
    success = rest.ClearAllQueryParams();
    if (success !== true) {
        console.log("Could not clear parameters from the previous request.");
        return;
    }

    //  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","SetSubscriptionAttributes");
    if (success !== true) {
        console.log("Could not set Action.");
        return;
    }

    success = rest.AddQueryParam("Version","2010-03-31");
    if (success !== true) {
        console.log("Could not set Version.");
        return;
    }

    //  Include temporary credentials in the signed form body on every request.
    if (credentials.HasMember("session_token") == true) {
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"));
        if (success !== true) {
            console.log("Could not set X-Amz-Security-Token.");
            return;
        }

    }

    success = rest.AddQueryParam("SubscriptionArn",subscriptionArn);
    if (success !== true) {
        console.log("Could not set SubscriptionArn.");
        return;
    }

    success = rest.AddQueryParam("AttributeName","FilterPolicy");
    if (success !== true) {
        console.log("Could not set AttributeName.");
        return;
    }

    success = rest.AddQueryParam("AttributeValue",filter.Emit());
    if (success !== true) {
        console.log("Could not set AttributeValue.");
        return;
    }

    responseXml = rest.FullRequestFormUrlEncoded("POST","/");
    if (rest.LastMethodSuccess !== true) {
        console.log("Request did not complete. Its outcome may be uncertain; reconcile before retrying.");
        return;
    }

    success = xml.LoadXml(responseXml);
    if (rest.ResponseStatusCode !== 200) {
        console.log("SNS HTTP status: " + rest.ResponseStatusCode);
        if (success == true) {
            value = xml.GetChildContent("Error|Code");
            if (xml.LastMethodSuccess == true) {
                console.log("AWS error code: " + value);
            }

            value = xml.GetChildContent("RequestId");
            if (xml.LastMethodSuccess == true) {
                console.log("AWS request ID: " + value);
            }

        }

        //  Full messages, headers, and signing diagnostics may contain private data.
        return;
    }

    if (success !== true) {
        console.log("Expected a well-formed XML response.");
        return;
    }

    stringCompare.SetString(xml.Tag);
    var stringMatch6 = stringCompare.ContentsEqual("SetSubscriptionAttributesResponse",true);
    if (stringMatch6 !== true) {
        console.log("Unexpected SNS response element.");
        return;
    }

    value = xml.GetChildContent("ResponseMetadata|RequestId");
    stringCompare.SetString(value);
    var stringMatch7 = stringCompare.ContentsEqual("",true);
    if ((xml.LastMethodSuccess !== true) || (stringMatch7 == true)) {
        console.log("Missing or empty ResponseMetadata|RequestId.");
        return;
    }

    console.log("AWS request ID: " + value);
    success = rest.ClearAllQueryParams();
    if (success !== true) {
        console.log("Could not clear parameters from the previous request.");
        return;
    }

    //  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","GetSubscriptionAttributes");
    if (success !== true) {
        console.log("Could not set Action.");
        return;
    }

    success = rest.AddQueryParam("Version","2010-03-31");
    if (success !== true) {
        console.log("Could not set Version.");
        return;
    }

    //  Include temporary credentials in the signed form body on every request.
    if (credentials.HasMember("session_token") == true) {
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"));
        if (success !== true) {
            console.log("Could not set X-Amz-Security-Token.");
            return;
        }

    }

    success = rest.AddQueryParam("SubscriptionArn",subscriptionArn);
    if (success !== true) {
        console.log("Could not set SubscriptionArn.");
        return;
    }

    responseXml = rest.FullRequestFormUrlEncoded("POST","/");
    if (rest.LastMethodSuccess !== true) {
        console.log("Request did not complete. Inspect diagnostics privately.");
        return;
    }

    success = xml.LoadXml(responseXml);
    if (rest.ResponseStatusCode !== 200) {
        console.log("SNS HTTP status: " + rest.ResponseStatusCode);
        if (success == true) {
            value = xml.GetChildContent("Error|Code");
            if (xml.LastMethodSuccess == true) {
                console.log("AWS error code: " + value);
            }

            value = xml.GetChildContent("RequestId");
            if (xml.LastMethodSuccess == true) {
                console.log("AWS request ID: " + value);
            }

        }

        //  Full messages, headers, and signing diagnostics may contain private data.
        return;
    }

    if (success !== true) {
        console.log("Expected a well-formed XML response.");
        return;
    }

    stringCompare.SetString(xml.Tag);
    var stringMatch8 = stringCompare.ContentsEqual("GetSubscriptionAttributesResponse",true);
    if (stringMatch8 !== true) {
        console.log("Unexpected SNS response element.");
        return;
    }

    value = xml.GetChildContent("ResponseMetadata|RequestId");
    stringCompare.SetString(value);
    var stringMatch9 = stringCompare.ContentsEqual("",true);
    if ((xml.LastMethodSuccess !== true) || (stringMatch9 == true)) {
        console.log("Missing or empty ResponseMetadata|RequestId.");
        return;
    }

    console.log("AWS request ID: " + value);
    if (xml.HasChildWithTag("GetSubscriptionAttributesResult") !== true) {
        console.log("Missing result.");
        return;
    }

    var attributes = new chilkat.JsonObject();
    var mapIndex = 0;
    while ((mapIndex < xml.NumChildrenAt("GetSubscriptionAttributesResult|Attributes"))) {
        xml.I = mapIndex;
        value = xml.GetChildContent("GetSubscriptionAttributesResult|Attributes|entry[i]|key");
        stringCompare.SetString(value);
        var stringMatch10 = stringCompare.ContentsEqual("",true);
        if ((xml.LastMethodSuccess !== true) || (stringMatch10 == true)) {
            console.log("Missing or empty GetSubscriptionAttributesResult|Attributes|entry[i]|key.");
            return;
        }

        var mapKey = value;
        value = xml.GetChildContent("GetSubscriptionAttributesResult|Attributes|entry[i]|value");
        if (xml.LastMethodSuccess !== true) {
            console.log("Missing map value.");
            return;
        }

        success = attributes.AppendString(mapKey,value);
        if (success !== true) {
            console.log("Invalid or duplicate map entry.");
            return;
        }

        mapIndex = mapIndex+1;
    }

    console.log("FilterPolicyScope: " + attributes.StringOf("FilterPolicyScope"));
    console.log("FilterPolicy: " + attributes.StringOf("FilterPolicy"));
    console.log("Example completed.");

}

chilkatExample();