Nuxtstop

For all things nuxt.js

How to Send Push Notifications with the OneSignal REST API

0 0

How to Send Push Notifications with the OneSignal REST API

It’s no secret that push notifications can help you engage and retain app users. In this tutorial, we'll 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 supers API calls, then you can use the OneSignal REST API.

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 Notification 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.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
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

Setup your NodeJS App

The first thing you need to do is to create an 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';
Enter fullscreen mode Exit fullscreen mode

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 ONE SIGNAL API KEY";
const ONE_SIGNAL_APP_ID = "YOUR ONE SIGNAL APP ID";
const BASE_URL = "https://onesignal.com/api/v1";
Enter fullscreen mode Exit fullscreen mode

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 S _ ettings _ tab.

How to Send Push Notifications with the OneSignal REST API

On this page, click on Keys & IDs.

How to Send Push Notifications with the OneSignal REST API

Copy the OneSignal App ID and the REST API KEY.

How to Send Push Notifications with the OneSignal REST API

Note: Another quick and easy way to access your OneSignal App ID is by copying it from the URL.

How to Send Push Notifications with the OneSignal REST API

Options Builder

This 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:

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
    };
}
Enter fullscreen mode Exit fullscreen mode

Create Notification

Create a push notification and send it to the users of your app.

Method: POST

Endpoint: https://onesignal.com/api/v1/notifications

Postman Collection

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Here’s a sample body object:

const body = {
    app_id: ONE_SIGNAL_APP_ID,
    included_segments: ['Subscribed Users'],
    data: {
        foo: 'bar',
    },
    contents: {
        en: 'Sample Push Message',
    },
};
Enter fullscreen mode Exit fullscreen mode

View Notification

Create a push notification and send it to the users of your app.

Method: GET

Endpoint: https://onesignal.com/api/v1/notifications

Postman Collection

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 {string} notificationId
const viewNotifcation = async (notificationId) => {
    const path = `notifications/${notificationId}?  app_id=${ONE_SIGNAL_APP_ID}`;
        const options = optionsBuilder("get", path);
    try {
        const response = await axios(options);
        console.log(response.data);
    } catch (error) {
        console.log(error);
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Feel free to test other OneSignal REST API endpoints and let us know what you think!

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.