It’s no secret that push notifications can help you engage and retain app users. This tutorial will show you how to use the OneSignal REST API using NodeJS.
Using the OneSignal REST API is very useful because it can help you integrate OneSignal into different workflows that your applications may have. The OneSignal REST API is friendly with different technologies, including front and backend. Basically, if the tech stack you are using supports API calls, then you can use the OneSignal REST API.
Useful Resources:
OneSignal & Your Browser's Push API
The Push API gives applications the ability to receive messages from a server whether or not the app is in the foreground or currently loaded on a user agent. This lets you deliver asynchronous notifications and updates to users who opt-in, resulting in better engagement with timely new content.
This tutorial will cover an overview of our OneSignal REST API reference and the usage of our API with a NodeJS server.
Guide Overview
- Part 1: OneSignal REST API Overview
- REST API reference - Part 2: Push Notifications In NodeJS
- Setup a NodeJS Application
- Send Push Notifications
- View Notification insights
This tutorial requires some basic knowledge of NodeJS and usage of REST APIs. Below is a list of platforms that I'm using:
- App with OneSignal integrated (mobile, web, or game)
- NPM
- I’m using NPM version v6.14.11
- NodeJS
- I’m using NodeJS v16.14.2
Part 1: OneSignal REST API Overview
Send Notifications
The OneSignal Push API allows you to programmatically send push notifications. The push notifications can be sent to different segments (by default you send them to all Subscribed Users) and even specific devices using the User ID. Another cool feature of the OneSignal REST API is the ability to cancel notifications that have been scheduled.
View Notification
One of my favorite endpoints to use with the OneSignal REST API is the view notification endpoint. This endpoint allows you to gather information about the notifications and outcomes associated with them. For example, the returned data can tell you see the number of notifications that have not been sent out, the number of notifications that got delivered, the number of confirmed deliveries, and much more information. If you want to learn more about all the data returned by this endpoint visit our rest API reference.
Method: POST
Endpoint: https://onesignal.mydomain.com/api/v1/notifications
Our API can do a lot more than just send a notification and view data from that notification. If you want to learn more about our whole REST API, visit the OneSignal REST API overview page.
Creating Your NodeJS App
Inside your terminal run the following commands to create a new NodeJS project using NPM:
npm init
After entering the previous npm command, answer all the questions that will appear on your terminal. These questions will generate the values of your package.json
.
Your package.json file will look like similar to this:
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
“type”: “module”,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Part 2: Push Notifications In NodeJS
The first thing you need to do is to create a index.js
file. This file will contain all code necessary to send and view your notifications.
At the top of this file, add the request npm package. This package will help us make API calls to the OneSignal endpoints in an easier way than doing it with NodeJS natively.
import axios from 'axios';
Now, run npm install axios
to add the axios
npm package into your project. After you have installed the axios
NPM package, add the following three variables to your index.js after the axios
import:
const API_KEY = "YOUR ONESIGNAL API KEY";
const ONESIGNAL_APP_ID = "YOUR ONESIGNAL APP ID";
const BASE_URL = "https://onesignal.mydomain.com/api/v1";
To get the API Key and the App ID from OneSignal, navigate to the OneSignal Dashboard and click on the app you created inside of OneSignal. Once you have selected the app you want to work with, click the Settings tab.
On this page, click on Keys & IDs.
Copy the OneSignal App ID and the REST API Key.
Note: Another quick and easy way to access your OneSignal App ID is by copying it from the URL.
Options Builder
This is a helper function created for this code sample. This helper function is not mandatory in order to use the OneSignal REST API. This function will be in charge of creating the options that you will pass to your API calls. This is a generic function that will build the JSON object based on the parameters that you have passed.
Parameters:
- @param {string} method
- @param {string} path
- @param {object} body
Returns:
- @returns {object} options
const optionsBuilder = (method, path, body) => {
return {
method,
'url': `${BASE_URL}/${path}`,
'headers': {
'Content-Type': 'application/json',
'Authorization': `Basic ${API_KEY}`,
},
body: body ? JSON.stringify(body) : null
};
}
Create Notification
Create a push notification and send it to the users of your app.
Method: POST
Endpoint: https://onesignal.mydomain.com/api/v1/notifications
Postman collection: Create notification
To send a push notification, you will add the following function that will make a call to the OneSignal REST API. This function takes a body parameter that represents the information that the push notification will contain.
Parameters:
- @param {object} body
- @returns {object} response
const createNotication = async (data) => {
const options = optionsBuilder("post","notifications", data);
try {
const response = await axios(options);
return response.data;
} catch (error) {
console.error(error);
return error;
}
}
Here’s a sample body object:
const body = {
app_id: ONESIGNAL_APP_ID,
included_segments: ['Subscribed Users'],
data: {
foo: 'bar',
},
contents: {
en: 'Sample Push Message',
},
};
View Notification
After you have sent a notification, view the notification information and outcomes associated with it using the notification id.
Method: GET
Endpoint: https://onesignal.mydomain.com/api/v1/notifications/:id?app_id=:app_id
Postman collection: View notification
To view a notification's information, you will add the following function that will make a call to the OneSignal REST API. This function takes a notification Id that represents the notification you have previously sent.
Parameters:
- @param {string} notificationId
const viewNotifcation = async (notificationId) => {
const path = `notifications/${notificationId}?app_id=${ONESIGNAL_APP_ID}`;
const options = optionsBuilder("get", path);
try {
const response = await axios(options);
console.log(response.data);
} catch (error) {
console.log(error);
}
}
Run Your Code
At the end of the file, add the following lines of code. The first createNotification()
function will return the notification's basic information when you send push notifications. I’m using this function to call the OneSignal API. As you can see, I’m using object destructuring to grab the notification ID from the notification object returned from the createNotification()
, that will be used to call the viewNotifcation()
function.
const {id} = await createNotication(body);
await viewNotifcation(id);
Feel free to test other OneSignal REST API endpoints and let us know what you think! This REST API is not limited to NodeJS. The OneSignal REST API can be used with any programming language that can make REST API calls.
If you want to dive directly into the code, don't forget to check the GitHub repo with the NodeJS code sample.
Join the OneSignal Developers Community
Want to learn more about the OneSignal products and other technologies? Join our OneSignal Developers Community!
The OneSignal Developer community is a group of passionate individuals who work with OneSignal products. Community members have the opportunity to expand their network and knowledge across different technologies.
Stay Connected
Follow our OneSignal Developers Twitter to learn more about the OneSignal product, technical tips, and the latest events from our developers.
The OneSignal Developer community gathers on our public chat server, available on Discord. Our Discord server is a safe environment to network with other members, ask questions, and learn from each other. It is also a place to engage with the OneSignal product development team.
Join our Discord Server