Rust SDK
Setup & Initialization
- 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
-
Configure Cargo.toml:
Enable the JSON feature for reqwest in your Cargo.toml file:
reqwest = { version = "0.12.15", features = ["json"] }
- 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
- 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(())
}
| Name | Type | Description |
|---|---|---|
CLIENT_ID* | string | Your NotificationAPI account clientId. You can get it from here. |
CLIENT_SECRET* | string | Your NotificationAPI account client secret. You can get it from here. |
base_url* | string | To 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:
| Name | Type | Description |
|---|---|---|
type* | string | The ID of the notification you wish to send. You can find this value from the dashboard. |
to* | object | The user to send the notification to. |
to.id* | string | The 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.email | string | Required for sending email notifications, otherwise optional. |
to.number | string | Required 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.timezone | string | The 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’. |
parameters | object | Used to pass in dynamic values into the notification design. Read more: Dynamic Parameters (Merge Tags) |
schedule | string | An ISO 8601 datetime string to schedule the notification for. For example, 2024-02-20T14:38:03.509Z. Read more: Scheduling |
replace | object, string key/value pair | Similar 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. |
subNotificationId | string | To break down your notification into multiple categories or groups. Read more: Sub Notifications |
templateId | string | By 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"] |
options | object | For configuring additional options |
email | object | Override the email template by providing the complete email content. When provided, this will replace the dashboard template for the email channel. |
email.subject* | string | The email subject line. Required when using email override. |
email.html* | string | The HTML content of the email. Required when using email override. |
email.previewText | string | The email preview text that appears in email clients. |
email.senderName | string | The sender name for the email. |
email.senderEmail | string | The sender email address. |
sms | object | Override the SMS template by providing the complete SMS content. When provided, this will replace the dashboard template for the SMS channel. |
sms.message* | string | The SMS message content. Required when using SMS override. |
sms.autoReply | object | Configure automatic reply to inbound SMS messages. See Inbound Messages for details. |
sms.autoReply.message* | string | The 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. |
inapp | object | Override 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* | string | The in-app notification title. Required when using in-app override. |
inapp.url | string | The URL to navigate to when the in-app notification is clicked. |
inapp.image | string | The image URL for the in-app notification. |
call | object | Override the call notification template by providing the complete call content. When provided, this will replace the dashboard template for the call channel. |
call.message* | string | The call message content. Required when using call override. |
web_push | object | Override 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* | string | The web push notification title. Required when using web push override. |
web_push.message* | string | The web push notification message. Required when using web push override. |
web_push.icon | string | The icon URL for the web push notification. |
web_push.url | string | The URL to navigate to when the web push notification is clicked. |
mobile_push | object | Override 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* | string | The mobile push notification title. Required when using mobile push override. |
mobile_push.message* | string | The mobile push notification message. Required when using mobile push override. |
slack | object | Override the Slack notification template by providing the complete Slack content. When provided, this will replace the dashboard template for the Slack channel. |
slack.text* | string | The Slack message text. Required when using Slack override. |
slack.blocks | object[] | Slack Block Kit blocks for rich formatting. Optional when using Slack override. |
Options Object
| Name | Type | Description |
|---|---|---|
email | object | Email options features. |
email.replyToAddresses | string[] | 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.ccAddresses | string[] | An array of emails to be CC’ed on the email notifications. |
email.bccAddresses | string[] | An array of emails to be BCC’ed on the email notifications. |
email.fromName | string | A string to display as the “From” field in an email. |
email.fromAddress | string | An email address to send the email from. To use a custom
|
email.attachments | | An array of attachments. Each attachment must be either URL-based OR
base64 content-based (mutually exclusive). The API validates this using
a |
apn | object | Additional Apple push notification options. |
apn.expiry | number | 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.priority | number | 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.collapseId | string | 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.threadId | string | 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.badge | number | 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.sound | string | 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 here . |
apn.contentAvailable | boolean | 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 . |
fcm | object | Additional Firebase Cloud Messaging push notification options. |
fcm.android | object | Additional Android push notification options. |
fcm.android.collapseKey | string | This parameter identifies a group of messages (e.g., with
|
fcm.android.priority | string | Sets the priority of the message. Valid values are |
fcm.android.ttl | string | 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 . |
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.