Amazon Simple Notification Service
Developer Guide (API Version 2010-03-31)

Amazon SNS Message Attributes

Amazon Simple Notification Service (Amazon SNS) supports delivery of message attributes. Message attributes allow you to provide structured metadata items (such as time stamps, geospatial data, signatures, and identifiers) about the message. Message attributes are optional and separate from, but sent along with, the message body. This information can be used by the receiver of the message to help decide how to handle the message without having to first process the message body. Each message can have up to 10 attributes. To specify message attributes, you can use the AWS software development kits (SDKs) or query API.

Important

To use message attributes with Amazon SQS endpoints, you must set the subscription attribute, Raw Message Delivery, to True. For more information about raw message delivery, see Amazon SNS Large Payload and Raw Message Delivery.

Message attributes are sent only when the message structure is String, not JSON.

You can also use message attributes to help structure the push notification message for mobile endpoints. In this scenario, the message attributes are only used to help structure the push notification message. The attributes are not delivered to the endpoint, as they are when sending messages with message attributes to Amazon SQS endpoints.

You can also use message attributes to make your messages filterable with subscription filter policies. You apply filter policies to topic subscriptions. With a filter policy applied, a subscription receives only those messages that have attributes that are accepted by the policy. For more information, see .

Message Attribute Items and Validation

Each message attribute consists of the following items:

  • Name – The message attribute name can contain the following characters: A-Z, a-z, 0-9, underscore(_), hyphen(-), and period (.). The name must not start or end with a period, and it should not have successive periods. The name is case-sensitive and must be unique among all attribute names for the message. The name can be up to 256 characters long. The name cannot start with "AWS." or "Amazon." (or any variations in casing) because these prefixes are reserved for use by Amazon Web Services.

  • Type – The supported message attribute data types are String, String.Array, Number, and Binary. The data type has the same restrictions on the content as the message body. The data type is case-sensitive, and it can be up to 256 bytes long. For more information, see the Message Attribute Data Types and Validation section.

  • Value – The user-specified message attribute value. For string data types, the value attribute has the same restrictions on the content as the message body. For more information, see the Publish action in the Amazon Simple Notification Service API Reference.

Name, type, and value must not be empty or null. In addition, the message body should not be empty or null. All parts of the message attribute, including name, type, and value, are included in the message size restriction, which is 256 KB.

Message Attribute Data Types and Validation

Message attribute data types identify how the message attribute values are handled by Amazon SNS. For example, if the type is a number, Amazon SNS validates that it's a number.

Amazon SNS supports the following logical data types:

  • String – Strings are Unicode with UTF-8 binary encoding. For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters.

  • String.Array – An array, formatted as a string, that can contain multiple values. The values can be strings, numbers, or the keywords true, false, and null.

  • Number – Numbers are positive or negative integers or floating-point numbers. Numbers have sufficient range and precision to encompass most of the possible values that integers, floats, and doubles typically support. A number can have a value from -109 to 109, with 5 digits of accuracy after the decimal point. Leading and trailing zeroes are trimmed.

  • Binary – Binary type attributes can store any binary data; for example, compressed data, encrypted data, or images.

Reserved Message Attributes for Mobile Push Notifications

The following table lists the reserved message attributes for mobile push notification services that you can use to structure your push notification message:

Push Notification Service Reserved Message Attribute Allowed Values

Baidu

AWS.SNS.MOBILE.BAIDU.DeployStatus (optional)

AWS.SNS.MOBILE.BAIDU.MessageType (optional)

AWS.SNS.MOBILE.BAIDU.MessageKey (optional)

1—development environment. 2—production environment. (default 1)

0—in-app message. 1—alert notification. (default 1)

A short message identifier you can attach to your message

MPNS

AWS.SNS.MOBILE.MPNS.Type (required)

AWS.SNS.MOBILE.MPNS.NotificationClass (required)

token (for tile notifications), toast, raw

real time, priority, regular

WNS

AWS.SNS.MOBILE.WNS.Type (required)

AWS.SNS.MOBILE.WNS.CachePolicy (optional)

AWS.SNS.MOBILE.WNS.Group (optional)

AWS.SNS.MOBILE.WNS.Match (optional)

AWS.SNS.MOBILE.WNS.SuppressPopup (optional)

AWS.SNS.MOBILE.WNS.Tag (optional)

same as X-WNS-Type

same as X-WNS-Cache-Policy

same as X-WNS-Group

same as X-WNS-Match

same as X-WNS-SuppressPopup

same as X-WNS-Tag

For more information about using message attributes with Baidu, see Using Message Attributes for Structuring the Message.

Applying Message Attributes

You can publish a message with attributes by using the Amazon SNS console. Or, to apply message attributes programmatically, you can use the API, the AWS Command Line Interface (AWS CLI), or any AWS SDK that supports Amazon SNS, such as the AWS SDK for Java.

Applying Message Attributes with the Console

Complete the following steps to publish a message with attributes by using the Amazon SNS console:

  1. Sign in to the AWS Management Console and open the Amazon SNS console at https://console.aws.amazon.com/sns/v2/home.

  2. In the navigation pane, choose Topics. The Topics page provides all of the Amazon SNS topics that you have in the selected region.

  3. If you don't have a topic, choose Create a new topic, and provide a value for Topic name. If you want to use the topic to send SMS messages, provide a value for Display name. Then, choose Create topic.

  4. If you have one or more topics, select the topic to which you want to publish the message. Then, choose Publish to topic.

  5. On the Publish a message page, provide a Subject and Message.

  6. For Message Attributes, specify the key, attribute type, and value. For example, the following entry creates an attribute named customer_interests. The attribute type is String.Array, and the value is an array of values.

    
                            Message attributes in the Amazon SNS console.

    If the attribute type is String, String.Array, or Number, Amazon SNS evaluates the message attribute against a subscription's filter policy, if present, before sending the message to that subscription.

    Remember

    If the attribute type is String.Array, enclose the array in brackets ([ ]). Within the array, enclose string values in double quotes. You don't need quotes for numbers or for the keywords true, false, and null.

Applying Message Attributes with the AWS CLI

To publish a message with attributes using the AWS CLI, use the publish command with the --message-attributes parameter, as shown in the following example:

$ aws sns publish --topic-arn topic-arn --message “message” --message-attributes '{"store":{"DataType":"String","StringValue":"example_corp"}}'

Applying Message Attributes with the AWS SDKs

The following examples show how to apply message attributes by using the Amazon SNS clients that are provided by the AWS SDKs.

AWS SDK for JavaAWS SDK for .NET
AWS SDK for Java

To publish a message with attributes using the AWS SDK for Java, use the publish method of the AmazonSNS client. Provide a PublishRequest object as the argument. When you initialize the PublishRequest object, use its withMessageAttributes method, which accepts a map of type Map<String,MessageAttributeValue>.

To simplify the process of publishing messages with attributes, you can add the following example class to your application and modify it as needed:

import com.amazonaws.services.sns.*; import com.amazonaws.services.sns.model.MessageAttributeValue; import com.amazonaws.services.sns.model.PublishRequest; import com.amazonaws.services.sns.model.PublishResult; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; public class SNSMessage { public String message; public Map<String, MessageAttributeValue> messageAttributes; public SNSMessage(String message) { this.message = message; messageAttributes = new HashMap<>(); } public void setMessage(String message) { this.message = message; } public String getMessage() { return message; } public void addAttribute(String attributeName, String attributeValue) { MessageAttributeValue messageAttributeValue = new MessageAttributeValue() .withDataType("String") .withStringValue(attributeValue); messageAttributes.put(attributeName, messageAttributeValue); } public void addAttribute(String attributeName, ArrayList<?> attributeValues) { String valuesString, delimiter = ", ", prefix = "[", suffix = "]"; if (attributeValues.get(0).getClass() == String.class) { delimiter = "\", \""; prefix = "[\""; suffix = "\"]"; } valuesString = attributeValues .stream() .map(value -> value.toString()) .collect(Collectors.joining(delimiter, prefix, suffix)); MessageAttributeValue messageAttributeValue = new MessageAttributeValue() .withDataType("String.Array") .withStringValue(valuesString); messageAttributes.put(attributeName, messageAttributeValue); } public void addAttribute(String attributeName, Number attributeValue) { MessageAttributeValue messageAttributeValue = new MessageAttributeValue() .withDataType("Number") .withStringValue(attributeValue.toString()); messageAttributes.put(attributeName, messageAttributeValue); } public String publish(AmazonSNS snsClient, String topicArn) { PublishRequest request = new PublishRequest(topicArn, message) .withMessageAttributes(messageAttributes); PublishResult result = snsClient.publish(request); return result.getMessageId(); } }

This class stores a messageAttributes field as a map. You use the overloaded addAttribute methods to add attributes to your message. These methods can add attributes with the data type String, String.Array, or Number. When you're ready to publish your message, use the publish method, and provide an AmazonSNS client and topic ARN.

The following code shows how to initialize and use the example SNSMessage class:

// Initialize example message class SNSMessage message = new SNSMessage(messageBody); // Add message attribute with string value message.addAttribute("store", "example_corp"); message.addAttribute("event", "order_placed"); // Add message attribute with a list of string values ArrayList<String> interestsValues = new ArrayList<String>(); interestsValues.add("soccer"); interestsValues.add("rugby"); interestsValues.add("hockey"); message.addAttribute("customer_interests", interestsValues); // Add message attribute with number value message.addAttribute("price_usd", 1000); // Add boolean attribute for filtering with subscription filter policies. // SNSMessage will apply a String.Array data type to this attribute, // which makes it eligible for evaluating with a filter policy. ArrayList<Boolean> encryptedVal = new ArrayList<Boolean>(); encryptedVal.add(false); message.addAttribute("encrypted", encryptedVal); // Publish message message.publish(snsClient, topicArn);
AWS SDK for .NET

To publish a message with attributes using the AWS SDK for .NET, use the Publish method of the AmazonSimpleNotificationServiceClient client. Provide a PublishRequest object as the argument. When you initialize the PublishRequest object, use its MessageAttributes method, which accepts a Dictionary of type Map<String,MessageAttributeValue>.

To simplify the process of publishing messages with attributes, you can add the following example class to your application and modify it as needed:

using System; using System.Collections.Generic; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; namespace SNSCreatePlatformEndpoint { class SNSMessage { private String message; private Dictionary<String, MessageAttributeValue> messageAttributes; public SNSMessage(String message) { this.message = message; messageAttributes = new Dictionary<string, MessageAttributeValue>(); } public string Message { get => this.message; set => this.message = value; } public void AddAttribute(String attributeName, String attributeValue) { messageAttributes[attributeName] = new MessageAttributeValue { DataType = "String", StringValue = attributeValue }; } public void AddAttribute(String attributeName, float attributeValue) { messageAttributes[attributeName] = new MessageAttributeValue { DataType = "Number", StringValue = attributeValue.ToString()}; } public void AddAttribute(String attributeName, int attributeValue) { messageAttributes[attributeName] = new MessageAttributeValue { DataType = "Number", StringValue = attributeValue.ToString() }; } public void AddAttribute(String attributeName, List<String> attributeValue) { String valueString = "[\"" + String.Join("\", \"", attributeValue.ToArray()) + "\"]"; messageAttributes[attributeName] = new MessageAttributeValue { DataType = "String.Array", StringValue = valueString }; } public void AddAttribute(String attributeName, List<float> attributeValue) { String valueString = "[" + String.Join(", ", attributeValue.ToArray()) + "]"; messageAttributes[attributeName] = new MessageAttributeValue { DataType = "String.Array", StringValue = valueString }; } public void AddAttribute(String attributeName, List<int> attributeValue) { String valueString = "[" + String.Join(", ", attributeValue.ToArray()) + "]"; messageAttributes[attributeName] = new MessageAttributeValue { DataType = "String.Array", StringValue = valueString }; } public void AddAttribute(String attributeName, List<Boolean> attributeValue) { String valueString = "[" + String.Join(", ", attributeValue.ToArray()) + "]"; messageAttributes[attributeName] = new MessageAttributeValue { DataType = "String.Array", StringValue = valueString }; } public String Publish(AmazonSimpleNotificationServiceClient snsClient, String topicArn) { PublishRequest request = new PublishRequest { TopicArn = topicArn, MessageAttributes = messageAttributes, Message = message }; PublishResponse result = snsClient.Publish(request); return result.MessageId; } } }

This class stores a MessageAttributes field as a dictionary. You use the overloaded AddAttribute methods to add attributes to your message. These methods can add attributes with the data type String, String.Array, or Number. When you're ready to publish your message, use the publish method, and provide an AmazonSimpleNotificationServiceClient client and topic ARN.

The following code shows how to initialize and use the example SNSMessage class:

AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USWest2); // Initialize example message class SNSMessage message = new SNSMessage(messageBody); // Add message attribute with string value message.AddAttribute("store", "example_corp"); message.AddAttribute("event", "order_placed"); // Add message attribute with a list of string values List<String> interestsValues = new List<String>(); interestsValues.Add("soccer"); interestsValues.Add("rugby"); interestsValues.Add("hockey"); message.AddAttribute("customer_interests", interestsValues); // Add message attribute with number value message.AddAttribute("price_usd", 1000); // Add boolean attribute for filtering with subscription filter policies. // SNSMessage will apply a String.Array data type to this attribute, // which makes it eligible for evaluating with a filter policy. List<Boolean> encryptedVal = new List<Boolean>(); encryptedVal.Add(false); message.AddAttribute("encrypted", encryptedVal); // Publish message message.Publish(snsClient, topicArn);

Applying Message Attributes with the Amazon SNS API

To publish a message with attributes using the Amazon SNS API, issue a request to the Publish action and use the MessageAttributes parameter.