Rust SDK

Setup & Initialization

  1. Add Dependencies:
cargo add dotenv   # Manage environment variables
cargo add reqwest   # HTTP client for making requests
cargo add tokio --features full  # Required for Async runtime
cargo add serde --features derive # JSON conversion
  1. Configure Cargo.toml:

    Enable the JSON feature for reqwest in your Cargo.toml file:

reqwest = { version = "0.12.15", features = ["json"] }
  1. Set Up Environment Variables:

Add your credentials to your .env file in your project root:

CLIENT_ID=your_client_id
CLIENT_SECRET=your_client_secret
  1. Initialize and Send Notification:
use reqwest::Client;
use serde::Serialize;
use std::env;
use dotenv::dotenv;

#[derive(Serialize)]
struct NotificationPayload<'a> {
    #[serde(rename = "type")]
    notification_type: &'a str,
    to: User,
    #[serde(rename = "parameters")]
    parameters: Parameters<'a>,
}

#[derive(Serialize)]
struct User {
    id: String,
    email: String,
    number: String,
}

#[derive(Serialize)]
struct Parameters<'a> {
    item: &'a str,
    address: &'a str,
    orderId: &'a str,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize environment variables
    dotenv().ok();
    let client_id = env::var("CLIENT_ID").expect("CLIENT_ID not set in .env file");
    let client_secret = env::var("CLIENT_SECRET").expect("CLIENT_SECRET not set in .env file");

    // Create HTTP client
    let client = Client::new();

    // Prepare notification payload
    let payload = NotificationPayload {
        notification_type: "order_tracking",
        to: User {
            id: "spongebob.squarepants".to_string(),
            email: "spongebob@squarepants.com".to_string(),
            number: "+15005550006".to_string()
        },
        parameters: Parameters {
            item: "Krabby Patty Burger",
            address: "124 Conch Street",
            orderId: "1234567890",
        },
    };

    // Send notification
    let response = client
        .post("https://api.notificationapi.com/{client_id}/sender")
        .basic_auth(client_id, Some(client_secret))
        .json(&payload)
        .send()
        .await?;

    // Check the response status
    if response.status().is_success() {
        println!("Notification sent successfully!");
    } else {
        println!("Failed to send notification: {:?}", response.text().await?);
    }

    Ok(())
}
NameTypeDescription
CLIENT_ID*stringYour NotificationAPI account clientId. You can get it from here.
CLIENT_SECRET*stringYour NotificationAPI account client secret. You can get it from here.
base_url*stringTo choose a different region other than default (https://api.notificationapi.com). Use https://api.ca.notificationapi.com for the Canada region and https://api.eu.notificationapi.com for the EU region.

* required

Region specific example:

let response = client
    .post("https://api.eu.notificationapi.com/{client_id}/sender")
    .basic_auth(client_id, Some(client_secret))
    .json(&payload)
    .send()
    .await?;

Send

Used to send a notification to the specified user.

Pass content directly without templates

You can ignore the templates and pass the content directly through the API by specifying channel content objects on the request.

use reqwest::Client;
use serde::Serialize;
use std::env;
use dotenv::dotenv;

#[derive(Serialize)]
struct NotificationPayload<'a> {
    #[serde(rename = "type")]
    notification_type: &'a str,
    to: User,
    #[serde(rename = "parameters")]
    parameters: Parameters<'a>,
}

#[derive(Serialize)]
struct User {
    id: String,
    email: String,
    number: String,
}

#[derive(Serialize)]
struct Parameters<'a> {
    item: &'a str,
    address: &'a str,
    orderId: &'a str,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize environment variables
    dotenv().ok();
    let client_id = env::var("CLIENT_ID").expect("CLIENT_ID not set in .env file");
    let client_secret = env::var("CLIENT_SECRET").expect("CLIENT_SECRET not set in .env file");

    // Create HTTP client
    let client = Client::new();

    // Prepare notification payload
    let payload = NotificationPayload {
        notification_type: "order_tracking",
        to: User {
            id: "spongebob.squarepants".to_string(),
            email: "spongebob@squarepants.com".to_string(),
            number: "+15005550006".to_string()
        },
        parameters: Parameters {
            item: "Krabby Patty Burger",
            address: "124 Conch Street",
            orderId: "1234567890",
        },
    };

    // Send notification
    let response = client
        .post("https://api.notificationapi.com/{client_id}/sender")
        .basic_auth(client_id, Some(client_secret))
        .json(&payload)
        .send()
        .await?;

    // Check the response status
    if response.status().is_success() {
        println!("Notification sent successfully!");
    } else {
        println!("Failed to send notification: {:?}", response.text().await?);
    }

    Ok(())
}

Parameters

The send() method accepts an object with the following fields:

NameTypeDescription
type*stringThe ID of the notification you wish to send. You can find this value from the dashboard.
to*objectThe user to send the notification to.
to.id*stringThe ID of the user in your system. Required. This is the only user field required for sending in-app, web push, and mobile push notifications.
to.emailstringRequired for sending email notifications, otherwise optional.
to.numberstringRequired for SMS/CALL notifications, otherwise optional. Valid format: +15005550006. Unformatted US/Canada numbers are also accepted, e.g., (415) 555-1212, 415-555-1212, or 4155551212.
to.timezonestringThe user’s timezone. Timezone names correspond to the Zone and Link names of the IANA Time Zone Database, such as ‘America/New_York’, ‘America/Denver’, ‘EST’, and ‘UTC’.
parametersobjectUsed to pass in dynamic values into the notification design. Read more: Dynamic Parameters (Merge Tags)
schedulestringAn ISO 8601 datetime string to schedule the notification for. For example, 2024-02-20T14:38:03.509Z. Read more: Scheduling
replaceobject, string key/value pairSimilar to parameters, but more flexible. Like the programmatic string replace function, this parameter will replace any string in the notification templates with another string. This operation happens on the fly when sending the notification and does not actually modify the templates.
This operation is case-sensitive and happens after parameters are injected.
subNotificationIdstringTo break down your notification into multiple categories or groups. Read more: Sub Notifications
templateIdstringBy default, notifications are sent using the default template of each channel. You can permanently change the default template from the dashboard. However, you can also use this parameter to force using a specific template. This is useful in multiple situations:
- Design variation: using different wording and design, e.g. “You have new updates” vs. “You don’t have any updates”
- White-labeling: using a specific template that you designed for a white-labeled customer
- Language: creating and using multiple templates for multiple languages
If the provided templateId does not exist for a channel, the default template will be used, and a warning message will be generated.
forceChannels (deprecated)string[]Used to override the channels which are used for the notification. This field only overrides the notification’s channels configuration. It does not override the user preferences.
Values available for use are:
EMAIL, INAPP_WEB, SMS, CALL, PUSH, WEB_PUSH
E.g. forceChannels: ["EMAIL", "SMS"]
optionsobjectFor configuring additional options
emailobjectOverride the email template by providing the complete email content. When provided, this will replace the dashboard template for the email channel.
email.subject*stringThe email subject line. Required when using email override.
email.html*stringThe HTML content of the email. Required when using email override.
email.previewTextstringThe email preview text that appears in email clients.
email.senderNamestringThe sender name for the email.
email.senderEmailstringThe sender email address.
smsobjectOverride the SMS template by providing the complete SMS content. When provided, this will replace the dashboard template for the SMS channel.
sms.message*stringThe SMS message content. Required when using SMS override.
sms.autoReplyobjectConfigure automatic reply to inbound SMS messages. See Inbound Messages for details.
sms.autoReply.message*stringThe auto-reply message to send when a recipient replies to your SMS. Sent once per recipient phone number per account. Opt-out keywords (STOP, CANCEL, etc.) skip auto-reply.
inappobjectOverride the in-app notification template by providing the complete in-app content. When provided, this will replace the dashboard template for the in-app channel.
inapp.title*stringThe in-app notification title. Required when using in-app override.
inapp.urlstringThe URL to navigate to when the in-app notification is clicked.
inapp.imagestringThe image URL for the in-app notification.
callobjectOverride the call notification template by providing the complete call content. When provided, this will replace the dashboard template for the call channel.
call.message*stringThe call message content. Required when using call override.
web_pushobjectOverride the web push notification template by providing the complete web push content. When provided, this will replace the dashboard template for the web push channel.
web_push.title*stringThe web push notification title. Required when using web push override.
web_push.message*stringThe web push notification message. Required when using web push override.
web_push.iconstringThe icon URL for the web push notification.
web_push.urlstringThe URL to navigate to when the web push notification is clicked.
mobile_pushobjectOverride the mobile push notification template by providing the complete mobile push content. When provided, this will replace the dashboard template for the mobile push channel.
mobile_push.title*stringThe mobile push notification title. Required when using mobile push override.
mobile_push.message*stringThe mobile push notification message. Required when using mobile push override.
slackobjectOverride the Slack notification template by providing the complete Slack content. When provided, this will replace the dashboard template for the Slack channel.
slack.text*stringThe Slack message text. Required when using Slack override.
slack.blocksobject[]Slack Block Kit blocks for rich formatting. Optional when using Slack override.

Options Object

NameTypeDescription
emailobjectEmail options features.
email.replyToAddressesstring[]

An array of email addresses that will receive responses when recipients reply to the notification email. This enables two-way email communication, allowing recipients to respond directly to notifications.

email.ccAddressesstring[]An array of emails to be CC’ed on the email notifications.
email.bccAddressesstring[]An array of emails to be BCC’ed on the email notifications.
email.fromNamestringA string to display as the “From” field in an email.
email.fromAddressstring

An email address to send the email from. To use a custom email.fromAddress from your domain, you must verify your domain in your NotificationAPI dashboard. Read more: Domain Verification

email.attachments

Array<{ filename: string; url: string } | { filename: string; content: string; contentType?: string }>

An array of attachments. Each attachment must be either URL-based OR base64 content-based (mutually exclusive). The API validates this using a oneOf schema. The URLs only need to be valid for a few minutes after calling the SDK method and can be invalidated afterwards for privacy. The maximum email size (including the content and all attachments) is 25MB. Provide file extensions in filename for better UX on recipient devices.

apnobjectAdditional Apple push notification options.
apn.expirynumber

The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately.

apn.prioritynumber

The priority of the notification. If you omit this header, APNs sets the notification priority to 10. Specify 10 to send the notification immediately. Specify 5 to send the notification based on power considerations on the user’s device. Specify 1 to prioritize the device’s power considerations over all other factors for delivery, and prevent awakening the device.

apn.collapseIdstring

An identifier you use to merge multiple notifications into a single notification for the user. Typically, each notification request displays a new notification on the user’s device. When sending the same notification more than once, use the same value in this header to merge the requests. The value of this key must not exceed 64 bytes.

apn.threadIdstring

Provide this key with a string value that represents the app-specific identifier for grouping notifications. If you provide a Notification Content app extension, you can use this value to group your notifications together. For local notifications, this key corresponds to the threadIdentifier property of the UNNotificationContent object.

apn.badgenumber

Include this key when you want the system to modify the badge of your app icon. If this key is not included in the dictionary, the badge is not changed. To remove the badge, set the value of this key to 0.

apn.soundstring

Include this key when you want the system to play a sound. The value of this key is the name of a sound file in your app’s main bundle or in the Library/Sounds folder of your app’s data container. If the sound file cannot be found, or if you specify default for the value, the system plays the default alert sound. For details about providing sound files for notifications; see

here

.

apn.contentAvailableboolean

Include this key with a value of 1 to configure a background update notification. When this key is present, the system wakes up your app in the background and delivers the notification to its app delegate. For information about configuring and handling background update notifications, see

here

.

fcmobjectAdditional Firebase Cloud Messaging push notification options.
fcm.androidobjectAdditional Android push notification options.
fcm.android.collapseKeystring

This parameter identifies a group of messages (e.g., with collapse_key: “Updates Available”) that can be collapsed, so that only the last message gets sent when delivery can be resumed. This is intended to avoid sending too many of the same messages when the device comes back online or becomes active. Note that there is no guarantee of the order in which messages get sent. Note: A maximum of 4 different collapse keys is allowed at any given time. This means a FCM connection server can simultaneously store 4 different send-to-sync messages per client app. If you exceed this number, there is no guarantee which 4 collapse keys the FCM connection server will keep.

fcm.android.prioritystring

Sets the priority of the message. Valid values are normal and high. On iOS, these correspond to APNs priorities 5 and 10. By default, notification messages are sent with high priority, and data messages are sent with normal priority. Normal priority optimizes the client app’s battery consumption and should be used unless immediate delivery is required. For messages with normal priority, the app may receive the message with unspecified delay. When a message is sent with high priority, it is sent immediately, and the app can wake a sleeping device and open a network connection to your server.

fcm.android.ttlstring

This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline. The maximum time to live supported is 4 weeks, and the default value is 4 weeks. For more information, see

Setting the lifespan of a message

.

INFO

To use a custom fromAddress from your domain, you’ll need to verify your domain first. See your NotificationAPI dashboard for Domain Verification setup instructions. We strongly recommend you to verify your domain before sending emails from production.

Size Limitation

When using parameters (merge tags) in the body of your notifications, it is recommended that the size of the combined parameters not exceed 150 KB. Exceeding this limit may result in delivery failure, or an API error.