# Setting and removing attributes

Setting and removing attributes varies per attribute type. Setting attributes on named users is recommended.

For predefined and custom attributes, [add them to your project](https://www.airship.com/docs/guides/audience/attributes/adding/) before setting them on your audience. Otherwise, setting those attributes will result in an error.

No setup is required for default and NPS survey attributes. You can go straight to [Targeting your audience using attributes](https://www.airship.com/docs/guides/audience/attributes/targeting/). Similarly, attributes from [Zero-copy data integration](https://www.airship.com/docs/guides/features/data-integration/zero-copy-data-integration/) are available for targeting once Airship completes your project configuration.

## Channels versus named users

You can set attributes on channels and named users, however their inheritance of attributes varies:

* **Channels inherit from named users** — All the channels associated with a named user will also bear the named users's attributes. When you remove a channel from a named user, Airship removes attributes set on the named user from that channel.

   Using the example `favorite_movie` attribute `contains` the value `jaws`, if you store the `favorite_movie` attribute at the named user level, you can target all contacts who are fans of Jaws movies over any of their channels. You can keep your audience up to date on Jaws-related news, no matter which channels they use to communicate with you.
   
<center>**Attributes at the named user level can be used to target any channel associated with a named user:**
</center>
```mermaid
graph LR
A[Named user<br>with attributes]
B[Attribute Selector]
subgraph Audience
C[App Message]
D[SMS]
E[Web Notification]
end
A --> B
B -.-> C
B -.-> D
B -.-> E
```


* **Named users do not inherit from channels** — Any attribute set for a channel will not also be set for an associated named user.

   If you store the `favorite_movie` attribute at the channel level, you can only target fans of Jaws movies on the specific channels bearing the `favorite_movie` attribute, limiting the scope of Jaws-related communications.

<center>**Attributes at the channel level are limited to that channel:**
</center>
```mermaid
graph LR
   A[App Channel<br>with Attributes]
   B[Attribute Selector]
   subgraph Audience
   C[App Message]
   D[SMS]
   E[Web Push]
   end
   A --> B -.-> C
```


In general, we recommend that you store attributes at the named user level so you can take advantage of your attributes across any of your users' channels. This helps you build and maintain a cohesive relationship with your audience. Setting attributes at the channel level limits the scope of the attribute to that channel and can also limit your flexibility when targeting audiences.

---

Named users also inherit a few [default attributes](https://www.airship.com/docs/reference/data-collection/attributes/#default-attributes) from the last channel that was associated with them, helping keep your named users up to date with scheduling and locale information.

These attributes appear in the `user_attributes` object:

| Default attribute | Description | Example |
| --- | --- | --- |
| ua_local_tz | The user's time zone | America/Los_Angeles |
| ua_country | The user's ISO 3166 two-character country code | US |
| ua_language | The user's ISO 639-1 two-character language code | en |

## Required delay before setting attribute values

<p>After adding attributes, allow at least 10 minutes before setting their values. This delay ensures proper processing of the attributes within Airship.</p>

## Attributes list retention and deletion

An attributes list has the same retention behavior whether uploaded in the Airship dashboard, using SFTP, or using the [Attribute Lists API](https://www.airship.com/docs/developer/rest-api/ua/operations/attribute-lists/).

<p>Airship automatically deletes a list and all its versions after 90 days of inactivity. The following timestamps are used to calculate the 90-day period:</p>
<ul>
<li>Creation date</li>
<li>New version uploaded</li>
</ul>
<p>The creation date is the initial day one of the 90-day period. Each instance of uploading a new version resets the timestamp to day one.</p>

After deletion, the list is removed from the upload history and is no longer visible in the Airship dashboard or through API calls. Deletion does not affect the project state. For example, if you use an attribute list that adds Attribute A to a channel, Attribute A will still exist on the channel after list deletion.

## Storing survey responses

Store responses to single choice questions in [Scenes](https://www.airship.com/docs/reference/glossary/#scene) as attributes. See the [Question content element](https://www.airship.com/docs/guides/messaging/editors/scenes/elements/#question) in *Configuring Scene content*.

## Setting and removing Text, Number, and Date attributes

You can set and remove Text, Number, and Date attributes using dashboard upload, SFTP, the SDKs, or APIs.

Use these formats when setting each attribute type:

| Type | Format |
| --- | --- |
| **Text** | String. When setting Text attributes using a CSV, you do not need to wrap the value in quotes. |
| **Number** | Number, float value, or string |
| **Date** | ISO 8601 date-time formatted string: `YYYY-MM-DDTHH:MM:SS`. Set an offset by appending the date-time with `+HH:MM`. For example, `2020-07-20T12:35:42+08:00`. |

### CSV upload

Set or remove attributes for [channel](https://www.airship.com/docs/reference/glossary/#channel_term) IDs, [named user](https://www.airship.com/docs/reference/glossary/#named_user) IDs, email addresses, or MSISDNs by uploading a CSV file in the dashboard or over SFTP. You cannot mix identifier types. When using email or SMS identifiers, Airship registers new channels for addresses or MSISDN/sender combinations that are new to your project. All values in CSV uploads, including numbers, are represented as strings and cannot be used with [math helpers](https://www.airship.com/docs/guides/personalization/handlebars/math-helpers/).

When you upload your file, you must select a type that determines how empty values in attribute columns are handled:

|  | Attributes | Attributes Snapshot |
| --- | --- | --- |
| **Handling of empty/null values** | Empty or null values are ignored, preserving any existing attribute values not explicitly set in the CSV. | Empty or null values trigger removing those attributes from the user. |
| **Primary use case** | This mode is useful for making partial updates to a user's attributes without affecting others. | This mode is useful for synchronizing attribute states with external systems, ensuring the attributes in the CSV exactly match the user's attributes. |

#### Prepare your file

To see a sample formatted file, go to **Audience**, then **Attributes**, then **Upload Attribute Data**. Select each upload type, and then select the download link.

Format a CSV file using the following requirements:

| Requirement | Value |
| --- | --- |
| **File size** | Up to 1.5 GB |
| **Row count** | Up to 10 million |
| **Encoding** | UTF-8 without BOM |
| **Header** | The first column's header must be one of `channel_id`, `named_user`, `email_address`, or `msisdn`. For SMS, the second column header must be `sms_sender`. Add attribute headers to the right of the identifier and any opt-in columns. For example, `email_address,ua_commercial_opted_in,fav_food,age`. |
| **Row format** | `identifier`, then attribute values, one row per identifier. For SMS, use `identifier,sender_ID`, then attribute values. MSISDN values must not include a leading zero. One attribute per cell. |
| **Attribute fields** | Up to 100 |
| **Date attributes** | ISO 8601 date-time format: `YYYY-MM-DDTHH:MM:SS`. Set an offset by appending `+HH:MM`. |

<p>Add opt-in status fields with <a href="https://www.airship.com/docs/developer/rest-api/ua/introduction/#date-time-format">date-time values</a> for email and SMS so you can send to newly created channels:</p>
<ul>
<li>SMS: <code>ua_opted_in</code></li>
<li>Email:
<ul>
<li><code>ua_commercial_opted_in</code> or <code>ua_commercial_opted_out</code> — Opted-in and opted-out dates are mutually exclusive. Providing both in the same row is invalid.</li>
<li><code>ua_transactional_opted_in</code> or <code>ua_transactional_opted_out</code> — Follow the same mutually exclusive rule as commercial dates.</li>
<li><code>ua_open_tracking_opted_in</code> or <code>ua_open_tracking_opted_out</code> — By default, new channels are opted in to open and click tracking. Opt out by setting an opted-out date. Opt back in with an opted-in date that is newer than the opted-out date. Providing both dates in the same row is invalid.</li>
<li><code>ua_click_tracking_opted_in</code> or <code>ua_click_tracking_opted_out</code> — Follow the same rules as open tracking.</li>
</ul>
</li>
</ul>
<p>To set the suppression state for email channels, use the <code>ua_email_suppression_state</code> field with value <code>BOUNCE</code>, <code>SPAM_COMPLAINT</code>, <code>COMMERCIAL_SPAM_COMPLAINT</code>, or <code>IMPORTED</code>.</p>

To set the time zone for email channels, use the `timezone` field with an IANA time zone database value, for example, `America/Los_Angeles`.

**Example CSV using channel IDs**

```text
channel_id,fav_food,age,birthdate
<id1>,pizza,18,2002-05-05T00:00:00
<id2>,burgers,22,1998-06-12T00:00:00
<id3>,sushi,27,1993-03-04T00:00:00
```


**Example CSV using email addresses**

```text
email_address,ua_commercial_opted_in,fav_food,age,birthdate
brandy@example.com,2022-01-01T18:45:30,burger,18,2004-05-05T00:00:00
jake@example.com,2022-01-01T12:45:30,sushi,22,2000-06-12T00:00:00
```


**Example CSV using MSISDNs**

```text
msisdn,sms_sender,ua_opted_in,fav_food,age,birthdate
14155550123,12345,2020-05-05T10:34:22,tacos,18,2002-05-05T00:00:00
12025550123,12345,2020-05-05T12:03:45,pizza,22,1998-06-12T00:00:00
```


#### Upload your file

See [SFTP upload for CSV files](https://www.airship.com/docs/guides/audience/tools/sftp-upload/), or complete these steps to upload in the dashboard:

1. Go to **Audience**, then **Attributes**, then **Upload Attribute Data**.
1. For **Upload Type**, select which file type you prepared, [Attributes CSV or Attributes Snapshot CSV](#csv-upload).
1. Select **Choose file** and select your file.
1. Select **Upload**.

To see your upload and SFTP transfer status, select **Upload History**. See [View upload history](https://www.airship.com/docs/guides/audience/attributes/adding/#view-upload-history) in *Adding attributes to your project*.

### SDK

To set or remove attributes on a channel or a contact, use the channel or contact classes in our SDKs:

* **iOS** —  [Contact](https://urbanairship.github.io/ios-library/v20/AirshipCore/documentation/airshipcore/airshipcontact)
, [Channel](https://urbanairship.github.io/ios-library/v20/AirshipCore/documentation/airshipcore/airshipchannel)

* **Android** — [Channel](https://urbanairship.github.io/android-library/urbanairship-core/com.urbanairship.channel/-airship-channel/index.html), [Contact](https://urbanairship.github.io/android-library/urbanairship-core/com.urbanairship.contacts/-contact/index.html)
* **Web** — [Channel](https://www.airship.com/docs/reference/libraries/web-notify-sdk/v2-latest/UaSDK.Channel.html#editAttributes), [Contact](https://www.airship.com/docs/reference/libraries/web-notify-sdk/v2-latest/UaSDK.Contact.html#editAttributes)

The code examples below show how to set attributes using the provided methods. See the
[SDK docs](https://www.airship.com/docs/sdk-topics/attributes/) for more details.


#### Android Java


```java
Airship.getChannel().editAttributes()
            .setAttribute("average_rating", 4.99)
            .setAttribute("last_product_purchased", "A1234567")
            .removeAttribute("purchase_pending")
            .apply();
```



#### iOS Swift


```swift
Airship.channel.editAttributes { editor in
    editor.set(string: "cauldron", attribute: "last_product_purchased")
    editor.set(number: 4.99, attribute: "average_rating")
    editor.remove("purchase_pending")
}
```



#### iOS Objective-C


```obj-c
[UAirship.channel editAttributes:^(UAAttributesEditor * editor) {
    [editor setString:@"cauldron" attribute:@"last_product_purchased"];
    [editor setNumber:@(4.99) attribute:@"average_rating"];
    [editor removeAttribute:@"purchase_pending"];
}];
```




**Setting attributes for Web**

```js
const editor = channel.editAttributes()
await editor
   .set("my_attribute", "some_value")
   .remove("other_attribute")
   .apply()
```


### API

You can set attribute values from external sources, such as a CRM or data warehouse:

* To set attributes on a single channel or named user, use [Set or remove attributes on channels](https://www.airship.com/docs/developer/rest-api/ua/operations/channels/#modifychannelattributes) or [Set or remove attributes on named user](https://www.airship.com/docs/developer/rest-api/ua/operations/named-users/#modifynameduserattributes). Use `set` or `remove` for the `action` value, and use the attribute ID as the `key` value.
* To set attributes on many channels or named users at once, use the [Attribute Lists API](https://www.airship.com/docs/developer/rest-api/ua/operations/attribute-lists/) to upload a CSV.

**Setting two attributes on a channel and removing another**

```http
POST /api/channels/attributes HTTP/1.1
Authorization: Basic <App Auth>
Accept: application/vnd.urbanairship+json; version=3
Content-Type: application/json

{
    "audience": {
        "ios_channel": "b8f9b663-0a3b-cf45-587a-be880946e881"
    },
    "attributes": [
        {
            "action": "set",
            "key": "favorite_movie",
            "value": "jaws_3_d",
            "timestamp": "2019-09-19 12:00:00"
        },
        {
            "action": "remove",
            "key": "favorite_color",
            "timestamp": "2019-09-19 12:00:00"
        },
        {
            "action": "set",
            "key": "first_name",
            "value": "Roger",
            "timestamp": "2019-09-19 12:00:00"
        }
    ]
}
```


**Setting two attributes on a named user and removing another**

```http
POST /api/named_users/my_named_user/attributes HTTP/1.1
Authorization: Basic <master authorization string>
Accept: application/vnd.urbanairship+json; version=3
Content-Type: application/json

{
    "attributes": [
        {
            "action": "set",
            "key": "firstName",
            "value": "Gyuri",
            "timestamp": "2020-09-19 12:00:00"
        },
        {
            "action": "remove",
            "key": "birthDate",
            "timestamp": "2020-09-19 12:00:00"
        },
        {
            "action": "set",
            "key": "lastName",
            "value": "Pataki",
            "timestamp": "2020-09-19 12:00:00"
        }
    ]
}
```


## Setting and removing JSON attributes

You can set and remove JSON attributes on a channel or a contact using the App and Web SDKs or APIs.

### SDK

[iOS SDK 19.3+](/docs/docs/developer/sdk-integration/apple/ios-changelog/#19.3.0) [Android SDK 19.6+](/docs/docs/developer/sdk-integration/android/changelog/#19.6.0)

The code examples below show how to set JSON attributes using the provided methods.


#### Android Kotlin


```kotlin
Airship.contact.editAttributes {
    setAttribute(
        attribute = "attribute_name",
        instanceId = "instance_id",
        expiration = Instant.now(),
        json = jsonMapOf(
            "key" to "value",
            "another_key" to "another_value"
        )
    )
}
```



#### iOS Swift


```swift
Airship.contact.editAttributes { editor in
    try! editor.set(
        json: [
            "key": .string("value"),
            "another_key": .string("another_value")
        ],
        attribute: "attribute_name",
        instanceID: "instance_id",
        expiration: Date.now
    )
}
```




**Setting JSON attributes for Web**

```js
const contact = await sdk.contact
const editor = await contact.editAttributes()
const nowInSeconds = Math.floor(Date.now() / 1000)

await editor
  .set("attribute_name#instance_id", {
     key: "value", 
     another_key: "another_value", 
     exp: nowInSeconds 
    }
  )
  .apply()
```


### API

Set or remove JSON attributes using the Channels and Named Users APIs:

* [Set or remove attributes on channels](https://www.airship.com/docs/developer/rest-api/ua/operations/channels/#modifychannelattributes)
* [Set or remove attributes on named user](https://www.airship.com/docs/developer/rest-api/ua/operations/named-users/#modifynameduserattributes)

Use `set` or `remove` for the `action` value. Set the key value as `<attribute_ID>#<instance_ID>`. Instance IDs:
   * Can contain letters, numbers, and underscores only
   * Must begin with a letter
   * Must end with a letter or number
   * Are limited to 31 characters maximum
   * Are case-sensitive

For more information, see [JSON attributes](https://www.airship.com/docs/guides/audience/attributes/about/#json-attributes) in *About attributes*.

In the examples below we are using the attribute ID `reservations` and instance ID `a001`.

**Setting a JSON attribute on a channel**

```http
POST /api/channels/attributes HTTP/1.1
Authorization: Basic <App Auth>
Accept: application/vnd.urbanairship+json; version=3
Content-Type: application/json

{
    "audience": {
        "ios_channel": "b31cf3ab-f33e-46ae-b874-782facda2bab"
    },
    "attributes": [
        {
            "action": "set",
            "key": "reservations#a001",
            "value": {
                "flights": [
                    {
                        "departs": {
                            "port": "PDX",
                            "time": "2023-12-01T05:09:00"
                        },
                        "arrives": {
                            "port": "LAX",
                            "time": "2023-12-01T07:09:00"
                        }
                    },
                    {
                        "departs": {
                            "port": "LAX",
                            "time": "2023-12-08T12:30:00"
                        },
                        "arrives": {
                            "port": "PDX",
                            "time": "2023-12-08T14:45:00"
                        }
                    }
                ]
            }
        }
    ]
}
```


**Setting the four different types of attributes on a named user**

```http
POST /api/named_users/my_named_user/attributes HTTP/1.1
Authorization: Basic <master authorization string>
Accept: application/vnd.urbanairship+json; version=3
Content-Type: application/json

{
    "attributes": [
        {
            "action": "set",
            "key": "favorite_food",
            "value": "cake"
        },
        {
            "action": "set",
            "key": "age",
            "value": 35
        },
        {
            "action": "set",
            "key": "birthdate",
            "value": "1985-07-14T00:00:00"
        },
        {
            "action": "set",
            "key": "flights#id123",
            "value": {
                "recordID": 123,
                "flightsInfo": [
                    {
                        "departureTime": "2024-07-14T12:35:42+08:00",
                        "flightId": "LY205",
                        "destinationAirportCode": "PDX",
                        "originAirportCode": "LAX"
                    },
                    {
                        "departureTime": "2024-14-14T12:00:00+08:00",
                        "flightId": "LY315",
                        "destinationAirportCode": "LAX",
                        "originAirportCode": "PDX"
                    }
                ]
            }
        }
    ]
}
```

