Amazon SNS: Filter a Subscription by JSON Message Body
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 MessageBody. 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 VB.NET Downloads
Dim success As Boolean = False
Dim stringCompare As 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.
Dim credentials As New Chilkat.JsonObject
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/sns.json")
If (success <> True) Then
Debug.WriteLine("Could not load private SNS credentials.")
Exit Sub
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
Debug.WriteLine("Missing or invalid access_key.")
Exit Sub
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
Debug.WriteLine("Missing or invalid secret_key.")
Exit Sub
End If
Dim region As String = "us-west-2"
Dim endpoint As New Chilkat.StringBuilder
endpoint.Append("sns.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As New Chilkat.AuthAws
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "sns"
aws.SignatureVersion = 4
Dim rest As New Chilkat.Rest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
success = rest.SetAuthAws(aws)
If (success <> True) Then
Debug.WriteLine("Could not configure AWS signing.")
Exit Sub
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
Debug.WriteLine("session_token must be a nonempty string when supplied.")
Exit Sub
End If
End If
Dim xml As New Chilkat.Xml
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 New Chilkat.StringBuilder
topic.Append(topicArn)
Dim arnPrefix As New Chilkat.StringBuilder
arnPrefix.Append("arn:aws:sns:")
arnPrefix.Append(region)
arnPrefix.Append(":")
If (topic.StartsWith(arnPrefix.GetAsString(),True) <> True) Then
Debug.WriteLine("Select an SNS topic ARN in the configured region and commercial AWS partition.")
Exit Sub
End If
' Replace with the confirmed subscription ARN, never "pending confirmation".
Dim subscriptionArn As String = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example:11111111-2222-3333-4444-555555555555"
Dim subscription As New Chilkat.StringBuilder
subscription.Append(subscriptionArn)
Dim subscriptionPrefix As New Chilkat.StringBuilder
subscriptionPrefix.Append(topicArn)
subscriptionPrefix.Append(":")
If ((subscription.StartsWith(subscriptionPrefix.GetAsString(),True) <> True) Or (subscription.Length <= subscriptionPrefix.Length)) Then
Debug.WriteLine("Use a confirmed subscription ARN for the selected topic.")
Exit Sub
End If
Dim filter As New Chilkat.JsonObject
filter.Strict = True
success = filter.Load("{""event"":[""order-created""],""amount"":[{""numeric"":["">="",100]}]}")
If (success <> True) Then
Debug.WriteLine("Could not construct JSON.")
Exit Sub
End If
' Explicit certificate verification; keep this Socket alive while Rest uses it.
Dim connection As New Chilkat.Socket
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
If (success <> True) Then
Debug.WriteLine("TLS connection failed; inspect diagnostics privately.")
Exit Sub
End If
success = rest.UseConnection(connection,True)
If (success <> True) Then
Debug.WriteLine("Could not attach TLS connection.")
Exit Sub
End If
success = rest.ClearAllQueryParams()
If (success <> True) Then
Debug.WriteLine("Could not clear parameters from the previous request.")
Exit Sub
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","SetSubscriptionAttributes")
If (success <> True) Then
Debug.WriteLine("Could not set Action.")
Exit Sub
End If
success = rest.AddQueryParam("Version","2010-03-31")
If (success <> True) Then
Debug.WriteLine("Could not set Version.")
Exit Sub
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
Debug.WriteLine("Could not set X-Amz-Security-Token.")
Exit Sub
End If
End If
success = rest.AddQueryParam("SubscriptionArn",subscriptionArn)
If (success <> True) Then
Debug.WriteLine("Could not set SubscriptionArn.")
Exit Sub
End If
success = rest.AddQueryParam("AttributeName","FilterPolicyScope")
If (success <> True) Then
Debug.WriteLine("Could not set AttributeName.")
Exit Sub
End If
success = rest.AddQueryParam("AttributeValue","MessageBody")
If (success <> True) Then
Debug.WriteLine("Could not set AttributeValue.")
Exit Sub
End If
responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> True) Then
Debug.WriteLine("Request did not complete. Its outcome may be uncertain; reconcile before retrying.")
Exit Sub
End If
success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
Debug.WriteLine("SNS HTTP status: " & rest.ResponseStatusCode)
If (success = True) Then
value = xml.GetChildContent("Error|Code")
If (xml.LastMethodSuccess = True) Then
Debug.WriteLine("AWS error code: " & value)
End If
value = xml.GetChildContent("RequestId")
If (xml.LastMethodSuccess = True) Then
Debug.WriteLine("AWS request ID: " & value)
End If
End If
' Full messages, headers, and signing diagnostics may contain private data.
Exit Sub
End If
If (success <> True) Then
Debug.WriteLine("Expected a well-formed XML response.")
Exit Sub
End If
stringCompare.SetString(xml.Tag)
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("SetSubscriptionAttributesResponse",True)
If (stringMatch4 <> True) Then
Debug.WriteLine("Unexpected SNS response element.")
Exit Sub
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
Debug.WriteLine("Missing or empty ResponseMetadata|RequestId.")
Exit Sub
End If
Debug.WriteLine("AWS request ID: " & value)
success = rest.ClearAllQueryParams()
If (success <> True) Then
Debug.WriteLine("Could not clear parameters from the previous request.")
Exit Sub
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","SetSubscriptionAttributes")
If (success <> True) Then
Debug.WriteLine("Could not set Action.")
Exit Sub
End If
success = rest.AddQueryParam("Version","2010-03-31")
If (success <> True) Then
Debug.WriteLine("Could not set Version.")
Exit Sub
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
Debug.WriteLine("Could not set X-Amz-Security-Token.")
Exit Sub
End If
End If
success = rest.AddQueryParam("SubscriptionArn",subscriptionArn)
If (success <> True) Then
Debug.WriteLine("Could not set SubscriptionArn.")
Exit Sub
End If
success = rest.AddQueryParam("AttributeName","FilterPolicy")
If (success <> True) Then
Debug.WriteLine("Could not set AttributeName.")
Exit Sub
End If
success = rest.AddQueryParam("AttributeValue",filter.Emit())
If (success <> True) Then
Debug.WriteLine("Could not set AttributeValue.")
Exit Sub
End If
responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> True) Then
Debug.WriteLine("Request did not complete. Its outcome may be uncertain; reconcile before retrying.")
Exit Sub
End If
success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
Debug.WriteLine("SNS HTTP status: " & rest.ResponseStatusCode)
If (success = True) Then
value = xml.GetChildContent("Error|Code")
If (xml.LastMethodSuccess = True) Then
Debug.WriteLine("AWS error code: " & value)
End If
value = xml.GetChildContent("RequestId")
If (xml.LastMethodSuccess = True) Then
Debug.WriteLine("AWS request ID: " & value)
End If
End If
' Full messages, headers, and signing diagnostics may contain private data.
Exit Sub
End If
If (success <> True) Then
Debug.WriteLine("Expected a well-formed XML response.")
Exit Sub
End If
stringCompare.SetString(xml.Tag)
Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("SetSubscriptionAttributesResponse",True)
If (stringMatch6 <> True) Then
Debug.WriteLine("Unexpected SNS response element.")
Exit Sub
End If
value = xml.GetChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("",True)
If ((xml.LastMethodSuccess <> True) Or (stringMatch7 = True)) Then
Debug.WriteLine("Missing or empty ResponseMetadata|RequestId.")
Exit Sub
End If
Debug.WriteLine("AWS request ID: " & value)
success = rest.ClearAllQueryParams()
If (success <> True) Then
Debug.WriteLine("Could not clear parameters from the previous request.")
Exit Sub
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","GetSubscriptionAttributes")
If (success <> True) Then
Debug.WriteLine("Could not set Action.")
Exit Sub
End If
success = rest.AddQueryParam("Version","2010-03-31")
If (success <> True) Then
Debug.WriteLine("Could not set Version.")
Exit Sub
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
Debug.WriteLine("Could not set X-Amz-Security-Token.")
Exit Sub
End If
End If
success = rest.AddQueryParam("SubscriptionArn",subscriptionArn)
If (success <> True) Then
Debug.WriteLine("Could not set SubscriptionArn.")
Exit Sub
End If
responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> True) Then
Debug.WriteLine("Request did not complete. Inspect diagnostics privately.")
Exit Sub
End If
success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
Debug.WriteLine("SNS HTTP status: " & rest.ResponseStatusCode)
If (success = True) Then
value = xml.GetChildContent("Error|Code")
If (xml.LastMethodSuccess = True) Then
Debug.WriteLine("AWS error code: " & value)
End If
value = xml.GetChildContent("RequestId")
If (xml.LastMethodSuccess = True) Then
Debug.WriteLine("AWS request ID: " & value)
End If
End If
' Full messages, headers, and signing diagnostics may contain private data.
Exit Sub
End If
If (success <> True) Then
Debug.WriteLine("Expected a well-formed XML response.")
Exit Sub
End If
stringCompare.SetString(xml.Tag)
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("GetSubscriptionAttributesResponse",True)
If (stringMatch8 <> True) Then
Debug.WriteLine("Unexpected SNS response element.")
Exit Sub
End If
value = xml.GetChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
Dim stringMatch9 As Boolean = stringCompare.ContentsEqual("",True)
If ((xml.LastMethodSuccess <> True) Or (stringMatch9 = True)) Then
Debug.WriteLine("Missing or empty ResponseMetadata|RequestId.")
Exit Sub
End If
Debug.WriteLine("AWS request ID: " & value)
If (xml.HasChildWithTag("GetSubscriptionAttributesResult") <> True) Then
Debug.WriteLine("Missing result.")
Exit Sub
End If
Dim attributes As New Chilkat.JsonObject
Dim mapIndex As Integer = 0
While (mapIndex < xml.NumChildrenAt("GetSubscriptionAttributesResult|Attributes"))
xml.I = mapIndex
value = xml.GetChildContent("GetSubscriptionAttributesResult|Attributes|entry[i]|key")
stringCompare.SetString(value)
Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("",True)
If ((xml.LastMethodSuccess <> True) Or (stringMatch10 = True)) Then
Debug.WriteLine("Missing or empty GetSubscriptionAttributesResult|Attributes|entry[i]|key.")
Exit Sub
End If
Dim mapKey As String = value
value = xml.GetChildContent("GetSubscriptionAttributesResult|Attributes|entry[i]|value")
If (xml.LastMethodSuccess <> True) Then
Debug.WriteLine("Missing map value.")
Exit Sub
End If
success = attributes.AppendString(mapKey,value)
If (success <> True) Then
Debug.WriteLine("Invalid or duplicate map entry.")
Exit Sub
End If
mapIndex = mapIndex + 1
End While
Debug.WriteLine("FilterPolicyScope: " & attributes.StringOf("FilterPolicyScope"))
Debug.WriteLine("FilterPolicy: " & attributes.StringOf("FilterPolicy"))
Debug.WriteLine("Example completed.")