[Yandex Cloud documentation](../../index.md) > [Yandex Cloud Notification Service](../index.md) > [Tools](index.md) > AWS SDK for Kotlin

# How to get started with the AWS SDK for Kotlin in Yandex Cloud Notification Service

{% note info %}

The service is at the [preview stage](../../overview/concepts/launch-stages.md).

{% endnote %}

To get started with the AWS SDK for Kotlin:

1. [Get your cloud ready](#before-you-begin).
1. [Get a static access key](#static-key).
1. [Configure the AWS SDK](#aws-sdk).
1. [Create a notification channel](#create-channel).
1. [Get a list of channels](#list-channel).
1. [Create an endpoint](#create-endpoint).
1. [Send a notification](#publish).


## Get your cloud ready {#before-you-begin}

Sign up for Yandex Cloud and create a [billing account](../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../billing/quickstart/index.md) and [link](../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../resource-manager/concepts/resources-hierarchy.md).


## Get a static access key {#static-key}

For authentication in Cloud Notification Service, use a [static access key](../../iam/concepts/authorization/access-key.md). The key is issued for the [service account](../../iam/concepts/users/service-accounts.md), and all actions are performed on behalf of that service account.

To get a static access key:
1. [Create](../../iam/operations/sa/create.md) a service account.
1. [Assign](../../iam/operations/sa/assign-role-for-sa.md) the `editor` [role](../../iam/roles-reference.md#editor) for the folder to the service account.
1. [Create](../../iam/operations/authentication/manage-access-keys.md#create-access-key) a static access key for the service account.

    Save the ID and secret key.


## Configure the AWS SDK {#aws-sdk}

You can find the prerequisites and an AWS SDK for Kotlin installation guide in the relevant [AWS documentation](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup-basic-onetime-setup.html#setup-overview).

To work with RuStore Android notifications, see [this RuStore SDK article](https://www.rustore.ru/help/sdk/push-notifications/kotlin-java/6-5-0).

### Get your OS ready {#prepare-os}

1. Install Java 8 or higher, e.g., [Oracle Java SE Development Kit](https://www.oracle.com/java/technologies/downloads/). For other JDKs you can use with the AWS SDK, see the [AWS developer guide](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup-basic-onetime-setup.html#setup-envtools).
1. Install [Gradle](https://gradle.org/install/).


### Create a project {#create-project}

1. Create a new project:

    1. Run this command:

        ```shell
        gradle init --type kotlin-application --dsl kotlin
        ```

    1. Select the default value for each message by pressing **Enter** in interactive mode.

1. Add dependencies to the `settings.gradle.kts` file in the project root:

    ```text
    dependencyResolutionManagement {
        repositories {
            mavenCentral()
        }
    
        versionCatalogs {
            create("awssdk") {
                from("aws.sdk.kotlin:version-catalog:1.4.0")
            }
        }
    }
    ```

   You can replace `1.4.0` with the [latest version of the SDK for Kotlin](https://github.com/awslabs/aws-sdk-kotlin/releases).

1. Paste the following code to the `gradle/libs.versions.toml` file:

    ```text
    [versions]
    junit-jupiter-engine = "5.10.3"
    
    [libraries]
    junit-jupiter-engine = { module = "org.junit.jupiter:junit-jupiter-engine", version.ref = "junit-jupiter-engine" }
    
    [plugins]
    kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version = "2.1.0" }
    ```

1. Paste the following code to the `app/build.gradle.kts` file:

    ```text
    plugins {
        alias(libs.plugins.kotlin.jvm)
        application
    }
    
    
    dependencies {
        implementation(awssdk.services.sns) // Add dependency on the AWS SDK for Kotlin's SNS client.
    
        testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
        testImplementation(libs.junit.jupiter.engine)
        testRuntimeOnly("org.junit.platform:junit-platform-launcher")
    }
    
    java {
        toolchain {
            languageVersion = JavaLanguageVersion.of(21)
        }
    }
    
    application {
        mainClass = "org.example.AppKt"
    }
    
    tasks.named<Test>("test") {
        useJUnitPlatform()
    }
    ```

1. Create a client in the `app/src/main/kotlin/org/example/App.kt` file:

    ```kotlin
    package org.example
    
    import aws.sdk.kotlin.services.sns.SnsClient
    import aws.smithy.kotlin.runtime.net.url.Url
    import aws.sdk.kotlin.runtime.auth.credentials.StaticCredentialsProvider
    import aws.smithy.kotlin.runtime.auth.awscredentials.Credentials
    
    import kotlinx.coroutines.runBlocking
    
    suspend fun main(): Unit = runBlocking {
        val snsClient = SnsClient {
            region = "ru-central1"; endpointUrl =
            Url.parse("https://notifications.yandexcloud.net/"); credentialsProvider =
            StaticCredentialsProvider(
                Credentials(
                    "<static_key_ID>",
                    "<secret_key>"
                )
            )
        }
    
        // Use snsClient
    }
    ```

    Where `credentialsProvider` contains the static key ID and secret key.

1. To start the project, run this command:

    ```bash
    gradle run
    ```


## Create a notification channel {#create-channel}

1. Import the classes:

    ```kotlin
    import aws.sdk.kotlin.services.sns.model.CreatePlatformApplicationRequest
    ```

1. Run the following code:

    ```kotlin
    snsClient.use {
        val response = snsClient.createPlatformApplication(CreatePlatformApplicationRequest {
            name = "<channel_name>"
            platform = "<platform_type>"
            attributes = mapOf("<authentication_type>" to "<key>")
        })
        println("Platform application ARN: ${response.platformApplicationArn}")
    }
    ```

    Where:

    * `name`: Notification channel name, user-defined.

        The name must be unique throughout CNS. Once the channel is created, you will not be able to change the name. The name may contain lowercase and uppercase Latin letters, numbers, underscores, hyphens, and periods. It must be from 1 to 256 characters long. For APNs channels, we recommend specifying the bundle ID in the name; for FCM and HMS, the full package name; for RuStore, `packageName`.

    * `platform`: Mobile platform type:

        * `APNS` and `APNS_SANDBOX`: Apple Push Notification service (APNs). Use `APNS_SANDBOX` to test the application.
        * `GCM`: Firebase Cloud Messaging (FCM).
        * `HMS`: Huawei Mobile Services (HMS).
        * `RUSTORE`: RuStore Android.

    * `attributes`: Mobile platform authentication parameters in `key=value` format. The values depend on the platform:

        * APNs:
        
            * Token-based authentication:
        
                * `PlatformPrincipal`: Path to the token signature key file from Apple
                * `PlatformCredential`: Key ID
                * `ApplePlatformTeamID`: Team ID
                * `ApplePlatformBundleID`: Bundle ID
        
            * Certificate-based authentication:
        
                * `PlatformPrincipal`: SSL certificate in `.pem` format
                * `PlatformCredential`: Certificate private key in `.pem` format
        
                    To save the certificate and the private key in individual `.pem` files, use the [openssl](https://docs.openssl.org/1.1.1/man1/pkcs12) Linux utility:
                    
                    ```bash
                    openssl pkcs12 -in Certificates.p12 -nokeys -nodes -out certificate.pem
                    openssl pkcs12 -in Certificates.p12 -nocerts -nodes -out privatekey.pem
                    ```
        
            Token-based authentication: The more modern and secure method.
        
        * FCM: `PlatformCredential` is the Google Cloud service account key in JSON format for authentication with the HTTP v1 API or API key (server key) for authentication with the legacy API.
        
            Use the HTTP v1 API because the [FCM legacy API is no longer supported](https://firebase.google.com/docs/cloud-messaging/migrate-v1) starting July 2024.
        
        * HMS:
        
            * `PlatformPrincipal`: Key ID
            * `PlatformCredential`: API key

    As a result, you will get a notification channel ID (ARN).


## Get a list of notification channels {#list-channel}

1. Import the classes:

    ```kotlin
    import aws.sdk.kotlin.services.sns.model.ListPlatformApplicationsRequest
    ```

1. Run the following code:

    ```kotlin
    snsClient.use {
        val response = snsClient.listPlatformApplications(ListPlatformApplicationsRequest {})
        response.platformApplications?.forEach { app ->
            println("Application ARN: ${app.platformApplicationArn}")
        }
    }
    ```

    You will get the list of notification channels located in the same folder as the service account.


## Create an endpoint {#create-endpoint}

1. Import the classes:

    ```kotlin
    import aws.sdk.kotlin.services.sns.model.CreatePlatformEndpointRequest
    ```

1. Run the following code:

    ```kotlin
    snsClient.use {
        val response = snsClient.createPlatformEndpoint(CreatePlatformEndpointRequest {
            platformApplicationArn = "<notification_channel_ARN>"
            token = "<push_token>"
        })
        println("Endpoint ARN: ${response.endpointArn}")
    }
    ```

    Where:

    * `platformApplicationArn`: Notification channel ID (ARN).
    * `token`: Unique push token for the application on the user’s device.


## Send a notification {#publish}

### Explicit notifications (Bright Push) {#bright-push}

1. Import the classes:

    ```kotlin
    import aws.sdk.kotlin.services.sns.model.PublishRequest
    ```

1. Run the following code:

    {% list tabs %}

    - Apple iOS (APNs)

      ```kotlin
      snsClient.use {
          val response = snsClient.publish(PublishRequest {
              targetArn = "<endpoint_ARN>"
              message = "{\"default\": \"<notification_text>\", \"APNS\": \"{\\\"aps\\\": {\\\"alert\\\": \\\"<notification_text>\\\"}}\"}"
              messageStructure = "json"
          })
          println("Message id: ${response.messageId}")
      }
      ```

    - Google Android (GCM)

      ```kotlin
      snsClient.use {
          val response = snsClient.publish(PublishRequest {
              targetArn = "<endpoint_ARN>"
              message = "{\"default\": \"<notification_text>\", \"GCM\": \"{\\\"notification\\\": {\\\"body\\\": \\\"<notification_text>\\\"}}\"}"
              messageStructure = "json"
          })
          println("Message id: ${response.messageId}")
      }
      ```

    {% endlist %}

    Where:

    * `targetArn`: Mobile endpoint ARN.
    * `message`: Message.
    * `messageStructure`: Message format.


### Silent notifications (Silent Push) {#silent-push}

1. Import the classes:

    ```kotlin
    import aws.sdk.kotlin.services.sns.model.PublishRequest
    ```

1. Run the following code:

    {% list tabs %}

    - Apple iOS (APNs)

      ```kotlin
      snsClient.use {
          val response = snsClient.publish(PublishRequest {
              targetArn = "<endpoint_ARN>"
              message = "{\"default\": \"<notification_text>\", \"APNS\": \"{\\\"key\\\": \\\"value\\\"}\"}"
              messageStructure = "json"
          })
          println("Message id: ${response.messageId}")
      }
      ```

    - Google Android (GCM)

      ```kotlin
      snsClient.use {
          val response = snsClient.publish(PublishRequest {
              targetArn = "<endpoint_ARN>"
              message = "{\"default\": \"<notification_text>\", \"GCM\": \"{\\\"data\\\": {\\\"key\\\": \\\"value\\\"}}\"}"
              messageStructure = "json"
          })
          println("Message id: ${response.messageId}")
      }
      ```

    {% endlist %}

    Where:

    * `targetArn`: Mobile endpoint ARN.
    * `message`: Message.
    * `messageStructure`: Message format.


### Text message {#sms-messages}

1. Import the classes:

    ```kotlin
    import aws.sdk.kotlin.services.sns.model.PublishRequest
    import aws.sdk.kotlin.services.sns.model.MessageAttributeValue
    ```

1. Run the following code:

    ```kotlin
    snsClient.use {
        val response = snsClient.publish(PublishRequest {
            phoneNumber = "<phone_number>"
            message = "<notification_text>"
            messageAttributes = mapOf("AWS.SNS.SMS.SenderID" to MessageAttributeValue {
                dataType = "String"; stringValue = "<text_name_of_sender>"
            })
        })
        println("Message id: ${response.messageId}")
    }
    ```

    Where:

    * `phoneNumber`: Recipient's phone number
    * `message`: Notification text
    * `stringValue`: Sender's text name


## Useful links {#see-also}

* [Getting started](../quickstart.md)
* [AWS CLI](aws-cli.md)
* [Concepts](../concepts/index.md)
* [AWS developer guide](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/get-started.html)